diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..0c4c30240c --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,22 @@ +{ + "name": "T3 Code Dev", + "image": "debian:bookworm", + "features": { + "ghcr.io/devcontainers-extra/features/bun:1": {}, + "ghcr.io/devcontainers/features/node:1": { + "version": "24", + "nodeGypDependencies": true + }, + "ghcr.io/devcontainers/features/python:1": { + "version": "3.12" + } + }, + "postCreateCommand": { + "bun-install": "bun install --backend=copyfile --frozen-lockfile" + }, + "customizations": { + "vscode": { + "extensions": ["oxc.oxc-vscode"] + } + } +} diff --git a/.docs/remote-architecture.md b/.docs/remote-architecture.md new file mode 100644 index 0000000000..32e35d7caf --- /dev/null +++ b/.docs/remote-architecture.md @@ -0,0 +1,302 @@ +# Remote Architecture + +This document describes the target architecture for first-class remote environments in T3 Code. + +It is intentionally architecture-first. It does not define a complete implementation plan or user-facing rollout checklist. The goal is to establish the core model so remote support can be added without another broad rewrite. + +## Goals + +- Treat remote environments as first-class product primitives, not special cases. +- Support multiple ways to reach the same environment. +- Keep the T3 server as the execution boundary. +- Let desktop, mobile, and web all share the same conceptual model. +- Avoid introducing a local control plane unless product pressure proves it is necessary. + +## Non-goals + +- Replacing the existing WebSocket server boundary with a custom transport protocol. +- Making SSH the only remote story. +- Syncing provider auth across machines. +- Shipping every access method in the first iteration. + +## High-level architecture + +T3 already has a clean runtime boundary: the client talks to a T3 server over HTTP/WebSocket, and the server owns orchestration, providers, terminals, git, and filesystem operations. + +Remote support should preserve that boundary. + +```text +┌──────────────────────────────────────────────┐ +│ Client (desktop / mobile / web) │ +│ │ +│ - known environments │ +│ - connection manager │ +│ - environment-aware routing │ +└───────────────┬──────────────────────────────┘ + │ + │ resolves one access endpoint + │ +┌───────────────▼──────────────────────────────┐ +│ Access method │ +│ │ +│ - direct ws / wss │ +│ - tunneled ws / wss │ +│ - desktop-managed ssh bootstrap + forward │ +└───────────────┬──────────────────────────────┘ + │ + │ connects to one T3 server + │ +┌───────────────▼──────────────────────────────┐ +│ Execution environment = one T3 server │ +│ │ +│ - environment identity │ +│ - provider state │ +│ - projects / threads / terminals │ +│ - git / filesystem / process runtime │ +└──────────────────────────────────────────────┘ +``` + +The important decision is that remoteness is expressed at the environment connection layer, not by splitting the T3 runtime itself. + +## Domain model + +### ExecutionEnvironment + +An `ExecutionEnvironment` is one running T3 server instance. + +It is the unit that owns: + +- provider availability and auth state +- model availability +- projects and threads +- terminal processes +- filesystem access +- git operations +- server settings + +It is identified by a stable `environmentId`. + +This is the shared cross-client primitive. Desktop, mobile, and web should all reason about the same concept here. + +### KnownEnvironment + +A `KnownEnvironment` is a client-side saved entry for an environment the client knows how to reach. + +It is not server-authored. It is local to a device or client profile. + +Examples: + +- a saved LAN URL +- a saved public `wss://` endpoint +- a desktop-managed SSH host entry +- a saved tunneled environment + +A known environment may or may not know the target `environmentId` before first successful connect. + +### AccessEndpoint + +An `AccessEndpoint` is one concrete way to reach a known environment. + +This is the key abstraction that keeps SSH from taking over the model. + +A single environment may have many endpoints: + +- `wss://t3.example.com` +- `ws://10.0.0.25:3773` +- a tunneled relay URL +- a desktop-managed SSH tunnel that resolves to a local forwarded WebSocket URL + +The environment stays the same. Only the access path changes. + +### RepositoryIdentity + +`RepositoryIdentity` remains a best-effort logical repo grouping mechanism across environments. + +It is not used for routing. It is only used for UI grouping and correlation between local and remote clones of the same repository. + +### Workspace / Project + +The current `Project` model remains environment-local. + +That means: + +- a local clone and a remote clone are different projects +- they may share a `RepositoryIdentity` +- threads still bind to one project in one environment + +## Access methods + +Access methods answer one question: + +How does the client speak WebSocket to a T3 server? + +They do not answer: + +- how the server got started +- who manages the server process +- whether the environment is local or remote + +### 1. Direct WebSocket access + +Examples: + +- `ws://10.0.0.15:3773` +- `wss://t3.example.com` + +This is the base model and should be the first-class default. + +Benefits: + +- works for desktop, mobile, and web +- no client-specific process management required +- best fit for hosted or self-managed remote T3 deployments + +### 2. Tunneled WebSocket access + +Examples: + +- public relay URLs +- private network relay URLs +- local tunnel products such as pipenet + +This is still direct WebSocket access from the client's perspective. The difference is that the route is mediated by a tunnel or relay. + +For T3, tunnels are best modeled as another `AccessEndpoint`, not as a different kind of environment. + +This is especially useful when: + +- the host is behind NAT +- inbound ports are unavailable +- mobile must reach a desktop-hosted environment +- a machine should be reachable without exposing raw LAN or public ports + +### 3. Desktop-managed SSH access + +SSH is an access and launch helper, not a separate environment type. + +The desktop main process can use SSH to: + +- reach a machine +- probe it +- launch or reuse a remote T3 server +- establish a local port forward + +After that, the renderer should still connect using an ordinary WebSocket URL against the forwarded local port. + +This keeps the renderer transport model consistent with every other access method. + +## Launch methods + +Launch methods answer a different question: + +How does a T3 server come to exist on the target machine? + +Launch and access should stay separate in the design. + +### 1. Pre-existing server + +The simplest launch method is no launch at all. + +The user or operator already runs T3 on the target machine, and the client connects through a direct or tunneled WebSocket endpoint. + +This should be the first remote mode shipped because it validates the environment model with minimal extra machinery. + +### 2. Desktop-managed remote launch over SSH + +This is the main place where Zed is a useful reference. + +Useful ideas to borrow from Zed: + +- remote probing +- platform detection +- session directories with pid/log metadata +- reconnect-friendly launcher behavior +- desktop-owned connection UX + +What should be different in T3: + +- no custom stdio/socket proxy protocol between renderer and remote runtime +- no attempt to make the remote runtime look like an editor transport +- keep the final client-to-server connection as WebSocket + +The recommended T3 flow is: + +1. Desktop connects over SSH. +2. Desktop probes the remote machine and verifies T3 availability. +3. Desktop launches or reuses a remote T3 server. +4. Desktop establishes local port forwarding. +5. Renderer connects to the forwarded WebSocket endpoint as a normal environment. + +### 3. Client-managed local publish + +This is the inverse of remote launch: a local T3 server is already running, and the client publishes it through a tunnel. + +This is useful for: + +- exposing a desktop-hosted environment to mobile +- temporary remote access without changing router or firewall settings + +This is still a launch concern, not a new environment kind. + +## Why access and launch must stay separate + +These concerns are easy to conflate, but separating them prevents architectural drift. + +Examples: + +- A manually hosted T3 server might be reached through direct `wss`. +- The same server might also be reachable through a tunnel. +- An SSH-managed server might be launched over SSH but then reached through forwarded WebSocket. +- A local desktop server might be published through a tunnel for mobile. + +In all of those cases, the `ExecutionEnvironment` is the same kind of thing. + +Only the launch and access paths differ. + +## Security model + +Remote support must assume that some environments will be reachable over untrusted networks. + +That means: + +- remote-capable environments should require explicit authentication +- tunnel exposure should not rely on obscurity +- client-saved endpoints should carry enough auth metadata to reconnect safely + +T3 already supports a WebSocket auth token on the server. That should become a first-class part of environment access rather than remaining an incidental query parameter convention. + +For publicly reachable environments, authenticated access should be treated as required. + +## Relationship to Zed + +Zed is a useful reference implementation for managed remote launch and reconnect behavior. + +The relevant lessons are: + +- remote bootstrap should be explicit +- reconnect should be first-class +- connection UX belongs in the client shell +- runtime ownership should stay clearly on the remote host + +The important mismatch is transport shape. + +Zed needs a custom proxy/server protocol because its remote boundary sits below the editor and project runtime. + +T3 should not copy that part. + +T3 already has the right runtime boundary: + +- one T3 server per environment +- ordinary HTTP/WebSocket between client and environment + +So T3 should borrow Zed's launch discipline, not its transport protocol. + +## Recommended rollout + +1. First-class known environments and access endpoints. +2. Direct `ws` / `wss` remote environments. +3. Authenticated tunnel-backed environments. +4. Desktop-managed SSH launch and forwarding. +5. Multi-environment UI improvements after the base runtime path is proven. + +This ordering keeps the architecture network-first and transport-agnostic while still leaving room for richer managed remote flows. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 67b5e32860..5c2d2c8381 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,6 +10,7 @@ jobs: quality: name: Format, Lint, Typecheck, Test, Browser Test, Build runs-on: blacksmith-4vcpu-ubuntu-2404 + timeout-minutes: 10 steps: - name: Checkout uses: actions/checkout@v6 @@ -71,11 +72,12 @@ jobs: - name: Verify preload bundle output run: | test -f apps/desktop/dist-electron/preload.js - grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js + grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js release_smoke: name: Release Smoke runs-on: ubuntu-24.04 + timeout-minutes: 10 steps: - name: Checkout uses: actions/checkout@v6 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 504952e3aa..ac01ee8793 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -19,6 +19,7 @@ jobs: preflight: name: Preflight runs-on: ubuntu-24.04 + timeout-minutes: 10 outputs: version: ${{ steps.release_meta.outputs.version }} tag: ${{ steps.release_meta.outputs.tag }} @@ -81,6 +82,7 @@ jobs: name: Build ${{ matrix.label }} needs: preflight runs-on: ${{ matrix.runner }} + timeout-minutes: 30 strategy: fail-fast: false matrix: @@ -227,6 +229,7 @@ jobs: name: Publish CLI to npm needs: [preflight, build] runs-on: ubuntu-24.04 + timeout-minutes: 10 steps: - name: Checkout uses: actions/checkout@v6 @@ -260,6 +263,7 @@ jobs: name: Publish GitHub Release needs: [preflight, build, publish_cli] runs-on: ubuntu-24.04 + timeout-minutes: 10 steps: - name: Checkout uses: actions/checkout@v6 @@ -307,6 +311,7 @@ jobs: name: Finalize release needs: [preflight, release] runs-on: ubuntu-24.04 + timeout-minutes: 10 steps: - id: app_token name: Mint release app token diff --git a/.gitignore b/.gitignore index 6e5f8cc59c..6c48782f9a 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,4 @@ apps/web/src/components/__screenshots__ .vitest-* __screenshots__/ .tanstack +squashfs-root/ diff --git a/.oxfmtrc.json b/.oxfmtrc.json index ef2236d0f2..776d11b803 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -1,6 +1,7 @@ { "$schema": "./node_modules/oxfmt/configuration_schema.json", "ignorePatterns": [ + ".reference", ".plans", "dist", "dist-electron", @@ -8,7 +9,8 @@ "bun.lock", "*.tsbuildinfo", "**/routeTree.gen.ts", - "apps/web/public/mockServiceWorker.js" + "apps/web/public/mockServiceWorker.js", + "apps/web/src/lib/vendor/qrcodegen.ts" ], "sortPackageJson": {} } diff --git a/.plans/18-server-auth-model.md b/.plans/18-server-auth-model.md new file mode 100644 index 0000000000..9f8ba8a05d --- /dev/null +++ b/.plans/18-server-auth-model.md @@ -0,0 +1,823 @@ +# Server Auth Model Plan + +## Purpose + +Define the long-term server auth architecture for T3 Code before first-class remote environments ship. + +This plan is deliberately broader than the current WebSocket token check and narrower than a complete remote collaboration system. The goal is to make the server secure by default, keep local desktop UX frictionless, and leave clean integration points for future remote access methods. + +This document is written in terms of Effect-native services and layers because auth needs to be a core runtime concern, not route-local glue code. + +## Primary goals + +- Make auth server-wide, not WebSocket-only. +- Make insecure exposure hard to do accidentally. +- Preserve zero-login local desktop UX for desktop-managed environments. +- Support browser-native pairing and session auth. +- Leave room for native/mobile credentials later without rewriting the server boundary. +- Keep auth separate from transport and launch method. + +## Non-goals + +- Full multi-user authorization and RBAC. +- OAuth / SSO / enterprise identity. +- Passkeys or biometric UX in v1. +- Syncing auth state across environments. +- Designing the full remote environment product in this document. + +## Core decisions + +### 1. Auth is a server concern + +Every privileged surface of the T3 server must go through the same auth policy engine: + +- HTTP routes +- WebSocket upgrades +- RPC methods reached through WebSocket + +The current split where [`/ws`](../apps/server/src/ws.ts) checks `authToken` but routes in [`http.ts`](../apps/server/src/http.ts) do not is not sufficient for a remote-capable product. + +### 2. Pairing and session are different things + +The system should distinguish: + +- bootstrap credentials +- session credentials + +Bootstrap credentials are short-lived and high-trust. They allow a client to become authenticated. + +Session credentials are the durable credentials used after pairing. + +Bootstrap should never become the long-lived request credential. + +### 3. Auth and transport are separate + +Auth must not be defined by how the client reached the server. + +Examples: + +- local desktop-managed server +- LAN `ws://` +- public `wss://` +- tunneled `wss://` +- SSH-forwarded `ws://127.0.0.1:` + +All of these should feed into the same auth model. + +### 4. Exposure level changes defaults + +The more exposed an environment is, the narrower the safe default should be. + +Safe default expectations: + +- local desktop-managed: auto-pair allowed +- loopback browser access: explicit bootstrap allowed +- non-loopback bind: auth required +- tunnel/public endpoint: auth required, explicit enablement required + +### 5. Browser and native clients may use different session credentials + +The auth model should support more than one session credential type even if only one ships first. + +Examples: + +- browser session cookie +- native bearer/device token + +This should be represented in the model now, even if browser cookies are the first implementation. + +## Target auth domain + +### Route classes + +Every route or transport entrypoint should be classified as one of: + +1. `public` +2. `bootstrap` +3. `authenticated` + +#### `public` + +Unauthenticated by definition. + +Should be extremely small. Examples: + +- static shell needed to render the pairing/login UI +- favicon/assets required for the pairing screen +- a minimal server health/version endpoint if needed + +#### `bootstrap` + +Used only to exchange a bootstrap credential for a session. + +Examples: + +- Initial bootstrap envelope over file descriptor at startup +- `POST /api/auth/bootstrap` +- `GET /api/auth/session` if unauthenticated checks are part of bootstrap UX + +#### `authenticated` + +Everything that reveals machine state or mutates it. + +Examples: + +- WebSocket upgrade +- orchestration snapshot and events +- terminal open/write/close +- project search and file writes +- git routes +- attachments +- project favicon lookup +- server settings + +The default stance should be: if it touches the machine, it is authenticated. + +## Credential model + +### Bootstrap credentials + +Initial credential types to model: + +- `desktop-bootstrap` +- `one-time-token` + +Possible future credential types: + +- `device-code` +- `passkey-assertion` +- `external-identity` + +#### `desktop-bootstrap` + +Used when the desktop shell manages the server and should be the only default pairing method for desktop-local environments. + +Properties: + +- launcher-provided +- short-lived +- one-time or bounded-use +- never shown to the user as a reusable password + +#### `one-time-token` + +Used for explicit browser/mobile pairing flows. + +Properties: + +- short TTL +- one-time use +- safe to embed in a pairing URL fragment +- exchanged for a session credential + +### Session credentials + +Initial credential types to model: + +- `browser-session-cookie` +- `bearer-session-token` + +#### `browser-session-cookie` + +Primary browser credential. + +Properties: + +- signed +- `HttpOnly` +- bounded lifetime +- revocable by server key rotation or session invalidation + +#### `bearer-session-token` + +Reserved for native/mobile or non-browser clients. + +Properties: + +- opaque token, not a bootstrap secret +- long enough lifetime to survive reconnects +- stored in secure client storage when available + +## Auth policy model + +Auth behavior should be driven by an explicit environment auth policy, not route-local heuristics. + +### Policy examples + +#### `DesktopManagedLocalPolicy` + +Default for desktop-managed local server. + +Allowed bootstrap methods: + +- `desktop-bootstrap` + +Allowed session methods: + +- `browser-session-cookie` + +Disabled by default: + +- `one-time-token` +- `bearer-session-token` +- password login +- public pairing + +#### `LoopbackBrowserPolicy` + +Used for browser access on localhost without desktop-managed bootstrap. + +Allowed bootstrap methods: + +- `one-time-token` + +Allowed session methods: + +- `browser-session-cookie` + +#### `RemoteReachablePolicy` + +Used when binding non-loopback or using an explicit remote/tunnel workflow. + +Allowed bootstrap methods: + +- `one-time-token` +- possibly `desktop-bootstrap` when a desktop shell is brokering access + +Allowed session methods: + +- `browser-session-cookie` +- `bearer-session-token` + +#### `UnsafeNoAuthPolicy` + +Should exist only as an explicit escape hatch. + +Requirements: + +- explicit opt-in flag +- loud startup warnings +- never defaulted automatically + +## Effect-native service model + +### `ServerAuth` + +The main auth facade used by HTTP routes and WebSocket upgrade handling. + +Responsibilities: + +- classify requests +- authenticate requests +- authorize bootstrap attempts +- create sessions from bootstrap credentials +- enforce policy by environment mode + +Sketch: + +```ts +export interface ServerAuthShape { + readonly getCapabilities: Effect.Effect; + readonly authenticateHttpRequest: ( + request: HttpServerRequest.HttpServerRequest, + routeClass: RouteAuthClass, + ) => Effect.Effect; + readonly authenticateWebSocketUpgrade: ( + request: HttpServerRequest.HttpServerRequest, + ) => Effect.Effect; + readonly exchangeBootstrapCredential: ( + input: BootstrapExchangeInput, + ) => Effect.Effect; +} + +export class ServerAuth extends ServiceMap.Service()( + "t3/ServerAuth", +) {} +``` + +### `BootstrapCredentialService` + +Owns issuance, storage, validation, and consumption of bootstrap credentials. + +Responsibilities: + +- issue desktop bootstrap grants +- issue one-time pairing tokens +- validate TTL and single-use semantics +- consume bootstrap grants atomically + +Sketch: + +```ts +export interface BootstrapCredentialServiceShape { + readonly issueDesktopBootstrap: ( + input: IssueDesktopBootstrapInput, + ) => Effect.Effect; + readonly issueOneTimeToken: ( + input: IssueOneTimeTokenInput, + ) => Effect.Effect; + readonly consume: ( + presented: PresentedBootstrapCredential, + ) => Effect.Effect; +} +``` + +### `SessionCredentialService` + +Owns creation and validation of authenticated sessions. + +Responsibilities: + +- mint cookie sessions +- mint bearer sessions +- validate active session credentials +- revoke sessions if needed later + +Sketch: + +```ts +export interface SessionCredentialServiceShape { + readonly createBrowserSession: ( + input: CreateSessionFromBootstrapInput, + ) => Effect.Effect; + readonly createBearerSession: ( + input: CreateSessionFromBootstrapInput, + ) => Effect.Effect; + readonly authenticateCookie: ( + request: HttpServerRequest.HttpServerRequest, + ) => Effect.Effect; + readonly authenticateBearer: ( + request: HttpServerRequest.HttpServerRequest, + ) => Effect.Effect; +} +``` + +### `ServerAuthPolicy` + +Pure policy/config service that decides which credential types are allowed. + +Responsibilities: + +- map runtime mode and bind/exposure settings to allowed auth methods +- answer whether a route can be public +- answer whether remote exposure requires auth + +This should stay mostly pure and cheap to test. + +### `ServerSecretStore` + +Owns long-lived server signing keys and secrets. + +Responsibilities: + +- get or create signing key +- rotate signing key +- abstract secure OS-backed storage vs filesystem fallback + +Important: + +- prefer platform secure storage when available +- support hardened filesystem fallback for headless/server-only environments + +### `BrowserSessionCookieCodec` + +Focused utility service for cookie encode/decode/signing behavior. + +This should not own policy. It should only own the cookie format. + +### `AuthRouteGuards` + +Thin helper layer used by routes to enforce auth consistently. + +Responsibilities: + +- require auth for HTTP route handlers +- classify route auth mode +- convert auth failures into `401` / `403` + +This prevents every route from re-implementing the same pattern. + +Integrates with `HttpRouter.middleware` to enforce auth consistently. + +## Suggested layer graph + +```text +ServerSecretStore + ├─> BootstrapCredentialService + ├─> BrowserSessionCookieCodec + └─> SessionCredentialService + +ServerAuthPolicy + ├─> BootstrapCredentialService + ├─> SessionCredentialService + └─> ServerAuth + +ServerAuth + └─> AuthRouteGuards +``` + +Layer naming should follow existing repo style: + +- `ServerSecretStoreLive` +- `BootstrapCredentialServiceLive` +- `SessionCredentialServiceLive` +- `ServerAuthPolicyLive` +- `ServerAuthLive` +- `AuthRouteGuardsLive` + +## High-level implementation examples + +### Example: WebSocket upgrade auth + +Current state: + +- `authToken` query param is checked in [`ws.ts`](../apps/server/src/ws.ts) + +Target shape: + +```ts +const websocketUpgradeAuth = HttpMiddleware.make((httpApp) => + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const serverAuth = yield* ServerAuth; + yield* serverAuth.authenticateWebSocketUpgrade(request); + return yield* httpApp; + }), +); +``` + +Then the `/ws` route becomes: + +```ts +export const websocketRpcRouteLayer = HttpRouter.add( + "GET", + "/ws", + rpcWebSocketHttpEffect.pipe( + websocketUpgradeAuth, + Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)), + ), +); +``` + +This keeps the route itself declarative and makes auth compose like normal HTTP middleware. + +### Example: authenticated HTTP route + +For routes like attachments or project favicon: + +```ts +const authenticatedRoute = (routeClass: RouteAuthClass) => + HttpMiddleware.make((httpApp) => + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const serverAuth = yield* ServerAuth; + yield* serverAuth.authenticateHttpRequest(request, routeClass); + return yield* httpApp; + }), + ); +``` + +Then: + +```ts +export const attachmentsRouteLayer = HttpRouter.add( + "GET", + `${ATTACHMENTS_ROUTE_PREFIX}/*`, + serveAttachment.pipe( + authenticatedRoute(RouteAuthClass.Authenticated), + Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)), + ), +); +``` + +### Example: desktop bootstrap exchange + +The desktop shell launches the local server and gets a short-lived bootstrap grant through a trusted side channel. + +That grant is then exchanged for a browser cookie session when the renderer loads. + +Sketch: + +```ts +const pairDesktopRenderer = Effect.gen(function* () { + const bootstrapService = yield* BootstrapCredentialService; + const credential = yield* bootstrapService.issueDesktopBootstrap({ + audience: "desktop-renderer", + ttlMs: 30_000, + }); + return credential; +}); +``` + +The renderer then calls a bootstrap endpoint and receives a cookie session. The bootstrap credential is consumed and becomes invalid. + +### Example: one-time pairing URL + +For browser-driven pairing: + +```ts +const createPairingToken = Effect.gen(function* () { + const bootstrapService = yield* BootstrapCredentialService; + return yield* bootstrapService.issueOneTimeToken({ + ttlMs: 5 * 60_000, + audience: "browser", + }); +}); +``` + +The server can emit a pairing URL where the token lives in the URL fragment so it is not automatically sent to the server before the client explicitly exchanges it. + +## Sequence diagrams + +These flows are meant to anchor the auth model in concrete user journeys. + +The important invariant across all of them is: + +- access method is not the auth method +- launch method is not the auth method +- bootstrap credential is not the session credential + +### Normal desktop user + +This is the default desktop-managed local flow. + +The desktop shell is trusted to bootstrap the local renderer, but the renderer should still exchange that one-time bootstrap grant for a normal browser session cookie. + +```text +Participants: + DesktopMain = Electron main + SecretStore = secure local secret backend + T3Server = local backend child process + Frontend = desktop renderer + +DesktopMain -> SecretStore : getOrCreate("server-signing-key") +SecretStore --> DesktopMain : signing key available + +DesktopMain -> T3Server : spawn server (--bootstrap-fd ...) +DesktopMain -> T3Server : send desktop bootstrap envelope +note over T3Server : policy = DesktopManagedLocalPolicy +note over T3Server : allowed pairing = desktop-bootstrap only + +Frontend -> DesktopMain : request local bootstrap grant +DesktopMain --> Frontend : short-lived desktop bootstrap grant + +Frontend -> T3Server : POST /api/auth/bootstrap +T3Server -> T3Server : validate desktop bootstrap grant +T3Server -> T3Server : create browser session +T3Server --> Frontend : Set-Cookie: session=... + +Frontend -> T3Server : GET /ws + authenticated cookie +T3Server -> T3Server : validate cookie session +T3Server --> Frontend : websocket accepted +``` + +### `npx t3` user + +This is the standalone local server flow. + +There is no trusted desktop shell here, so pairing should be explicit. + +```text +Participants: + UserShell = npx t3 launcher + T3Server = standalone local server + Browser = browser tab + +UserShell -> T3Server : start server +T3Server -> T3Server : getOrCreate("server-signing-key") +note over T3Server : policy = LoopbackBrowserPolicy + +UserShell -> T3Server : issue one-time pairing token +T3Server --> UserShell : pairing URL or pairing token + +UserShell --> Browser : open /pair?token=... + +Browser -> T3Server : GET /pair?token=... +T3Server -> T3Server : validate one-time token +T3Server -> T3Server : create browser session +T3Server --> Browser : Set-Cookie: session=... +T3Server --> Browser : redirect to app + +Browser -> T3Server : GET /ws + authenticated cookie +T3Server --> Browser : websocket accepted +``` + +### Phone user with tunneled host + +This is the explicit remote access flow for a browser on another device. + +The tunnel only provides reachability. It must not imply trust. + +Recommended UX: + +- desktop shows a QR code +- desktop also shows a copyable pairing URL +- if the phone opens the host URL without a valid token, the server should render a login or pairing screen rather than granting access + +```text +Participants: + DesktopUser = user at the host machine + DesktopMain = desktop app + Tunnel = tunnel provider + T3Server = T3 server + PhoneBrowser = mobile browser + +DesktopUser -> DesktopMain : enable remote access via tunnel +DesktopMain -> T3Server : switch policy to RemoteReachablePolicy +DesktopMain -> Tunnel : publish local T3 endpoint +Tunnel --> DesktopMain : public https/wss URL + +DesktopMain -> T3Server : issue one-time pairing token +T3Server --> DesktopMain : pairing token +DesktopMain -> DesktopUser : show QR code / shareable URL + +DesktopUser -> PhoneBrowser : scan QR / open URL +PhoneBrowser -> Tunnel : GET https://public-host/pair?token=... +Tunnel -> T3Server : forward request +T3Server -> T3Server : validate one-time token +T3Server -> T3Server : create mobile browser session +T3Server --> PhoneBrowser : Set-Cookie: session=... +T3Server --> PhoneBrowser : redirect to app + +PhoneBrowser -> Tunnel : GET /ws + authenticated cookie +Tunnel -> T3Server : forward websocket upgrade +T3Server --> PhoneBrowser : websocket accepted +``` + +### Phone user with private network + +This is operationally similar to the tunnel flow, but the access endpoint is on a private network such as Tailscale. + +The auth flow should stay the same. + +```text +Participants: + DesktopUser = user at the host machine + T3Server = T3 server + PrivateNet = tailscale / private LAN + PhoneBrowser = mobile browser + +DesktopUser -> T3Server : enable private-network access +T3Server -> T3Server : switch policy to RemoteReachablePolicy +DesktopUser -> T3Server : issue one-time pairing token +T3Server --> DesktopUser : pairing URL / QR + +DesktopUser -> PhoneBrowser : open private-network URL +PhoneBrowser -> PrivateNet : GET http(s)://private-host/pair?token=... +PrivateNet -> T3Server : route request +T3Server -> T3Server : validate one-time token +T3Server -> T3Server : create mobile browser session +T3Server --> PhoneBrowser : Set-Cookie: session=... +T3Server --> PhoneBrowser : redirect to app + +PhoneBrowser -> PrivateNet : GET /ws + authenticated cookie +PrivateNet -> T3Server : websocket upgrade +T3Server --> PhoneBrowser : websocket accepted +``` + +### Desktop user adding new SSH hosts + +SSH should be treated as launch and reachability plumbing, not as the long-term auth model. + +The desktop app uses SSH to start or reach the remote server, then the renderer pairs against that server using the same bootstrap/session split as every other environment. + +```text +Participants: + DesktopUser = local desktop user + DesktopMain = desktop app + SSH = ssh transport/session + RemoteHost = remote machine + RemoteT3 = remote T3 server + Frontend = desktop renderer + +DesktopUser -> DesktopMain : add SSH host +DesktopMain -> SSH : connect to remote host +SSH -> RemoteHost : probe environment / verify t3 availability +DesktopMain -> SSH : run remote launch command +SSH -> RemoteHost : t3 remote launch --json +RemoteHost -> RemoteT3 : start or reuse server +RemoteT3 --> RemoteHost : port + environment metadata +RemoteHost --> SSH : launch result JSON +SSH --> DesktopMain : remote server details + +DesktopMain -> SSH : establish local port forward +SSH --> DesktopMain : localhost:FORWARDED_PORT ready + +note over RemoteT3 : policy = RemoteReachablePolicy +note over DesktopMain,RemoteT3 : desktop may use a trusted bootstrap flow here + +Frontend -> DesktopMain : request bootstrap for selected environment +DesktopMain --> Frontend : short-lived bootstrap grant + +Frontend -> RemoteT3 : POST /api/auth/bootstrap via forwarded port +RemoteT3 -> RemoteT3 : validate bootstrap grant +RemoteT3 -> RemoteT3 : create browser session +RemoteT3 --> Frontend : Set-Cookie: session=... + +Frontend -> RemoteT3 : GET /ws + authenticated cookie +RemoteT3 --> Frontend : websocket accepted +``` + +## Storage decisions + +### Server secrets + +Use a `ServerSecretStore` abstraction. + +Preferred order (use a layer for each, resolve on startup): + +1. OS secure storage if available +2. hardened filesystem fallback if not + +The filesystem fallback should store only opaque signing material with strict file permissions. It should not store user passwords or reusable third-party credentials. + +### Client credentials + +Client-side credential persistence should prefer secure storage when available: + +- desktop: OS keychain / secure store +- mobile: platform secure storage +- browser: cookie session for browser auth + +This concern should stay in the client shell/runtime layer, not the server auth layer. + +## What to build now + +These are the parts worth building before remote environments ship: + +1. `ServerAuth` service boundary. +2. route classification and route guards. +3. `ServerSecretStore` abstraction. +4. bootstrap vs session credential split. +5. browser session cookie codec as one session method. +6. explicit auth capabilities/config surfaced in contracts. + +Even if only one pairing flow is used initially, these seams will keep future remote and mobile work contained. + +## What to add as part of first remote-capable auth + +1. Browser pairing flow using one-time bootstrap token and cookie session. +2. Desktop-managed auto-bootstrap for the local desktop-managed environment. +3. Auth-required defaults for any non-loopback or explicitly published server. +4. Explicit environment auth policy selection instead of scattered `if (host !== localhost)` checks. + +## What to defer + +- passkeys / WebAuthn +- iCloud Keychain / Face ID-specific UX +- multi-user permissions +- collaboration roles +- OAuth / SSO +- polished session management UI +- complex device approval flows + +These can all sit on top of the same bootstrap/session/service split. + +## Relationship to future remote environments + +Remote access is one reason this auth model matters, but the auth model should not be remote-shaped. + +Keep the design focused on: + +- one T3 server +- one auth policy +- multiple credential types +- multiple future access methods + +That keeps the server auth model stable even as access methods expand later. + +## Recommended implementation order + +### Phase 1 + +- Introduce route auth classes. +- Add `ServerAuth` and `AuthRouteGuards`. +- Move existing `authToken` check behind `ServerAuth`. +- Require auth for all privileged HTTP routes as well as WebSocket. + +### Phase 2 + +- Add `ServerSecretStore` service with platform-specific layer implementations. + - `layerOSXKeychain`, `layer +- Add bootstrap/session split. +- Add browser session cookie support. +- Add one-time bootstrap exchange endpoint. + +### Phase 3 + +- Add desktop bootstrap flow on top of the same services. +- Make desktop-managed local environments default to bootstrap-only pairing. +- Surface auth capabilities in shared contracts and renderer bootstrap. + +### Phase 4 + +- Add non-browser bearer session support if mobile/native needs it. +- Add richer policy modes for remote-reachable environments. + +## Acceptance criteria + +- No privileged HTTP or WebSocket path bypasses auth policy. +- Local desktop-managed flows still avoid a visible login screen. +- Non-loopback or published environments require explicit authenticated pairing by default. +- Bootstrap and session credentials are distinct in code and in behavior. +- Auth logic is centralized in Effect services/layers rather than route-local branching. 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 d7b2fccb8f..d3a54a1b90 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,8 @@ We are very very early in this project. Expect bugs. We are not accepting contributions yet. +Observability guide: [docs/observability.md](./docs/observability.md) + ## If you REALLY want to contribute still.... read this first Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR. diff --git a/REMOTE.md b/REMOTE.md index 9dc15ed1fe..30dc562792 100644 --- a/REMOTE.md +++ b/REMOTE.md @@ -1,68 +1,87 @@ -# Remote Access Setup +# Remote Access -Use this when you want to open T3 Code from another device (phone, tablet, another laptop). +Use this when you want to connect to a T3 Code server from another device such as a phone, tablet, or separate desktop app. -## CLI ↔ Env option map +## Recommended Setup -The T3 Code CLI accepts the following configuration options, available either as CLI flags or environment variables: +Use a trusted private network that meshes your devices together, such as a tailnet. -| CLI flag | Env var | Notes | -| ----------------------- | --------------------- | ------------------------------------------------------------------------------------ | -| `--mode ` | `T3CODE_MODE` | Runtime mode. | -| `--port ` | `T3CODE_PORT` | HTTP/WebSocket port. | -| `--host
` | `T3CODE_HOST` | Bind interface/address. | -| `--base-dir ` | `T3CODE_HOME` | Base directory. | -| `--dev-url ` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. | -| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. | -| `--auth-token ` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. Use this for standard CLI and remote-server flows. | -| `--bootstrap-fd ` | `T3CODE_BOOTSTRAP_FD` | Read a one-shot bootstrap envelope from an inherited file descriptor during startup. | +That gives you: -> TIP: Use the `--help` flag to see all available options and their descriptions. +- a stable address to connect to +- transport security at the network layer +- less exposure than opening the server to the public internet -## Security First +## Enabling Network Access -- Always set `--auth-token` before exposing the server outside localhost. - - When you control the process launcher, prefer sending the auth token in a JSON envelope via `--bootstrap-fd `. - With `--bootstrap-fd `, the launcher starts the server first, then sends a one-shot JSON envelope over the inherited file descriptor. This allows the auth token to be delivered without putting it in process environment or command line arguments. -- Treat the token like a password. -- Prefer binding to trusted interfaces (LAN IP or Tailnet IP) instead of opening all interfaces unless needed. +There are two ways to expose your server for remote connections: from the desktop app or from the CLI. -## 1) Build + run server for remote access +### Option 1: Desktop App -Remote access should use the built web app (not local Vite redirect mode). +If you are already running the desktop app and want to make it reachable from other devices: + +1. Open **Settings** → **Connections**. +2. Under **Manage Local Backend**, toggle **Network access** on. This will restart the app and run the backend on all network interfaces. +3. The settings panel will show the address the server is reachable at (e.g. `http://192.168.x.y:3773`). +4. Use **Create Link** to generate a pairing link you can share with another device. + +### Option 2: Headless Server (CLI) + +Use this when you want to run the server without a GUI, for example on a remote machine over SSH. + +Run the server with `t3 serve`. ```bash -bun run build -TOKEN="$(openssl rand -hex 24)" -bun run --cwd apps/server start -- --host 0.0.0.0 --port 3773 --auth-token "$TOKEN" --no-browser +npx t3 serve --host "$(tailscale ip -4)" ``` -Then open on your phone: +`t3 serve` starts the server without opening a browser and prints: -`http://:3773` +- a connection string +- a pairing token +- a pairing URL +- a QR code for the pairing URL -Example: +From there, connect from another device in either of these ways: -`http://192.168.1.42:3773` +- scan the QR code on your phone +- in the desktop app, enter the full pairing URL +- in the desktop app, enter the host and token separately -Notes: +Use `t3 serve --help` for the full flag reference. It supports the same general startup options as the normal server command, including an optional `cwd` argument. -- `--host 0.0.0.0` listens on all IPv4 interfaces. -- `--no-browser` prevents local auto-open, which is usually better for headless/remote sessions. -- Ensure your OS firewall allows inbound TCP on the selected port. +> Note +> The GUIs do not currently support adding projects on remote environments. +> For now, use `t3 project ...` on the server machine instead. +> Full GUI support for remote project management is coming soon. -## 2) Tailnet / Tailscale access +## How Pairing Works -If you use Tailscale, you can bind directly to your Tailnet address. +The remote device does not need a long-lived secret up front. -```bash -TAILNET_IP="$(tailscale ip -4)" -TOKEN="$(openssl rand -hex 24)" -bun run --cwd apps/server start -- --host "$(tailscale ip -4)" --port 3773 --auth-token "$TOKEN" --no-browser -``` +Instead: -Open from any device in your tailnet: +1. `t3 serve` issues a one-time owner pairing token. +2. The remote device exchanges that token with the server. +3. The server creates an authenticated session for that device. -`http://:3773` +After pairing, future access is session-based. You do not need to keep reusing the original token unless you are pairing a new device. -You can also bind `--host 0.0.0.0` and connect through the Tailnet IP, but binding directly to the Tailnet IP limits exposure. +## Managing Access Later + +Use `t3 auth` to manage access after the initial pairing flow. + +Typical uses: + +- issue additional pairing credentials +- inspect active sessions +- revoke old pairing links or sessions + +Use `t3 auth --help` and the nested subcommand help pages for the full reference. + +## Security Notes + +- Treat pairing URLs and pairing tokens like passwords. +- Prefer binding `--host` to a trusted private address, such as a Tailnet IP, instead of exposing the server broadly. +- Anyone with a valid pairing credential can create a session until that credential expires or is revoked. +- Use `t3 auth` to revoke credentials or sessions you no longer trust. diff --git a/apps/desktop/package.json b/apps/desktop/package.json index dfa3bde2f8..a38ffd2df1 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/desktop", - "version": "0.0.15", + "version": "0.0.17", "private": true, "main": "dist-electron/main.js", "scripts": { diff --git a/apps/desktop/scripts/dev-electron.mjs b/apps/desktop/scripts/dev-electron.mjs index 1506d80e9f..7c0d55ac9a 100644 --- a/apps/desktop/scripts/dev-electron.mjs +++ b/apps/desktop/scripts/dev-electron.mjs @@ -5,16 +5,25 @@ import { join } from "node:path"; 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 devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim(); +if (!devServerUrl) { + throw new Error("VITE_DEV_SERVER_URL is required for desktop development."); +} + +const devServer = new URL(devServerUrl); +const port = Number.parseInt(devServer.port, 10); +if (!Number.isInteger(port) || port <= 0) { + throw new Error(`VITE_DEV_SERVER_URL must include an explicit port: ${devServerUrl}`); +} + 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; @@ -23,6 +32,7 @@ const childTreeGracePeriodMs = 1_200; await waitForResources({ baseDir: desktopDir, files: requiredFiles, + tcpHost: devServer.hostname, tcpPort: port, }); @@ -62,10 +72,7 @@ function startApp() { [`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"], { cwd: desktopDir, - env: { - ...childEnv, - VITE_DEV_SERVER_URL: devServerUrl, - }, + env: childEnv, stdio: "inherit", }, ); diff --git a/apps/desktop/scripts/electron-launcher.mjs b/apps/desktop/scripts/electron-launcher.mjs index 9d7c522781..b8875b08ab 100644 --- a/apps/desktop/scripts/electron-launcher.mjs +++ b/apps/desktop/scripts/electron-launcher.mjs @@ -18,7 +18,7 @@ import { fileURLToPath } from "node:url"; const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL); const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)"; -const APP_BUNDLE_ID = "com.t3tools.t3code"; +const APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code"; const LAUNCHER_VERSION = 1; const __dirname = dirname(fileURLToPath(import.meta.url)); diff --git a/apps/desktop/src/backendPort.test.ts b/apps/desktop/src/backendPort.test.ts new file mode 100644 index 0000000000..8f586deb70 --- /dev/null +++ b/apps/desktop/src/backendPort.test.ts @@ -0,0 +1,109 @@ +import { describe, expect, it, vi } from "vitest"; + +import { resolveDesktopBackendPort } from "./backendPort"; + +describe("resolveDesktopBackendPort", () => { + it("returns the starting port when it is available", async () => { + const canListenOnHost = vi.fn(async (port: number) => port === 3773); + + await expect( + resolveDesktopBackendPort({ + host: "127.0.0.1", + startPort: 3773, + canListenOnHost, + }), + ).resolves.toBe(3773); + + expect(canListenOnHost).toHaveBeenCalledTimes(1); + expect(canListenOnHost).toHaveBeenCalledWith(3773, "127.0.0.1"); + }); + + it("increments sequentially until it finds an available port", async () => { + const canListenOnHost = vi.fn(async (port: number) => port === 3775); + + await expect( + resolveDesktopBackendPort({ + host: "127.0.0.1", + startPort: 3773, + canListenOnHost, + }), + ).resolves.toBe(3775); + + expect(canListenOnHost.mock.calls).toEqual([ + [3773, "127.0.0.1"], + [3774, "127.0.0.1"], + [3775, "127.0.0.1"], + ]); + }); + + it("treats wildcard-bound ports as unavailable even when loopback probing succeeds", async () => { + const canListenOnHost = vi.fn(async (port: number, host: string) => { + if (port === 3773 && host === "127.0.0.1") return true; + if (port === 3773 && host === "0.0.0.0") return false; + return port === 3774; + }); + + await expect( + resolveDesktopBackendPort({ + host: "127.0.0.1", + requiredHosts: ["0.0.0.0"], + startPort: 3773, + canListenOnHost, + }), + ).resolves.toBe(3774); + + expect(canListenOnHost.mock.calls).toEqual([ + [3773, "127.0.0.1"], + [3773, "0.0.0.0"], + [3774, "127.0.0.1"], + [3774, "0.0.0.0"], + ]); + }); + + it("checks overlapping hosts sequentially to avoid self-interference", async () => { + let inFlightCount = 0; + const canListenOnHost = vi.fn(async (_port: number, _host: string) => { + inFlightCount += 1; + const overlapped = inFlightCount > 1; + await Promise.resolve(); + inFlightCount -= 1; + return !overlapped; + }); + + await expect( + resolveDesktopBackendPort({ + host: "127.0.0.1", + requiredHosts: ["0.0.0.0", "::"], + startPort: 3773, + maxPort: 3773, + canListenOnHost, + }), + ).resolves.toBe(3773); + + expect(canListenOnHost.mock.calls).toEqual([ + [3773, "127.0.0.1"], + [3773, "0.0.0.0"], + [3773, "::"], + ]); + }); + + it("fails when the scan range is exhausted", async () => { + const canListenOnHost = vi.fn(async () => false); + + await expect( + resolveDesktopBackendPort({ + host: "127.0.0.1", + startPort: 65534, + maxPort: 65535, + canListenOnHost, + }), + ).rejects.toThrow( + "No desktop backend port is available on hosts 127.0.0.1 between 65534 and 65535", + ); + + expect(canListenOnHost.mock.calls).toEqual([ + [65534, "127.0.0.1"], + [65535, "127.0.0.1"], + ]); + }); +}); diff --git a/apps/desktop/src/backendPort.ts b/apps/desktop/src/backendPort.ts new file mode 100644 index 0000000000..1ce90a257f --- /dev/null +++ b/apps/desktop/src/backendPort.ts @@ -0,0 +1,83 @@ +import * as Effect from "effect/Effect"; +import { NetService } from "@t3tools/shared/Net"; + +export const DEFAULT_DESKTOP_BACKEND_PORT = 3773; +const MAX_TCP_PORT = 65_535; + +export interface ResolveDesktopBackendPortOptions { + readonly host: string; + readonly startPort?: number; + readonly maxPort?: number; + readonly requiredHosts?: ReadonlyArray; + readonly canListenOnHost?: (port: number, host: string) => Promise; +} + +const defaultCanListenOnHost = async (port: number, host: string): Promise => + Effect.service(NetService).pipe( + Effect.flatMap((net) => net.canListenOnHost(port, host)), + Effect.provide(NetService.layer), + Effect.runPromise, + ); + +const isValidPort = (port: number): boolean => + Number.isInteger(port) && port >= 1 && port <= MAX_TCP_PORT; + +const normalizeHosts = ( + host: string, + requiredHosts: ReadonlyArray, +): ReadonlyArray => + Array.from( + new Set( + [host, ...requiredHosts] + .map((candidate) => candidate.trim()) + .filter((candidate) => candidate.length > 0), + ), + ); + +async function canListenOnAllHosts( + port: number, + hosts: ReadonlyArray, + canListenOnHost: (port: number, host: string) => Promise, +): Promise { + for (const candidateHost of hosts) { + if (!(await canListenOnHost(port, candidateHost))) { + return false; + } + } + + return true; +} + +export async function resolveDesktopBackendPort({ + host, + startPort = DEFAULT_DESKTOP_BACKEND_PORT, + maxPort = MAX_TCP_PORT, + requiredHosts = [], + canListenOnHost = defaultCanListenOnHost, +}: ResolveDesktopBackendPortOptions): Promise { + if (!isValidPort(startPort)) { + throw new Error(`Invalid desktop backend start port: ${startPort}`); + } + + if (!isValidPort(maxPort)) { + throw new Error(`Invalid desktop backend max port: ${maxPort}`); + } + + if (maxPort < startPort) { + throw new Error(`Desktop backend max port ${maxPort} is below start port ${startPort}`); + } + + const hostsToCheck = normalizeHosts(host, requiredHosts); + + // Keep desktop startup predictable across app restarts by probing upward from + // the same preferred port instead of picking a fresh ephemeral port. + for (let port = startPort; port <= maxPort; port += 1) { + if (await canListenOnAllHosts(port, hostsToCheck, canListenOnHost)) { + return port; + } + } + + throw new Error( + `No desktop backend port is available on hosts ${hostsToCheck.join(", ")} between ${startPort} and ${maxPort}`, + ); +} diff --git a/apps/desktop/src/backendReadiness.test.ts b/apps/desktop/src/backendReadiness.test.ts new file mode 100644 index 0000000000..fd6180b5da --- /dev/null +++ b/apps/desktop/src/backendReadiness.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, it, vi } from "vitest"; + +import { + BackendReadinessAbortedError, + isBackendReadinessAborted, + waitForHttpReady, +} from "./backendReadiness"; + +describe("waitForHttpReady", () => { + it("returns once the backend reports a successful session endpoint", async () => { + const fetchImpl = vi + .fn() + .mockResolvedValueOnce(new Response(null, { status: 503 })) + .mockResolvedValueOnce(new Response(null, { status: 200 })); + + await waitForHttpReady("http://127.0.0.1:3773", { + fetchImpl, + timeoutMs: 1_000, + intervalMs: 0, + }); + + expect(fetchImpl).toHaveBeenCalledTimes(2); + }); + + it("retries after a readiness request stalls past the per-request timeout", async () => { + const fetchImpl = vi + .fn() + .mockImplementationOnce( + (_input, init) => + new Promise((_resolve, reject) => { + init?.signal?.addEventListener( + "abort", + () => { + reject(new Error("request timed out")); + }, + { once: true }, + ); + }) as ReturnType, + ) + .mockResolvedValueOnce(new Response(null, { status: 200 })); + + await waitForHttpReady("http://127.0.0.1:3773", { + fetchImpl, + timeoutMs: 100, + intervalMs: 0, + requestTimeoutMs: 1, + }); + + expect(fetchImpl).toHaveBeenCalledTimes(2); + }); + + it("aborts an in-flight readiness wait", async () => { + const controller = new AbortController(); + const fetchImpl = vi.fn().mockImplementation( + () => + new Promise((_resolve, reject) => { + controller.signal.addEventListener( + "abort", + () => { + reject(new BackendReadinessAbortedError()); + }, + { once: true }, + ); + }) as ReturnType, + ); + + const waitPromise = waitForHttpReady("http://127.0.0.1:3773", { + fetchImpl, + timeoutMs: 1_000, + intervalMs: 0, + signal: controller.signal, + }); + + controller.abort(); + + await expect(waitPromise).rejects.toBeInstanceOf(BackendReadinessAbortedError); + }); + + it("recognizes aborted readiness errors", () => { + expect(isBackendReadinessAborted(new BackendReadinessAbortedError())).toBe(true); + expect(isBackendReadinessAborted(new Error("nope"))).toBe(false); + }); +}); diff --git a/apps/desktop/src/backendReadiness.ts b/apps/desktop/src/backendReadiness.ts new file mode 100644 index 0000000000..cd5a3c023e --- /dev/null +++ b/apps/desktop/src/backendReadiness.ts @@ -0,0 +1,103 @@ +export interface WaitForHttpReadyOptions { + readonly timeoutMs?: number; + readonly intervalMs?: number; + readonly requestTimeoutMs?: number; + readonly fetchImpl?: typeof fetch; + readonly signal?: AbortSignal; +} + +const DEFAULT_TIMEOUT_MS = 10_000; +const DEFAULT_INTERVAL_MS = 100; +const DEFAULT_REQUEST_TIMEOUT_MS = 1_000; + +export class BackendReadinessAbortedError extends Error { + constructor() { + super("Backend readiness wait was aborted."); + this.name = "BackendReadinessAbortedError"; + } +} + +function delay(ms: number, signal: AbortSignal | undefined): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + cleanup(); + resolve(); + }, ms); + + const onAbort = () => { + cleanup(); + reject(new BackendReadinessAbortedError()); + }; + + const cleanup = () => { + clearTimeout(timer); + signal?.removeEventListener("abort", onAbort); + }; + + if (signal?.aborted) { + cleanup(); + reject(new BackendReadinessAbortedError()); + return; + } + + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} + +export function isBackendReadinessAborted(error: unknown): error is BackendReadinessAbortedError { + return error instanceof BackendReadinessAbortedError; +} + +export async function waitForHttpReady( + baseUrl: string, + options?: WaitForHttpReadyOptions, +): Promise { + const fetchImpl = options?.fetchImpl ?? fetch; + const signal = options?.signal; + const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const intervalMs = options?.intervalMs ?? DEFAULT_INTERVAL_MS; + const requestTimeoutMs = options?.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS; + const deadline = Date.now() + timeoutMs; + + for (;;) { + if (signal?.aborted) { + throw new BackendReadinessAbortedError(); + } + + const requestController = new AbortController(); + const requestTimeout = setTimeout(() => { + requestController.abort(); + }, requestTimeoutMs); + const abortRequest = () => { + requestController.abort(); + }; + signal?.addEventListener("abort", abortRequest, { once: true }); + + try { + const response = await fetchImpl(`${baseUrl}/api/auth/session`, { + redirect: "manual", + signal: requestController.signal, + }); + if (response.ok) { + return; + } + } catch (error) { + if (isBackendReadinessAborted(error)) { + throw error; + } + if (signal?.aborted) { + throw new BackendReadinessAbortedError(); + } + // Retry until the backend becomes reachable or the deadline expires. + } finally { + clearTimeout(requestTimeout); + signal?.removeEventListener("abort", abortRequest); + } + + if (Date.now() >= deadline) { + throw new Error(`Timed out waiting for backend readiness at ${baseUrl}.`); + } + + await delay(intervalMs, signal); + } +} diff --git a/apps/desktop/src/clientPersistence.test.ts b/apps/desktop/src/clientPersistence.test.ts new file mode 100644 index 0000000000..df2178c0b0 --- /dev/null +++ b/apps/desktop/src/clientPersistence.test.ts @@ -0,0 +1,234 @@ +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; + +import { + EnvironmentId, + type ClientSettings, + type PersistedSavedEnvironmentRecord, +} from "@t3tools/contracts"; +import { afterEach, describe, expect, it } from "vitest"; + +import { + readClientSettings, + readSavedEnvironmentRegistry, + readSavedEnvironmentSecret, + removeSavedEnvironmentSecret, + writeClientSettings, + writeSavedEnvironmentRegistry, + writeSavedEnvironmentSecret, + type DesktopSecretStorage, +} from "./clientPersistence"; + +const tempDirectories: string[] = []; + +afterEach(() => { + for (const directory of tempDirectories.splice(0)) { + fs.rmSync(directory, { recursive: true, force: true }); + } +}); + +function makeTempPath(fileName: string): string { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "t3-client-persistence-test-")); + tempDirectories.push(directory); + return path.join(directory, fileName); +} + +function makeSecretStorage(available: boolean): DesktopSecretStorage { + return { + isEncryptionAvailable: () => available, + encryptString: (value) => Buffer.from(`enc:${value}`, "utf8"), + decryptString: (value) => { + const decoded = value.toString("utf8"); + if (!decoded.startsWith("enc:")) { + throw new Error("invalid secret"); + } + return decoded.slice("enc:".length); + }, + }; +} + +const clientSettings: ClientSettings = { + confirmThreadArchive: true, + confirmThreadDelete: false, + diffWordWrap: true, + sidebarProjectSortOrder: "manual", + sidebarThreadSortOrder: "created_at", + timestampFormat: "24-hour", +}; + +const savedRegistryRecord: PersistedSavedEnvironmentRecord = { + environmentId: EnvironmentId.make("environment-1"), + label: "Remote environment", + httpBaseUrl: "https://remote.example.com/", + wsBaseUrl: "wss://remote.example.com/", + createdAt: "2026-04-09T00:00:00.000Z", + lastConnectedAt: "2026-04-09T01:00:00.000Z", +}; + +describe("clientPersistence", () => { + it("persists and reloads client settings", () => { + const settingsPath = makeTempPath("client-settings.json"); + + writeClientSettings(settingsPath, clientSettings); + + expect(readClientSettings(settingsPath)).toEqual(clientSettings); + }); + + it("persists and reloads saved environment metadata", () => { + const registryPath = makeTempPath("saved-environments.json"); + + writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]); + + expect(readSavedEnvironmentRegistry(registryPath)).toEqual([savedRegistryRecord]); + }); + + it("persists encrypted saved environment secrets when encryption is available", () => { + const registryPath = makeTempPath("saved-environments.json"); + const secretStorage = makeSecretStorage(true); + + writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]); + + expect( + writeSavedEnvironmentSecret({ + registryPath, + environmentId: savedRegistryRecord.environmentId, + secret: "bearer-token", + secretStorage, + }), + ).toBe(true); + + expect( + readSavedEnvironmentSecret({ + registryPath, + environmentId: savedRegistryRecord.environmentId, + secretStorage, + }), + ).toBe("bearer-token"); + + expect(JSON.parse(fs.readFileSync(registryPath, "utf8"))).toEqual({ + records: [ + { + ...savedRegistryRecord, + encryptedBearerToken: Buffer.from("enc:bearer-token", "utf8").toString("base64"), + }, + ], + }); + }); + + it("preserves existing secrets when encryption is unavailable", () => { + const registryPath = makeTempPath("saved-environments.json"); + const availableSecretStorage = makeSecretStorage(true); + + writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]); + + writeSavedEnvironmentSecret({ + registryPath, + environmentId: savedRegistryRecord.environmentId, + secret: "bearer-token", + secretStorage: availableSecretStorage, + }); + + expect( + writeSavedEnvironmentSecret({ + registryPath, + environmentId: savedRegistryRecord.environmentId, + secret: "next-token", + secretStorage: makeSecretStorage(false), + }), + ).toBe(false); + + expect( + readSavedEnvironmentSecret({ + registryPath, + environmentId: savedRegistryRecord.environmentId, + secretStorage: availableSecretStorage, + }), + ).toBe("bearer-token"); + }); + + it("removes saved environment secrets", () => { + const registryPath = makeTempPath("saved-environments.json"); + const secretStorage = makeSecretStorage(true); + + writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]); + + writeSavedEnvironmentSecret({ + registryPath, + environmentId: savedRegistryRecord.environmentId, + secret: "bearer-token", + secretStorage, + }); + + removeSavedEnvironmentSecret({ + registryPath, + environmentId: savedRegistryRecord.environmentId, + }); + + expect( + readSavedEnvironmentSecret({ + registryPath, + environmentId: savedRegistryRecord.environmentId, + secretStorage, + }), + ).toBeNull(); + }); + + it("treats malformed secrets documents as empty", () => { + const registryPath = makeTempPath("saved-environments.json"); + fs.writeFileSync(registryPath, "{}\n", "utf8"); + + expect( + readSavedEnvironmentSecret({ + registryPath, + environmentId: savedRegistryRecord.environmentId, + secretStorage: makeSecretStorage(true), + }), + ).toBeNull(); + + expect(() => + removeSavedEnvironmentSecret({ + registryPath, + environmentId: savedRegistryRecord.environmentId, + }), + ).not.toThrow(); + }); + + it("returns false when writing a secret without metadata", () => { + const registryPath = makeTempPath("saved-environments.json"); + + expect( + writeSavedEnvironmentSecret({ + registryPath, + environmentId: savedRegistryRecord.environmentId, + secret: "bearer-token", + secretStorage: makeSecretStorage(true), + }), + ).toBe(false); + }); + + it("preserves encrypted secrets when metadata is rewritten", () => { + const registryPath = makeTempPath("saved-environments.json"); + const secretStorage = makeSecretStorage(true); + + writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]); + + writeSavedEnvironmentSecret({ + registryPath, + environmentId: savedRegistryRecord.environmentId, + secret: "bearer-token", + secretStorage, + }); + + writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]); + + expect(readSavedEnvironmentRegistry(registryPath)).toEqual([savedRegistryRecord]); + expect( + readSavedEnvironmentSecret({ + registryPath, + environmentId: savedRegistryRecord.environmentId, + secretStorage, + }), + ).toBe("bearer-token"); + }); +}); diff --git a/apps/desktop/src/clientPersistence.ts b/apps/desktop/src/clientPersistence.ts new file mode 100644 index 0000000000..183de1a971 --- /dev/null +++ b/apps/desktop/src/clientPersistence.ts @@ -0,0 +1,216 @@ +import * as FS from "node:fs"; +import * as Path from "node:path"; + +import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts"; +import { Predicate } from "effect"; + +interface ClientSettingsDocument { + readonly settings: ClientSettings; +} + +interface PersistedSavedEnvironmentStorageRecord extends PersistedSavedEnvironmentRecord { + readonly encryptedBearerToken?: string; +} + +interface SavedEnvironmentRegistryDocument { + readonly records: readonly PersistedSavedEnvironmentStorageRecord[]; +} + +export interface DesktopSecretStorage { + readonly isEncryptionAvailable: () => boolean; + readonly encryptString: (value: string) => Buffer; + readonly decryptString: (value: Buffer) => string; +} + +function readJsonFile(filePath: string): T | null { + try { + if (!FS.existsSync(filePath)) { + return null; + } + return JSON.parse(FS.readFileSync(filePath, "utf8")) as T; + } catch { + return null; + } +} + +function writeJsonFile(filePath: string, value: unknown): void { + const directory = Path.dirname(filePath); + const tempPath = `${filePath}.${process.pid}.${Date.now()}.tmp`; + FS.mkdirSync(directory, { recursive: true }); + FS.writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, "utf8"); + FS.renameSync(tempPath, filePath); +} + +function isPersistedSavedEnvironmentStorageRecord( + value: unknown, +): value is PersistedSavedEnvironmentStorageRecord { + return ( + Predicate.isObject(value) && + typeof value.environmentId === "string" && + typeof value.label === "string" && + typeof value.httpBaseUrl === "string" && + typeof value.wsBaseUrl === "string" && + typeof value.createdAt === "string" && + (value.lastConnectedAt === null || typeof value.lastConnectedAt === "string") && + (value.encryptedBearerToken === undefined || typeof value.encryptedBearerToken === "string") + ); +} + +function readSavedEnvironmentRegistryDocument(filePath: string): SavedEnvironmentRegistryDocument { + const parsed = readJsonFile(filePath); + if (!Predicate.isObject(parsed)) { + return { records: [] }; + } + + return { + records: Array.isArray(parsed.records) + ? parsed.records.filter(isPersistedSavedEnvironmentStorageRecord) + : [], + }; +} + +function toPersistedSavedEnvironmentRecord( + record: PersistedSavedEnvironmentStorageRecord, +): PersistedSavedEnvironmentRecord { + return { + environmentId: record.environmentId, + label: record.label, + httpBaseUrl: record.httpBaseUrl, + wsBaseUrl: record.wsBaseUrl, + createdAt: record.createdAt, + lastConnectedAt: record.lastConnectedAt, + }; +} + +export function readClientSettings(settingsPath: string): ClientSettings | null { + return readJsonFile(settingsPath)?.settings ?? null; +} + +export function writeClientSettings(settingsPath: string, settings: ClientSettings): void { + writeJsonFile(settingsPath, { settings } satisfies ClientSettingsDocument); +} + +export function readSavedEnvironmentRegistry( + registryPath: string, +): readonly PersistedSavedEnvironmentRecord[] { + return readSavedEnvironmentRegistryDocument(registryPath).records.map((record) => + toPersistedSavedEnvironmentRecord(record), + ); +} + +export function writeSavedEnvironmentRegistry( + registryPath: string, + records: readonly PersistedSavedEnvironmentRecord[], +): void { + const currentDocument = readSavedEnvironmentRegistryDocument(registryPath); + const encryptedBearerTokenById = new Map( + currentDocument.records.flatMap((record) => + record.encryptedBearerToken + ? [[record.environmentId, record.encryptedBearerToken] as const] + : [], + ), + ); + writeJsonFile(registryPath, { + records: records.map((record) => { + const encryptedBearerToken = encryptedBearerTokenById.get(record.environmentId); + return encryptedBearerToken + ? { + environmentId: record.environmentId, + label: record.label, + httpBaseUrl: record.httpBaseUrl, + wsBaseUrl: record.wsBaseUrl, + createdAt: record.createdAt, + lastConnectedAt: record.lastConnectedAt, + encryptedBearerToken, + } + : record; + }), + } satisfies SavedEnvironmentRegistryDocument); +} + +export function readSavedEnvironmentSecret(input: { + readonly registryPath: string; + readonly environmentId: string; + readonly secretStorage: DesktopSecretStorage; +}): string | null { + const document = readSavedEnvironmentRegistryDocument(input.registryPath); + const encoded = document.records.find( + (record) => record.environmentId === input.environmentId, + )?.encryptedBearerToken; + if (!encoded) { + return null; + } + + if (!input.secretStorage.isEncryptionAvailable()) { + return null; + } + + try { + return input.secretStorage.decryptString(Buffer.from(encoded, "base64")); + } catch { + return null; + } +} + +export function writeSavedEnvironmentSecret(input: { + readonly registryPath: string; + readonly environmentId: string; + readonly secret: string; + readonly secretStorage: DesktopSecretStorage; +}): boolean { + const document = readSavedEnvironmentRegistryDocument(input.registryPath); + + if (!input.secretStorage.isEncryptionAvailable()) { + return false; + } + + let found = false; + + writeJsonFile(input.registryPath, { + records: document.records.map((record) => { + if (record.environmentId !== input.environmentId) { + return record; + } + + found = true; + const encryptedBearerToken = input.secretStorage + .encryptString(input.secret) + .toString("base64"); + return { + environmentId: record.environmentId, + label: record.label, + httpBaseUrl: record.httpBaseUrl, + wsBaseUrl: record.wsBaseUrl, + createdAt: record.createdAt, + lastConnectedAt: record.lastConnectedAt, + encryptedBearerToken, + } satisfies PersistedSavedEnvironmentStorageRecord; + }), + } satisfies SavedEnvironmentRegistryDocument); + return found; +} + +export function removeSavedEnvironmentSecret(input: { + readonly registryPath: string; + readonly environmentId: string; +}): void { + const document = readSavedEnvironmentRegistryDocument(input.registryPath); + if ( + !document.records.some( + (record) => + record.environmentId === input.environmentId && record.encryptedBearerToken !== undefined, + ) + ) { + return; + } + + writeJsonFile(input.registryPath, { + records: document.records.map((record) => { + if (record.environmentId !== input.environmentId) { + return record; + } + + return toPersistedSavedEnvironmentRecord(record); + }), + } satisfies SavedEnvironmentRegistryDocument); +} diff --git a/apps/desktop/src/desktopSettings.test.ts b/apps/desktop/src/desktopSettings.test.ts new file mode 100644 index 0000000000..e687bf544e --- /dev/null +++ b/apps/desktop/src/desktopSettings.test.ts @@ -0,0 +1,64 @@ +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +import { + DEFAULT_DESKTOP_SETTINGS, + readDesktopSettings, + setDesktopServerExposurePreference, + writeDesktopSettings, +} from "./desktopSettings"; + +const tempDirectories: string[] = []; + +afterEach(() => { + for (const directory of tempDirectories.splice(0)) { + fs.rmSync(directory, { recursive: true, force: true }); + } +}); + +function makeSettingsPath() { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "t3-desktop-settings-test-")); + tempDirectories.push(directory); + return path.join(directory, "desktop-settings.json"); +} + +describe("desktopSettings", () => { + it("returns defaults when no settings file exists", () => { + expect(readDesktopSettings(makeSettingsPath())).toEqual(DEFAULT_DESKTOP_SETTINGS); + }); + + it("persists and reloads the configured server exposure mode", () => { + const settingsPath = makeSettingsPath(); + + writeDesktopSettings(settingsPath, { + serverExposureMode: "network-accessible", + }); + + expect(readDesktopSettings(settingsPath)).toEqual({ + serverExposureMode: "network-accessible", + }); + }); + + it("preserves the requested network-accessible preference across temporary fallback", () => { + expect( + setDesktopServerExposurePreference( + { + serverExposureMode: "local-only", + }, + "network-accessible", + ), + ).toEqual({ + serverExposureMode: "network-accessible", + }); + }); + + it("falls back to defaults when the settings file is malformed", () => { + const settingsPath = makeSettingsPath(); + fs.writeFileSync(settingsPath, "{not-json", "utf8"); + + expect(readDesktopSettings(settingsPath)).toEqual(DEFAULT_DESKTOP_SETTINGS); + }); +}); diff --git a/apps/desktop/src/desktopSettings.ts b/apps/desktop/src/desktopSettings.ts new file mode 100644 index 0000000000..80ef229ea2 --- /dev/null +++ b/apps/desktop/src/desktopSettings.ts @@ -0,0 +1,51 @@ +import * as FS from "node:fs"; +import * as Path from "node:path"; +import type { DesktopServerExposureMode } from "@t3tools/contracts"; + +export interface DesktopSettings { + readonly serverExposureMode: DesktopServerExposureMode; +} + +export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = { + serverExposureMode: "local-only", +}; + +export function setDesktopServerExposurePreference( + settings: DesktopSettings, + requestedMode: DesktopServerExposureMode, +): DesktopSettings { + return settings.serverExposureMode === requestedMode + ? settings + : { + ...settings, + serverExposureMode: requestedMode, + }; +} + +export function readDesktopSettings(settingsPath: string): DesktopSettings { + try { + if (!FS.existsSync(settingsPath)) { + return DEFAULT_DESKTOP_SETTINGS; + } + + const raw = FS.readFileSync(settingsPath, "utf8"); + const parsed = JSON.parse(raw) as { + readonly serverExposureMode?: unknown; + }; + + return { + serverExposureMode: + parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only", + }; + } catch { + return DEFAULT_DESKTOP_SETTINGS; + } +} + +export function writeDesktopSettings(settingsPath: string, settings: DesktopSettings): void { + const directory = Path.dirname(settingsPath); + const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`; + FS.mkdirSync(directory, { recursive: true }); + FS.writeFileSync(tempPath, `${JSON.stringify(settings, null, 2)}\n`, "utf8"); + FS.renameSync(tempPath, settingsPath); +} diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index f1086e9c29..f6e7544d0b 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -7,18 +7,23 @@ import * as Path from "node:path"; import { app, BrowserWindow, + clipboard, dialog, ipcMain, Menu, nativeImage, nativeTheme, protocol, + safeStorage, shell, } from "electron"; import type { MenuItemConstructorOptions } from "electron"; -import * as Effect from "effect/Effect"; import type { + ClientSettings, DesktopTheme, + DesktopServerExposureMode, + DesktopServerExposureState, + PersistedSavedEnvironmentRecord, DesktopUpdateActionResult, DesktopUpdateCheckResult, DesktopUpdateState, @@ -26,9 +31,27 @@ import type { import { autoUpdater } from "electron-updater"; import type { ContextMenuItem } from "@t3tools/contracts"; -import { NetService } from "@t3tools/shared/Net"; import { RotatingFileSink } from "@t3tools/shared/logging"; +import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings"; +import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort"; +import { + DEFAULT_DESKTOP_SETTINGS, + readDesktopSettings, + setDesktopServerExposurePreference, + writeDesktopSettings, +} from "./desktopSettings"; +import { + readClientSettings, + readSavedEnvironmentRegistry, + readSavedEnvironmentSecret, + removeSavedEnvironmentSecret, + writeClientSettings, + writeSavedEnvironmentRegistry, + writeSavedEnvironmentSecret, +} from "./clientPersistence"; +import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness"; import { showDesktopConfirmDialog } from "./confirmDialog"; +import { resolveDesktopServerExposure } from "./serverExposure"; import { syncShellEnvironment } from "./syncShellEnvironment"; import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState"; import { @@ -58,14 +81,28 @@ 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 GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap"; +const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings"; +const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings"; +const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry"; +const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry"; +const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret"; +const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret"; +const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret"; +const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state"; +const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode"; const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3"); const STATE_DIR = Path.join(BASE_DIR, "userdata"); +const DESKTOP_SETTINGS_PATH = Path.join(STATE_DIR, "desktop-settings.json"); +const CLIENT_SETTINGS_PATH = Path.join(STATE_DIR, "client-settings.json"); +const SAVED_ENVIRONMENT_REGISTRY_PATH = Path.join(STATE_DIR, "saved-environments.json"); const DESKTOP_SCHEME = "t3"; 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; @@ -74,18 +111,29 @@ const LOG_DIR = Path.join(STATE_DIR, "logs"); const LOG_FILE_MAX_BYTES = 10 * 1024 * 1024; const LOG_FILE_MAX_FILES = 10; const APP_RUN_ID = Crypto.randomBytes(6).toString("hex"); +const SERVER_SETTINGS_PATH = Path.join(STATE_DIR, "settings.json"); const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000; const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000; const DESKTOP_UPDATE_CHANNEL = "latest"; const DESKTOP_UPDATE_ALLOW_PRERELEASE = false; +const DESKTOP_LOOPBACK_HOST = "127.0.0.1"; +const DESKTOP_REQUIRED_PORT_PROBE_HOSTS = ["0.0.0.0", "::"] as const; type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"]; +type LinuxDesktopNamedApp = Electron.App & { + setDesktopName?: (desktopName: string) => void; +}; let mainWindow: BrowserWindow | null = null; let backendProcess: ChildProcess.ChildProcess | null = null; let backendPort = 0; -let backendAuthToken = ""; +let backendBindHost = DESKTOP_LOOPBACK_HOST; +let backendBootstrapToken = ""; +let backendHttpUrl = ""; let backendWsUrl = ""; +let backendEndpointUrl: string | null = null; +let backendAdvertisedHost: string | null = null; +let backendReadinessAbortController: AbortController | null = null; let restartAttempt = 0; let restartTimer: ReturnType | null = null; let isQuitting = false; @@ -94,8 +142,12 @@ let aboutCommitHashCache: string | null | undefined; let desktopLogSink: RotatingFileSink | null = null; let backendLogSink: RotatingFileSink | null = null; let restoreStdIoCapture: (() => void) | null = null; +let backendObservabilitySettings = readPersistedBackendObservabilitySettings(); +let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH); +let desktopServerExposureMode: DesktopServerExposureMode = desktopSettings.serverExposureMode; let destructiveMenuIconCache: Electron.NativeImage | null | undefined; +const expectedBackendExitChildren = new WeakSet(); const desktopRuntimeInfo = resolveDesktopRuntimeInfo({ platform: process.platform, processArch: process.arch, @@ -116,17 +168,143 @@ function sanitizeLogValue(value: string): string { return value.replace(/\s+/g, " ").trim(); } +function readPersistedBackendObservabilitySettings(): { + readonly otlpTracesUrl: string | undefined; + readonly otlpMetricsUrl: string | undefined; +} { + try { + if (!FS.existsSync(SERVER_SETTINGS_PATH)) { + return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined }; + } + return parsePersistedServerObservabilitySettings(FS.readFileSync(SERVER_SETTINGS_PATH, "utf8")); + } catch (error) { + console.warn("[desktop] failed to read persisted backend observability settings", error); + return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined }; + } +} + +function resolveConfiguredDesktopBackendPort(rawPort: string | undefined): number | undefined { + if (!rawPort) { + return undefined; + } + + const parsedPort = Number.parseInt(rawPort, 10); + if (!Number.isInteger(parsedPort) || parsedPort < 1 || parsedPort > 65_535) { + return undefined; + } + + return parsedPort; +} + +function resolveDesktopDevServerUrl(): string { + const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim(); + if (!devServerUrl) { + throw new Error("VITE_DEV_SERVER_URL is required in desktop development."); + } + + return devServerUrl; +} + function backendChildEnv(): NodeJS.ProcessEnv { const env = { ...process.env }; delete env.T3CODE_PORT; - delete env.T3CODE_AUTH_TOKEN; delete env.T3CODE_MODE; delete env.T3CODE_NO_BROWSER; delete env.T3CODE_HOST; delete env.T3CODE_DESKTOP_WS_URL; + delete env.T3CODE_DESKTOP_LAN_ACCESS; + delete env.T3CODE_DESKTOP_LAN_HOST; return env; } +function getDesktopServerExposureState(): DesktopServerExposureState { + return { + mode: desktopServerExposureMode, + endpointUrl: backendEndpointUrl, + advertisedHost: backendAdvertisedHost, + }; +} + +function getDesktopSecretStorage() { + return { + isEncryptionAvailable: () => safeStorage.isEncryptionAvailable(), + encryptString: (value: string) => safeStorage.encryptString(value), + decryptString: (value: Buffer) => safeStorage.decryptString(value), + } as const; +} + +function resolveAdvertisedHostOverride(): string | undefined { + const override = process.env.T3CODE_DESKTOP_LAN_HOST?.trim(); + return override && override.length > 0 ? override : undefined; +} + +async function applyDesktopServerExposureMode( + mode: DesktopServerExposureMode, + options?: { readonly persist?: boolean; readonly rejectIfUnavailable?: boolean }, +): Promise { + const advertisedHostOverride = resolveAdvertisedHostOverride(); + const requestedMode = mode; + let exposure = resolveDesktopServerExposure({ + mode, + port: backendPort, + networkInterfaces: OS.networkInterfaces(), + ...(advertisedHostOverride ? { advertisedHostOverride } : {}), + }); + + if (requestedMode === "network-accessible" && exposure.endpointUrl === null) { + if (options?.rejectIfUnavailable) { + throw new Error("No reachable network address is available for this desktop right now."); + } + exposure = resolveDesktopServerExposure({ + mode: "local-only", + port: backendPort, + networkInterfaces: OS.networkInterfaces(), + ...(advertisedHostOverride ? { advertisedHostOverride } : {}), + }); + } + + desktopServerExposureMode = exposure.mode; + desktopSettings = setDesktopServerExposurePreference(desktopSettings, requestedMode); + backendBindHost = exposure.bindHost; + backendHttpUrl = exposure.localHttpUrl; + backendWsUrl = exposure.localWsUrl; + backendEndpointUrl = exposure.endpointUrl; + backendAdvertisedHost = exposure.advertisedHost; + + if (options?.persist) { + writeDesktopSettings(DESKTOP_SETTINGS_PATH, desktopSettings); + } + + return getDesktopServerExposureState(); +} + +function relaunchDesktopApp(reason: string): void { + writeDesktopLogHeader(`desktop relaunch requested reason=${reason}`); + setImmediate(() => { + isQuitting = true; + clearUpdatePollTimer(); + cancelBackendReadinessWait(); + void stopBackendAndWaitForExit() + .catch((error) => { + writeDesktopLogHeader( + `desktop relaunch backend shutdown warning message=${formatErrorMessage(error)}`, + ); + }) + .finally(() => { + restoreStdIoCapture?.(); + if (isDevelopment) { + app.exit(75); + return; + } + app.relaunch({ + execPath: process.execPath, + args: process.argv.slice(1), + }); + app.exit(0); + }); + }); +} + function writeDesktopLogHeader(message: string): void { if (!desktopLogSink) return; desktopLogSink.write(`[${logTimestamp()}] [${logScope("desktop")}] ${message}\n`); @@ -174,6 +352,27 @@ function getSafeTheme(rawTheme: unknown): DesktopTheme | null { return null; } +async function waitForBackendHttpReady(baseUrl: string): Promise { + cancelBackendReadinessWait(); + const controller = new AbortController(); + backendReadinessAbortController = controller; + + try { + await waitForHttpReady(baseUrl, { + signal: controller.signal, + }); + } finally { + if (backendReadinessAbortController === controller) { + backendReadinessAbortController = null; + } + } +} + +function cancelBackendReadinessWait(): void { + backendReadinessAbortController?.abort(); + backendReadinessAbortController = null; +} + function writeDesktopStreamChunk( streamName: "stdout" | "stderr", chunk: unknown, @@ -263,6 +462,10 @@ function captureBackendOutput(child: ChildProcess.ChildProcess): void { initializePackagedLogging(); +if (process.platform === "linux") { + app.commandLine.appendSwitch("class", LINUX_WM_CLASS); +} + function getDestructiveMenuIcon(): Electron.NativeImage | undefined { if (process.platform !== "darwin") return undefined; if (destructiveMenuIconCache !== undefined) { @@ -390,7 +593,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 { @@ -514,10 +717,7 @@ function dispatchMenuAction(action: string): void { const send = () => { if (targetWindow.isDestroyed()) return; targetWindow.webContents.send(MENU_ACTION_CHANNEL, action); - if (!targetWindow.isVisible()) { - targetWindow.show(); - } - targetWindow.focus(); + revealWindow(targetWindow); }; if (targetWindow.webContents.isLoadingMainFrame()) { @@ -529,12 +729,15 @@ function dispatchMenuAction(action: string): void { } function handleCheckForUpdatesMenuClick(): void { + const hasUpdateFeedConfig = + readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES); const disabledReason = getAutoUpdateDisabledReason({ isDevelopment, isPackaged: app.isPackaged, platform: process.platform, appImage: process.env.APPIMAGE, disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1", + hasUpdateFeedConfig, }); if (disabledReason) { console.info("[desktop-updater] Manual update check requested, but updates are disabled."); @@ -715,6 +918,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) { @@ -734,6 +941,26 @@ function clearUpdatePollTimer(): void { } } +function revealWindow(window: BrowserWindow): void { + if (window.isDestroyed()) { + return; + } + + if (window.isMinimized()) { + window.restore(); + } + + if (!window.isVisible()) { + window.show(); + } + + if (process.platform === "darwin") { + app.focus({ steal: true }); + } + + window.focus(); +} + function emitUpdateState(): void { for (const window of BrowserWindow.getAllWindows()) { if (window.isDestroyed()) continue; @@ -747,6 +974,8 @@ function setUpdateState(patch: Partial): void { } function shouldEnableAutoUpdates(): boolean { + const hasUpdateFeedConfig = + readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES); return ( getAutoUpdateDisabledReason({ isDevelopment, @@ -754,6 +983,7 @@ function shouldEnableAutoUpdates(): boolean { platform: process.platform, appImage: process.env.APPIMAGE, disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1", + hasUpdateFeedConfig, }) === null ); } @@ -837,17 +1067,6 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed } function configureAutoUpdater(): void { - const enabled = shouldEnableAutoUpdates(); - setUpdateState({ - ...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo), - enabled, - status: enabled ? "idle" : "disabled", - }); - if (!enabled) { - return; - } - updaterConfigured = true; - const githubToken = process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || ""; if (githubToken) { @@ -872,6 +1091,17 @@ function configureAutoUpdater(): void { }); } + const enabled = shouldEnableAutoUpdates(); + setUpdateState({ + ...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo), + enabled, + status: enabled ? "idle" : "disabled", + }); + if (!enabled) { + return; + } + updaterConfigured = true; + autoUpdater.autoDownload = false; autoUpdater.autoInstallOnAppQuit = false; // Keep alpha branding, but force all installs onto the stable update track. @@ -975,6 +1205,7 @@ function scheduleBackendRestart(reason: string): void { function startBackend(): void { if (isQuitting || backendProcess) return; + backendObservabilitySettings = readPersistedBackendObservabilitySettings(); const backendEntry = resolveBackendEntry(); if (!FS.existsSync(backendEntry)) { scheduleBackendRestart(`missing server entry at ${backendEntry}`); @@ -1002,7 +1233,14 @@ function startBackend(): void { noBrowser: true, port: backendPort, t3Home: BASE_DIR, - authToken: backendAuthToken, + host: backendBindHost, + desktopBootstrapToken: backendBootstrapToken, + ...(backendObservabilitySettings.otlpTracesUrl + ? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl } + : {}), + ...(backendObservabilitySettings.otlpMetricsUrl + ? { otlpMetricsUrl: backendObservabilitySettings.otlpMetricsUrl } + : {}), })}\n`, ); bootstrapStream.end(); @@ -1029,27 +1267,33 @@ function startBackend(): void { }); child.on("error", (error) => { + const wasExpected = expectedBackendExitChildren.has(child); if (backendProcess === child) { backendProcess = null; } closeBackendSession(`pid=${child.pid ?? "unknown"} error=${error.message}`); + if (wasExpected) { + return; + } scheduleBackendRestart(error.message); }); child.on("exit", (code, signal) => { + const wasExpected = expectedBackendExitChildren.has(child); if (backendProcess === child) { backendProcess = null; } closeBackendSession( `pid=${child.pid ?? "unknown"} code=${code ?? "null"} signal=${signal ?? "null"}`, ); - if (isQuitting) return; + if (isQuitting || wasExpected) return; const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`; scheduleBackendRestart(reason); }); } function stopBackend(): void { + cancelBackendReadinessWait(); if (restartTimer) { clearTimeout(restartTimer); restartTimer = null; @@ -1060,6 +1304,7 @@ function stopBackend(): void { if (!child) return; if (child.exitCode === null && child.signalCode === null) { + expectedBackendExitChildren.add(child); child.kill("SIGTERM"); setTimeout(() => { if (child.exitCode === null && child.signalCode === null) { @@ -1070,6 +1315,7 @@ function stopBackend(): void { } async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise { + cancelBackendReadinessWait(); if (restartTimer) { clearTimeout(restartTimer); restartTimer = null; @@ -1080,6 +1326,7 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise { if (!child) return; const backendChild = child; if (backendChild.exitCode !== null || backendChild.signalCode !== null) return; + expectedBackendExitChildren.add(backendChild); await new Promise((resolve) => { let settled = false; @@ -1121,9 +1368,116 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise { } function registerIpcHandlers(): void { - ipcMain.removeAllListeners(GET_WS_URL_CHANNEL); - ipcMain.on(GET_WS_URL_CHANNEL, (event) => { - event.returnValue = backendWsUrl; + ipcMain.removeAllListeners(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL); + ipcMain.on(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL, (event) => { + event.returnValue = { + label: "Local environment", + httpBaseUrl: backendHttpUrl || null, + wsBaseUrl: backendWsUrl || null, + bootstrapToken: backendBootstrapToken || undefined, + } as const; + }); + + ipcMain.removeHandler(GET_CLIENT_SETTINGS_CHANNEL); + ipcMain.handle(GET_CLIENT_SETTINGS_CHANNEL, async () => readClientSettings(CLIENT_SETTINGS_PATH)); + + ipcMain.removeHandler(SET_CLIENT_SETTINGS_CHANNEL); + ipcMain.handle(SET_CLIENT_SETTINGS_CHANNEL, async (_event, rawSettings: unknown) => { + if (typeof rawSettings !== "object" || rawSettings === null) { + throw new Error("Invalid client settings payload."); + } + + writeClientSettings(CLIENT_SETTINGS_PATH, rawSettings as ClientSettings); + }); + + ipcMain.removeHandler(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL); + ipcMain.handle(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, async () => + readSavedEnvironmentRegistry(SAVED_ENVIRONMENT_REGISTRY_PATH), + ); + + ipcMain.removeHandler(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL); + ipcMain.handle(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, async (_event, rawRecords: unknown) => { + if (!Array.isArray(rawRecords)) { + throw new Error("Invalid saved environment registry payload."); + } + + writeSavedEnvironmentRegistry( + SAVED_ENVIRONMENT_REGISTRY_PATH, + rawRecords as readonly PersistedSavedEnvironmentRecord[], + ); + }); + + ipcMain.removeHandler(GET_SAVED_ENVIRONMENT_SECRET_CHANNEL); + ipcMain.handle( + GET_SAVED_ENVIRONMENT_SECRET_CHANNEL, + async (_event, rawEnvironmentId: unknown) => { + if (typeof rawEnvironmentId !== "string" || rawEnvironmentId.trim().length === 0) { + return null; + } + + return readSavedEnvironmentSecret({ + registryPath: SAVED_ENVIRONMENT_REGISTRY_PATH, + environmentId: rawEnvironmentId, + secretStorage: getDesktopSecretStorage(), + }); + }, + ); + + ipcMain.removeHandler(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL); + ipcMain.handle( + SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, + async (_event, rawEnvironmentId: unknown, rawSecret: unknown) => { + if (typeof rawEnvironmentId !== "string" || rawEnvironmentId.trim().length === 0) { + throw new Error("Invalid saved environment id."); + } + if (typeof rawSecret !== "string" || rawSecret.trim().length === 0) { + throw new Error("Invalid saved environment secret."); + } + + return writeSavedEnvironmentSecret({ + registryPath: SAVED_ENVIRONMENT_REGISTRY_PATH, + environmentId: rawEnvironmentId, + secret: rawSecret, + secretStorage: getDesktopSecretStorage(), + }); + }, + ); + + ipcMain.removeHandler(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL); + ipcMain.handle( + REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, + async (_event, rawEnvironmentId: unknown) => { + if (typeof rawEnvironmentId !== "string" || rawEnvironmentId.trim().length === 0) { + return; + } + + removeSavedEnvironmentSecret({ + registryPath: SAVED_ENVIRONMENT_REGISTRY_PATH, + environmentId: rawEnvironmentId, + }); + }, + ); + + ipcMain.removeHandler(GET_SERVER_EXPOSURE_STATE_CHANNEL); + ipcMain.handle(GET_SERVER_EXPOSURE_STATE_CHANNEL, async () => getDesktopServerExposureState()); + + ipcMain.removeHandler(SET_SERVER_EXPOSURE_MODE_CHANNEL); + ipcMain.handle(SET_SERVER_EXPOSURE_MODE_CHANNEL, async (_event, rawMode: unknown) => { + if (rawMode !== "local-only" && rawMode !== "network-accessible") { + throw new Error("Invalid desktop server exposure input."); + } + + const nextMode = rawMode as DesktopServerExposureMode; + if (nextMode === desktopServerExposureMode) { + return getDesktopServerExposureState(); + } + + const nextState = await applyDesktopServerExposureMode(nextMode, { + persist: true, + rejectIfUnavailable: true, + }); + relaunchDesktopApp(`serverExposureMode=${nextMode}`); + return nextState; }); ipcMain.removeHandler(PICK_FOLDER_CHANNEL); @@ -1291,14 +1645,19 @@ function getIconOption(): { icon: string } | Record { return iconPath ? { icon: iconPath } : {}; } +function getInitialWindowBackgroundColor(): string { + return nativeTheme.shouldUseDarkColors ? "#0a0a0a" : "#ffffff"; +} + function createWindow(): BrowserWindow { const window = new BrowserWindow({ width: 1100, height: 780, minWidth: 840, minHeight: 620, - show: false, + show: isDevelopment, autoHideMenuBar: true, + backgroundColor: getInitialWindowBackgroundColor(), ...getIconOption(), title: APP_DISPLAY_NAME, titleBarStyle: "hiddenInset", @@ -1329,6 +1688,22 @@ function createWindow(): BrowserWindow { menuTemplate.push({ type: "separator" }); } + const externalUrl = getSafeExternalUrl(params.linkURL); + if (externalUrl) { + menuTemplate.push( + { label: "Copy Link", click: () => clipboard.writeText(params.linkURL) }, + { type: "separator" }, + ); + } + + if (params.mediaType === "image") { + menuTemplate.push({ + label: "Copy Image", + click: () => window.webContents.copyImageAt(params.x, params.y), + }); + menuTemplate.push({ type: "separator" }); + } + menuTemplate.push( { role: "cut", enabled: params.editFlags.canCut }, { role: "copy", enabled: params.editFlags.canCopy }, @@ -1355,15 +1730,20 @@ function createWindow(): BrowserWindow { window.setTitle(APP_DISPLAY_NAME); emitUpdateState(); }); - window.once("ready-to-show", () => { - window.show(); - }); + if (!isDevelopment) { + window.once("ready-to-show", () => { + revealWindow(window); + }); + } if (isDevelopment) { - void window.loadURL(process.env.VITE_DEV_SERVER_URL as string); + void window.loadURL(resolveDesktopDevServerUrl()); window.webContents.openDevTools({ mode: "detach" }); + setImmediate(() => { + revealWindow(window); + }); } else { - void window.loadURL(`${DESKTOP_SCHEME}://app/index.html`); + void window.loadURL(resolveDesktopWindowUrl()); } window.on("closed", () => { @@ -1375,6 +1755,14 @@ function createWindow(): BrowserWindow { return window; } +function resolveDesktopWindowUrl(): string { + if (backendHttpUrl) { + return backendHttpUrl; + } + + return `${DESKTOP_SCHEME}://app`; +} + // Override Electron's userData path before the `ready` event so that // Chromium session data uses a filesystem-friendly directory name. // Must be called synchronously at the top level — before `app.whenReady()`. @@ -1384,21 +1772,72 @@ configureAppIdentity(); async function bootstrap(): Promise { writeDesktopLogHeader("bootstrap start"); - backendPort = await Effect.service(NetService).pipe( - Effect.flatMap((net) => net.reserveLoopbackPort()), - Effect.provide(NetService.layer), - Effect.runPromise, + const configuredBackendPort = resolveConfiguredDesktopBackendPort(process.env.T3CODE_PORT); + if (isDevelopment && configuredBackendPort === undefined) { + throw new Error("T3CODE_PORT is required in desktop development."); + } + + backendPort = + configuredBackendPort ?? + (await resolveDesktopBackendPort({ + host: DESKTOP_LOOPBACK_HOST, + startPort: DEFAULT_DESKTOP_BACKEND_PORT, + requiredHosts: DESKTOP_REQUIRED_PORT_PROBE_HOSTS, + })); + writeDesktopLogHeader( + configuredBackendPort === undefined + ? `selected backend port via sequential scan startPort=${DEFAULT_DESKTOP_BACKEND_PORT} port=${backendPort}` + : `using configured backend port port=${backendPort}`, ); - writeDesktopLogHeader(`reserved backend port via NetService port=${backendPort}`); - backendAuthToken = Crypto.randomBytes(24).toString("hex"); - const baseUrl = `ws://127.0.0.1:${backendPort}`; - backendWsUrl = `${baseUrl}/?token=${encodeURIComponent(backendAuthToken)}`; - writeDesktopLogHeader(`bootstrap resolved websocket endpoint baseUrl=${baseUrl}`); + backendBootstrapToken = Crypto.randomBytes(24).toString("hex"); + if (desktopSettings.serverExposureMode !== DEFAULT_DESKTOP_SETTINGS.serverExposureMode) { + writeDesktopLogHeader( + `bootstrap restoring persisted server exposure mode mode=${desktopSettings.serverExposureMode}`, + ); + } + const serverExposureState = await applyDesktopServerExposureMode( + desktopSettings.serverExposureMode, + { + persist: desktopSettings.serverExposureMode !== DEFAULT_DESKTOP_SETTINGS.serverExposureMode, + }, + ); + writeDesktopLogHeader(`bootstrap resolved backend endpoint baseUrl=${backendHttpUrl}`); + if (serverExposureState.endpointUrl) { + writeDesktopLogHeader( + `bootstrap enabled network access endpointUrl=${serverExposureState.endpointUrl}`, + ); + } else if (desktopSettings.serverExposureMode === "network-accessible") { + writeDesktopLogHeader( + "bootstrap fell back to local-only because no advertised network host was available", + ); + } registerIpcHandlers(); writeDesktopLogHeader("bootstrap ipc handlers registered"); startBackend(); writeDesktopLogHeader("bootstrap backend start requested"); + + if (isDevelopment) { + mainWindow = createWindow(); + writeDesktopLogHeader("bootstrap main window created"); + void waitForBackendHttpReady(backendHttpUrl) + .then(() => { + writeDesktopLogHeader("bootstrap backend ready"); + }) + .catch((error) => { + if (isBackendReadinessAborted(error)) { + return; + } + writeDesktopLogHeader( + `bootstrap backend readiness warning message=${formatErrorMessage(error)}`, + ); + console.warn("[desktop] backend readiness check timed out during dev bootstrap", error); + }); + return; + } + + await waitForBackendHttpReady(backendHttpUrl); + writeDesktopLogHeader("bootstrap backend ready"); mainWindow = createWindow(); writeDesktopLogHeader("bootstrap main window created"); } @@ -1408,6 +1847,7 @@ app.on("before-quit", () => { updateInstallInFlight = false; writeDesktopLogHeader("before-quit received"); clearUpdatePollTimer(); + cancelBackendReadinessWait(); stopBackend(); restoreStdIoCapture?.(); }); @@ -1421,13 +1861,19 @@ app registerDesktopProtocol(); configureAutoUpdater(); void bootstrap().catch((error) => { + if (isBackendReadinessAborted(error) && isQuitting) { + return; + } handleFatalStartupError("bootstrap", error); }); app.on("activate", () => { - if (BrowserWindow.getAllWindows().length === 0) { - mainWindow = createWindow(); + const existingWindow = mainWindow ?? BrowserWindow.getAllWindows()[0]; + if (existingWindow) { + revealWindow(existingWindow); + return; } + mainWindow = createWindow(); }); }) .catch((error) => { @@ -1446,6 +1892,7 @@ if (process.platform !== "win32") { isQuitting = true; writeDesktopLogHeader("SIGINT received"); clearUpdatePollTimer(); + cancelBackendReadinessWait(); stopBackend(); restoreStdIoCapture?.(); app.quit(); diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 3d59db1714..e3107a9248 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -12,13 +12,38 @@ 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"; +const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap"; +const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings"; +const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings"; +const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry"; +const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry"; +const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret"; +const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret"; +const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret"; +const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state"; +const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode"; contextBridge.exposeInMainWorld("desktopBridge", { - getWsUrl: () => { - const result = ipcRenderer.sendSync(GET_WS_URL_CHANNEL); - return typeof result === "string" ? result : null; + getLocalEnvironmentBootstrap: () => { + const result = ipcRenderer.sendSync(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL); + if (typeof result !== "object" || result === null) { + return null; + } + return result as ReturnType; }, + getClientSettings: () => ipcRenderer.invoke(GET_CLIENT_SETTINGS_CHANNEL), + setClientSettings: (settings) => ipcRenderer.invoke(SET_CLIENT_SETTINGS_CHANNEL, settings), + getSavedEnvironmentRegistry: () => ipcRenderer.invoke(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL), + setSavedEnvironmentRegistry: (records) => + ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, records), + getSavedEnvironmentSecret: (environmentId) => + ipcRenderer.invoke(GET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId), + setSavedEnvironmentSecret: (environmentId, secret) => + ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId, secret), + removeSavedEnvironmentSecret: (environmentId) => + ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId), + getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL), + setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode), pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL), confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message), setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme), diff --git a/apps/desktop/src/serverExposure.test.ts b/apps/desktop/src/serverExposure.test.ts new file mode 100644 index 0000000000..b1ae4bef4f --- /dev/null +++ b/apps/desktop/src/serverExposure.test.ts @@ -0,0 +1,139 @@ +import { describe, expect, it } from "vitest"; + +import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure"; + +describe("resolveLanAdvertisedHost", () => { + it("prefers an explicit host override", () => { + expect( + resolveLanAdvertisedHost( + { + en0: [ + { + address: "192.168.1.44", + family: "IPv4", + internal: false, + netmask: "255.255.255.0", + cidr: "192.168.1.44/24", + mac: "00:00:00:00:00:00", + }, + ], + }, + "10.0.0.9", + ), + ).toBe("10.0.0.9"); + }); + + it("returns the first usable non-internal IPv4 address", () => { + expect( + resolveLanAdvertisedHost( + { + lo0: [ + { + address: "127.0.0.1", + family: "IPv4", + internal: true, + netmask: "255.0.0.0", + cidr: "127.0.0.1/8", + mac: "00:00:00:00:00:00", + }, + ], + en0: [ + { + address: "192.168.1.44", + family: "IPv4", + internal: false, + netmask: "255.255.255.0", + cidr: "192.168.1.44/24", + mac: "00:00:00:00:00:00", + }, + ], + }, + undefined, + ), + ).toBe("192.168.1.44"); + }); + + it("returns null when no usable network address is available", () => { + expect( + resolveLanAdvertisedHost( + { + lo0: [ + { + address: "127.0.0.1", + family: "IPv4", + internal: true, + netmask: "255.0.0.0", + cidr: "127.0.0.1/8", + mac: "00:00:00:00:00:00", + }, + ], + }, + undefined, + ), + ).toBeNull(); + }); +}); + +describe("resolveDesktopServerExposure", () => { + it("keeps the desktop server loopback-only when local-only mode is selected", () => { + expect( + resolveDesktopServerExposure({ + mode: "local-only", + port: 3773, + networkInterfaces: {}, + }), + ).toEqual({ + mode: "local-only", + bindHost: "127.0.0.1", + localHttpUrl: "http://127.0.0.1:3773", + localWsUrl: "ws://127.0.0.1:3773", + endpointUrl: null, + advertisedHost: null, + }); + }); + + it("binds to all interfaces in network-accessible mode", () => { + expect( + resolveDesktopServerExposure({ + mode: "network-accessible", + port: 3773, + networkInterfaces: { + en0: [ + { + address: "192.168.1.44", + family: "IPv4", + internal: false, + netmask: "255.255.255.0", + cidr: "192.168.1.44/24", + mac: "00:00:00:00:00:00", + }, + ], + }, + }), + ).toEqual({ + mode: "network-accessible", + bindHost: "0.0.0.0", + localHttpUrl: "http://127.0.0.1:3773", + localWsUrl: "ws://127.0.0.1:3773", + endpointUrl: "http://192.168.1.44:3773", + advertisedHost: "192.168.1.44", + }); + }); + + it("stays network-accessible even when no LAN address is currently detectable", () => { + expect( + resolveDesktopServerExposure({ + mode: "network-accessible", + port: 3773, + networkInterfaces: {}, + }), + ).toEqual({ + mode: "network-accessible", + bindHost: "0.0.0.0", + localHttpUrl: "http://127.0.0.1:3773", + localWsUrl: "ws://127.0.0.1:3773", + endpointUrl: null, + advertisedHost: null, + }); + }); +}); diff --git a/apps/desktop/src/serverExposure.ts b/apps/desktop/src/serverExposure.ts new file mode 100644 index 0000000000..65c99b60e1 --- /dev/null +++ b/apps/desktop/src/serverExposure.ts @@ -0,0 +1,80 @@ +import type { NetworkInterfaceInfo } from "node:os"; +import type { DesktopServerExposureMode } from "@t3tools/contracts"; + +const DESKTOP_LOOPBACK_HOST = "127.0.0.1"; +const DESKTOP_LAN_BIND_HOST = "0.0.0.0"; + +export interface DesktopServerExposure { + readonly mode: DesktopServerExposureMode; + readonly bindHost: string; + readonly localHttpUrl: string; + readonly localWsUrl: string; + readonly endpointUrl: string | null; + readonly advertisedHost: string | null; +} + +const normalizeOptionalHost = (value: string | undefined): string | undefined => { + const normalized = value?.trim(); + return normalized && normalized.length > 0 ? normalized : undefined; +}; + +const isUsableLanIpv4Address = (address: string): boolean => + !address.startsWith("127.") && !address.startsWith("169.254."); + +export function resolveLanAdvertisedHost( + networkInterfaces: NodeJS.Dict, + explicitHost: string | undefined, +): string | null { + const normalizedExplicitHost = normalizeOptionalHost(explicitHost); + if (normalizedExplicitHost) { + return normalizedExplicitHost; + } + + for (const interfaceAddresses of Object.values(networkInterfaces)) { + if (!interfaceAddresses) continue; + + for (const address of interfaceAddresses) { + if (address.internal) continue; + if (address.family !== "IPv4") continue; + if (!isUsableLanIpv4Address(address.address)) continue; + return address.address; + } + } + + return null; +} + +export function resolveDesktopServerExposure(input: { + readonly mode: DesktopServerExposureMode; + readonly port: number; + readonly networkInterfaces: NodeJS.Dict; + readonly advertisedHostOverride?: string; +}): DesktopServerExposure { + const localHttpUrl = `http://${DESKTOP_LOOPBACK_HOST}:${input.port}`; + const localWsUrl = `ws://${DESKTOP_LOOPBACK_HOST}:${input.port}`; + + if (input.mode === "local-only") { + return { + mode: input.mode, + bindHost: DESKTOP_LOOPBACK_HOST, + localHttpUrl, + localWsUrl, + endpointUrl: null, + advertisedHost: null, + }; + } + + const advertisedHost = resolveLanAdvertisedHost( + input.networkInterfaces, + input.advertisedHostOverride, + ); + + return { + mode: input.mode, + bindHost: DESKTOP_LAN_BIND_HOST, + localHttpUrl, + localWsUrl, + endpointUrl: advertisedHost ? `http://${advertisedHost}:${input.port}` : null, + advertisedHost, + }; +} diff --git a/apps/desktop/src/updateState.test.ts b/apps/desktop/src/updateState.test.ts index 43b718bd00..8db92e1915 100644 --- a/apps/desktop/src/updateState.test.ts +++ b/apps/desktop/src/updateState.test.ts @@ -71,10 +71,37 @@ describe("getAutoUpdateDisabledReason", () => { platform: "darwin", appImage: undefined, disabledByEnv: false, + hasUpdateFeedConfig: true, }), ).toContain("packaged production builds"); }); + it("reports packaged local builds without an update feed as disabled", () => { + expect( + getAutoUpdateDisabledReason({ + isDevelopment: false, + isPackaged: true, + platform: "darwin", + appImage: undefined, + disabledByEnv: false, + hasUpdateFeedConfig: false, + }), + ).toContain("no update feed"); + }); + + it("allows packaged builds with an update feed", () => { + expect( + getAutoUpdateDisabledReason({ + isDevelopment: false, + isPackaged: true, + platform: "darwin", + appImage: undefined, + disabledByEnv: false, + hasUpdateFeedConfig: true, + }), + ).toBeNull(); + }); + it("reports env-disabled auto updates", () => { expect( getAutoUpdateDisabledReason({ @@ -83,6 +110,7 @@ describe("getAutoUpdateDisabledReason", () => { platform: "darwin", appImage: undefined, disabledByEnv: true, + hasUpdateFeedConfig: true, }), ).toContain("T3CODE_DISABLE_AUTO_UPDATE"); }); @@ -95,6 +123,7 @@ describe("getAutoUpdateDisabledReason", () => { platform: "linux", appImage: undefined, disabledByEnv: false, + hasUpdateFeedConfig: true, }), ).toContain("AppImage"); }); diff --git a/apps/desktop/src/updateState.ts b/apps/desktop/src/updateState.ts index 8c8ef1ddc9..928bb40886 100644 --- a/apps/desktop/src/updateState.ts +++ b/apps/desktop/src/updateState.ts @@ -34,7 +34,11 @@ export function getAutoUpdateDisabledReason(args: { platform: NodeJS.Platform; appImage?: string | undefined; disabledByEnv: boolean; + hasUpdateFeedConfig: boolean; }): string | null { + if (!args.hasUpdateFeedConfig) { + return "Automatic updates are not available because no update feed is configured."; + } if (args.isDevelopment || !args.isPackaged) { return "Automatic updates are only available in packaged production builds."; } diff --git a/apps/marketing/src/pages/download.astro b/apps/marketing/src/pages/download.astro index 0cf31a82e4..54454d4026 100644 --- a/apps/marketing/src/pages/download.astro +++ b/apps/marketing/src/pages/download.astro @@ -1,5 +1,6 @@ --- import Layout from "../layouts/Layout.astro"; +import { RELEASES_URL } from "../lib/releases"; --- @@ -17,11 +18,11 @@ import Layout from "../layouts/Layout.astro";

macOS

- + Apple Silicon (arm64) .dmg - + Intel (x64) .dmg @@ -35,7 +36,7 @@ import Layout from "../layouts/Layout.astro";

Windows

- + Windows 10, 11 .exe @@ -49,7 +50,7 @@ import Layout from "../layouts/Layout.astro";

Linux

- + x86_64 AppImage diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.ts index 9340b9460d..6daa43ca42 100644 --- a/apps/server/integration/OrchestrationEngineHarness.integration.ts +++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts @@ -26,6 +26,7 @@ import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts"; import { GitCoreLive } from "../src/git/Layers/GitCore.ts"; import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts"; +import { GitStatusBroadcaster } from "../src/git/Services/GitStatusBroadcaster.ts"; import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts"; import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts"; import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts"; @@ -45,10 +46,11 @@ import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts"; import { ProviderService } from "../src/provider/Services/ProviderService.ts"; import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts"; import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts"; +import { RepositoryIdentityResolverLive } from "../src/project/Layers/RepositoryIdentityResolver.ts"; import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts"; import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts"; import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts"; -import { RuntimeReceiptBusLive } from "../src/orchestration/Layers/RuntimeReceiptBus.ts"; +import { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts"; import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts"; import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts"; import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts"; @@ -69,6 +71,7 @@ import { } 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, { @@ -125,7 +128,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; @@ -288,14 +291,15 @@ export const makeOrchestrationIntegrationHarness = ( ); const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive)); + const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive; const runtimeServicesLayer = Layer.mergeAll( - orchestrationLayer, - OrchestrationProjectionSnapshotQueryLive, + projectionSnapshotQueryLayer, + orchestrationLayer.pipe(Layer.provide(projectionSnapshotQueryLayer)), ProjectionCheckpointRepositoryLive, ProjectionPendingApprovalRepositoryLive, checkpointStoreLayer, providerLayer, - RuntimeReceiptBusLive, + RuntimeReceiptBusTest, ); const serverSettingsLayer = ServerSettingsService.layerTest(); const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe( @@ -318,20 +322,41 @@ export const makeOrchestrationIntegrationHarness = ( ); const checkpointReactorLayer = CheckpointReactorLive.pipe( Layer.provideMerge(runtimeServicesLayer), + Layer.provideMerge( + Layer.succeed(GitStatusBroadcaster, { + getStatus: () => Effect.die("getStatus should not be called in this test"), + refreshLocalStatus: () => + Effect.succeed({ + isRepo: true, + hasOriginRemote: false, + isDefaultBranch: true, + branch: "main", + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + }), + refreshStatus: () => Effect.die("refreshStatus should not be called in this test"), + streamStatus: () => Stream.empty, + }), + ), Layer.provideMerge( WorkspaceEntriesLive.pipe( + Layer.provide(WorkspacePathsLive), Layer.provideMerge(gitCoreLayer), Layer.provide(NodeServices.layer), ), ), + Layer.provideMerge(WorkspacePathsLive), ); const orchestrationReactorLayer = OrchestrationReactorLive.pipe( Layer.provideMerge(runtimeIngestionLayer), Layer.provideMerge(providerCommandReactorLayer), Layer.provideMerge(checkpointReactorLayer), ); - const layer = orchestrationReactorLayer.pipe( + const layer = Layer.empty.pipe( + Layer.provideMerge(runtimeServicesLayer), + Layer.provideMerge(orchestrationReactorLayer), Layer.provide(persistenceLayer), + Layer.provideMerge(RepositoryIdentityResolverLive), Layer.provideMerge(ServerSettingsService.layerTest()), Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)), Layer.provideMerge(NodeServices.layer), @@ -370,7 +395,7 @@ export const makeOrchestrationIntegrationHarness = ( runtime.runPromise(reactor.start().pipe(Scope.provide(scope))), ).pipe(Effect.orDie); const receiptHistory = yield* Ref.make>([]); - yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) => + yield* Stream.runForEach(runtimeReceiptBus.streamEventsForTest, (receipt) => Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid), ).pipe(Effect.forkIn(scope)); yield* Effect.sleep(10); @@ -413,7 +438,7 @@ export const makeOrchestrationIntegrationHarness = ( ) => waitFor( pendingApprovalRepository - .getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) }) + .getByRequestId({ requestId: ApprovalRequestId.make(requestId) }) .pipe( Effect.map((row) => Option.match(row, { diff --git a/apps/server/integration/TestProviderAdapter.integration.ts b/apps/server/integration/TestProviderAdapter.integration.ts index 9c87d9821a..f497395307 100644 --- a/apps/server/integration/TestProviderAdapter.integration.ts +++ b/apps/server/integration/TestProviderAdapter.integration.ts @@ -289,7 +289,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter state.turnCount += 1; const turnCount = state.turnCount; - const turnId = TurnId.makeUnsafe(`turn-${turnCount}`); + const turnId = TurnId.make(`turn-${turnCount}`); const response = state.queuedResponses.shift(); if (!response) { @@ -307,7 +307,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter ...(fixtureEvent as Record), eventId: randomUUID(), provider, - sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)), + sessionId: RuntimeSessionId.make(String(input.threadId)), createdAt: nowIso(), }; rawEvent.threadId = state.snapshot.threadId; @@ -363,7 +363,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter if (deferredTurnCompletedEvents.length === 0) { yield* emit({ type: "turn.completed", - eventId: EventId.makeUnsafe(randomUUID()), + eventId: EventId.make(randomUUID()), provider, createdAt: nowIso(), threadId: state.snapshot.threadId, diff --git a/apps/server/integration/fixtures/providerRuntime.ts b/apps/server/integration/fixtures/providerRuntime.ts index 42e7ecd87d..14a45518c3 100644 --- a/apps/server/integration/fixtures/providerRuntime.ts +++ b/apps/server/integration/fixtures/providerRuntime.ts @@ -5,14 +5,14 @@ const PROVIDER = "codex" as const; const SESSION_ID = "fixture-session"; const THREAD_ID = "fixture-thread"; const TURN_ID = "fixture-turn"; -const REQUEST_ID = RuntimeRequestId.makeUnsafe("req-1"); +const REQUEST_ID = RuntimeRequestId.make("req-1"); function baseEvent( eventId: string, createdAt: string, ): Pick { return { - eventId: EventId.makeUnsafe(eventId), + eventId: EventId.make(eventId), provider: PROVIDER, sessionId: SESSION_ID, createdAt, diff --git a/apps/server/integration/orchestrationEngine.integration.test.ts b/apps/server/integration/orchestrationEngine.integration.test.ts index d6b1004749..a7f845672c 100644 --- a/apps/server/integration/orchestrationEngine.integration.test.ts +++ b/apps/server/integration/orchestrationEngine.integration.test.ts @@ -30,14 +30,13 @@ import type { } from "../src/orchestration/Services/RuntimeReceiptBus.ts"; import * as NodeServices from "@effect/platform-node/NodeServices"; -const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value); -const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value); -const asEventId = (value: string): EventId => EventId.makeUnsafe(value); -const asApprovalRequestId = (value: string): ApprovalRequestId => - ApprovalRequestId.makeUnsafe(value); +const asMessageId = (value: string): MessageId => MessageId.make(value); +const asProjectId = (value: string): ProjectId => ProjectId.make(value); +const asEventId = (value: string): EventId => EventId.make(value); +const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value); const PROJECT_ID = asProjectId("project-1"); -const THREAD_ID = ThreadId.makeUnsafe("thread-1"); +const THREAD_ID = ThreadId.make("thread-1"); const FIXTURE_TURN_ID = "fixture-turn"; const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1"); type IntegrationProvider = ProviderKind; @@ -57,7 +56,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; @@ -112,7 +111,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) => yield* harness.engine.dispatch({ type: "project.create", - commandId: CommandId.makeUnsafe("cmd-project-create"), + commandId: CommandId.make("cmd-project-create"), projectId: PROJECT_ID, title: "Integration Project", workspaceRoot: harness.workspaceDir, @@ -125,7 +124,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) => yield* harness.engine.dispatch({ type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-thread-create"), + commandId: CommandId.make("cmd-thread-create"), threadId: THREAD_ID, projectId: PROJECT_ID, title: "Integration Thread", @@ -150,7 +149,7 @@ const startTurn = (input: { }) => input.harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe(input.commandId), + commandId: CommandId.make(input.commandId), threadId: THREAD_ID, message: { messageId: asMessageId(input.messageId), @@ -261,7 +260,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)( yield* harness.engine.dispatch({ type: "project.create", - commandId: CommandId.makeUnsafe("cmd-project-create-real-codex"), + commandId: CommandId.make("cmd-project-create-real-codex"), projectId: PROJECT_ID, title: "Integration Project", workspaceRoot: harness.workspaceDir, @@ -274,7 +273,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)( yield* harness.engine.dispatch({ type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-thread-create-real-codex"), + commandId: CommandId.make("cmd-thread-create-real-codex"), threadId: THREAD_ID, projectId: PROJECT_ID, title: "Integration Thread", @@ -291,7 +290,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)( yield* harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-1"), + commandId: CommandId.make("cmd-turn-start-real-codex-1"), threadId: THREAD_ID, message: { messageId: asMessageId("msg-real-codex-1"), @@ -318,7 +317,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)( yield* harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-2"), + commandId: CommandId.make("cmd-turn-start-real-codex-2"), threadId: THREAD_ID, message: { messageId: asMessageId("msg-real-codex-2"), @@ -583,7 +582,7 @@ it.live("tracks approval requests and resolves pending approvals on user respons yield* harness.engine.dispatch({ type: "thread.approval.respond", - commandId: CommandId.makeUnsafe("cmd-approval-respond"), + commandId: CommandId.make("cmd-approval-respond"), threadId: THREAD_ID, requestId: APPROVAL_REQUEST_ID, decision: "accept", @@ -815,7 +814,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git yield* harness.engine.dispatch({ type: "thread.checkpoint.revert", - commandId: CommandId.makeUnsafe("cmd-checkpoint-revert"), + commandId: CommandId.make("cmd-checkpoint-revert"), threadId: THREAD_ID, turnCount: 1, createdAt: nowIso(), @@ -875,7 +874,7 @@ it.live( yield* harness.engine.dispatch({ type: "thread.checkpoint.revert", - commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-no-session"), + commandId: CommandId.make("cmd-checkpoint-revert-no-session"), threadId: THREAD_ID, turnCount: 0, createdAt: nowIso(), @@ -1119,7 +1118,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () => yield* harness.engine.dispatch({ type: "thread.approval.respond", - commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"), + commandId: CommandId.make("cmd-claude-approval-respond"), threadId: THREAD_ID, requestId: APPROVAL_REQUEST_ID, decision: "accept", @@ -1192,7 +1191,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () => yield* harness.engine.dispatch({ type: "thread.turn.interrupt", - commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"), + commandId: CommandId.make("cmd-turn-interrupt-claude"), threadId: THREAD_ID, createdAt: nowIso(), }); @@ -1309,7 +1308,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state", yield* harness.engine.dispatch({ type: "thread.checkpoint.revert", - commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"), + commandId: CommandId.make("cmd-checkpoint-revert-claude"), threadId: THREAD_ID, turnCount: 1, createdAt: nowIso(), diff --git a/apps/server/integration/providerService.integration.test.ts b/apps/server/integration/providerService.integration.test.ts index ef03a1ab5c..89cf6ac153 100644 --- a/apps/server/integration/providerService.integration.test.ts +++ b/apps/server/integration/providerService.integration.test.ts @@ -86,6 +86,7 @@ const collectEventsDuring = ( Effect.forkScoped, ); + yield* Effect.sleep("50 millis"); yield* action; return yield* Effect.forEach( @@ -104,7 +105,6 @@ const runTurn = (input: { }) => Effect.gen(function* () { yield* input.harness.queueTurnResponse(input.threadId, input.response); - return yield* collectEventsDuring( input.provider.streamEvents, input.response.events.length, @@ -116,21 +116,18 @@ const runTurn = (input: { ); }); -it.effect("replays typed runtime fixture events", () => +it.live("replays typed runtime fixture events", () => Effect.gen(function* () { const fixture = yield* makeIntegrationFixture; yield* Effect.gen(function* () { const provider = yield* ProviderService; - const session = yield* provider.startSession( - ThreadId.makeUnsafe("thread-integration-typed"), - { - threadId: ThreadId.makeUnsafe("thread-integration-typed"), - provider: "codex", - cwd: fixture.cwd, - runtimeMode: "full-access", - }, - ); + const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), { + threadId: ThreadId.make("thread-integration-typed"), + provider: "codex", + cwd: fixture.cwd, + runtimeMode: "full-access", + }); assert.equal((session.threadId ?? "").length > 0, true); const observedEvents = yield* runTurn({ @@ -149,7 +146,7 @@ it.effect("replays typed runtime fixture events", () => }).pipe(Effect.provide(NodeServices.layer)), ); -it.effect("replays file-changing fixture turn events", () => +it.live("replays file-changing fixture turn events", () => Effect.gen(function* () { const fixture = yield* makeIntegrationFixture; const { join } = yield* Path.Path; @@ -157,15 +154,12 @@ it.effect("replays file-changing fixture turn events", () => yield* Effect.gen(function* () { const provider = yield* ProviderService; - const session = yield* provider.startSession( - ThreadId.makeUnsafe("thread-integration-tools"), - { - threadId: ThreadId.makeUnsafe("thread-integration-tools"), - provider: "codex", - cwd: fixture.cwd, - runtimeMode: "full-access", - }, - ); + const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), { + threadId: ThreadId.make("thread-integration-tools"), + provider: "codex", + cwd: fixture.cwd, + runtimeMode: "full-access", + }); assert.equal((session.threadId ?? "").length > 0, true); const observedEvents = yield* runTurn({ @@ -188,7 +182,7 @@ it.effect("replays file-changing fixture turn events", () => }).pipe(Effect.provide(NodeServices.layer)), ); -it.effect("runs multi-turn tool/approval flow", () => +it.live("runs multi-turn tool/approval flow", () => Effect.gen(function* () { const fixture = yield* makeIntegrationFixture; const { join } = yield* Path.Path; @@ -196,15 +190,12 @@ it.effect("runs multi-turn tool/approval flow", () => yield* Effect.gen(function* () { const provider = yield* ProviderService; - const session = yield* provider.startSession( - ThreadId.makeUnsafe("thread-integration-multi"), - { - threadId: ThreadId.makeUnsafe("thread-integration-multi"), - provider: "codex", - cwd: fixture.cwd, - runtimeMode: "full-access", - }, - ); + const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), { + threadId: ThreadId.make("thread-integration-multi"), + provider: "codex", + cwd: fixture.cwd, + runtimeMode: "full-access", + }); assert.equal((session.threadId ?? "").length > 0, true); const firstTurnEvents = yield* runTurn({ @@ -242,7 +233,7 @@ it.effect("runs multi-turn tool/approval flow", () => }).pipe(Effect.provide(NodeServices.layer)), ); -it.effect("rolls back provider conversation state only", () => +it.live("rolls back provider conversation state only", () => Effect.gen(function* () { const fixture = yield* makeIntegrationFixture; const { join } = yield* Path.Path; @@ -250,15 +241,12 @@ it.effect("rolls back provider conversation state only", () => yield* Effect.gen(function* () { const provider = yield* ProviderService; - const session = yield* provider.startSession( - ThreadId.makeUnsafe("thread-integration-rollback"), - { - threadId: ThreadId.makeUnsafe("thread-integration-rollback"), - provider: "codex", - cwd: fixture.cwd, - runtimeMode: "full-access", - }, - ); + const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), { + threadId: ThreadId.make("thread-integration-rollback"), + provider: "codex", + cwd: fixture.cwd, + runtimeMode: "full-access", + }); assert.equal((session.threadId ?? "").length > 0, true); yield* runTurn({ diff --git a/apps/server/package.json b/apps/server/package.json index b85e1c1d46..950079a4dc 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -1,6 +1,6 @@ { "name": "t3", - "version": "0.0.15", + "version": "0.0.17", "license": "MIT", "repository": { "type": "git", @@ -8,28 +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", - "ws": "^8.18.0" + "open": "^10.1.0" }, "devDependencies": { "@effect/language-service": "catalog:", @@ -39,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/scripts/cli.ts b/apps/server/scripts/cli.ts index 21bc515aa7..299da67fab 100644 --- a/apps/server/scripts/cli.ts +++ b/apps/server/scripts/cli.ts @@ -14,6 +14,22 @@ import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog import rootPackageJson from "../../../package.json" with { type: "json" }; import serverPackageJson from "../package.json" with { type: "json" }; +interface PackageJson { + name: string; + repository: { + type: string; + url: string; + directory: string; + }; + bin: Record; + type: string; + version: string; + engines: Record; + files: string[]; + dependencies: Record; + overrides: Record; +} + class CliError extends Data.TaggedError("CliError")<{ readonly message: string; readonly cause?: unknown; @@ -177,7 +193,7 @@ const publishCmd = Command.make( const backupPath = `${packageJsonPath}.bak`; // Assert build assets exist - for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) { + for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) { const abs = path.join(serverDir, relPath); if (!(yield* fs.exists(abs))) { return yield* new CliError({ @@ -192,7 +208,7 @@ const publishCmd = Command.make( // Resolve catalog dependencies before any file mutations. If this throws, // acquire fails and no release hook runs, so filesystem must still be untouched. const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version); - const pkg = { + const pkg: PackageJson = { name: serverPackageJson.name, repository: serverPackageJson.repository, bin: serverPackageJson.bin, @@ -200,7 +216,8 @@ const publishCmd = Command.make( version, engines: serverPackageJson.engines, files: serverPackageJson.files, - dependencies: serverPackageJson.dependencies as Record, + dependencies: serverPackageJson.dependencies, + overrides: rootPackageJson.overrides, }; pkg.dependencies = resolveCatalogDependencies( @@ -208,6 +225,11 @@ const publishCmd = Command.make( rootPackageJson.workspaces.catalog, "apps/server dependencies", ); + pkg.overrides = resolveCatalogDependencies( + pkg.overrides, + rootPackageJson.workspaces.catalog, + "root overrides", + ); const original = yield* fs.readFileString(packageJsonPath); yield* fs.writeFileString(backupPath, original); diff --git a/apps/server/src/auth/Layers/AuthControlPlane.test.ts b/apps/server/src/auth/Layers/AuthControlPlane.test.ts new file mode 100644 index 0000000000..9fc091124b --- /dev/null +++ b/apps/server/src/auth/Layers/AuthControlPlane.test.ts @@ -0,0 +1,111 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { Effect, Layer } from "effect"; + +import { ServerConfigShape } from "../../config.ts"; +import { ServerConfig } from "../../config.ts"; +import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts"; +import { ServerSecretStoreLive } from "./ServerSecretStore.ts"; +import { SessionCredentialServiceLive } from "./SessionCredentialService.ts"; +import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; +import { AuthControlPlane } from "../Services/AuthControlPlane.ts"; +import { makeAuthControlPlane } from "./AuthControlPlane.ts"; +import { SessionCredentialService } from "../Services/SessionCredentialService.ts"; + +const makeServerConfigLayer = ( + overrides?: Partial>, +) => + Layer.effect( + ServerConfig, + Effect.gen(function* () { + const config = yield* ServerConfig; + return { + ...config, + ...overrides, + } satisfies ServerConfigShape; + }), + ).pipe( + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-control-plane-test-" })), + ); + +const makeAuthControlPlaneLayer = ( + overrides?: Partial>, +) => + Layer.effect(AuthControlPlane, makeAuthControlPlane).pipe( + Layer.provideMerge(BootstrapCredentialServiceLive), + Layer.provideMerge(SessionCredentialServiceLive), + Layer.provideMerge(ServerSecretStoreLive), + Layer.provideMerge(SqlitePersistenceMemory), + Layer.provide(makeServerConfigLayer(overrides)), + ); + +it.layer(NodeServices.layer)("AuthControlPlane", (it) => { + it.effect("creates, lists, and revokes client pairing links", () => + Effect.gen(function* () { + const authControlPlane = yield* AuthControlPlane; + + const created = yield* authControlPlane.createPairingLink({ + role: "client", + subject: "one-time-token", + label: "CI phone", + }); + const listedBeforeRevoke = yield* authControlPlane.listPairingLinks({ role: "client" }); + const revoked = yield* authControlPlane.revokePairingLink(created.id); + const listedAfterRevoke = yield* authControlPlane.listPairingLinks({ role: "client" }); + + expect(created.role).toBe("client"); + expect(created.credential.length).toBeGreaterThan(0); + expect(listedBeforeRevoke).toHaveLength(1); + expect(listedBeforeRevoke[0]?.id).toBe(created.id); + expect(listedBeforeRevoke[0]?.label).toBe("CI phone"); + expect(listedBeforeRevoke[0]?.credential).toBe(created.credential); + expect(revoked).toBe(true); + expect(listedAfterRevoke).toHaveLength(0); + }).pipe(Effect.provide(makeAuthControlPlaneLayer())), + ); + + it.effect("issues bearer sessions and lists them without exposing raw tokens", () => + Effect.gen(function* () { + const authControlPlane = yield* AuthControlPlane; + const sessionCredentials = yield* SessionCredentialService; + + const issued = yield* authControlPlane.issueSession({ + label: "deploy-bot", + }); + const verified = yield* sessionCredentials.verify(issued.token); + const listedBeforeRevoke = yield* authControlPlane.listSessions(); + const revoked = yield* authControlPlane.revokeSession(issued.sessionId); + const listedAfterRevoke = yield* authControlPlane.listSessions(); + + expect(issued.method).toBe("bearer-session-token"); + expect(issued.role).toBe("owner"); + expect(issued.client.deviceType).toBe("bot"); + expect(issued.client.label).toBe("deploy-bot"); + expect(verified.sessionId).toBe(issued.sessionId); + expect(verified.role).toBe("owner"); + expect(verified.method).toBe("bearer-session-token"); + expect(listedBeforeRevoke).toHaveLength(1); + expect(listedBeforeRevoke[0]?.sessionId).toBe(issued.sessionId); + expect("token" in (listedBeforeRevoke[0] ?? {})).toBe(false); + expect(revoked).toBe(true); + expect(listedAfterRevoke).toHaveLength(0); + }).pipe(Effect.provide(makeAuthControlPlaneLayer())), + ); + + it.effect("surfaces lastConnectedAt through the listed session view", () => + Effect.gen(function* () { + const authControlPlane = yield* AuthControlPlane; + const sessionCredentials = yield* SessionCredentialService; + + const issued = yield* authControlPlane.issueSession({ + label: "remote-ipad", + }); + const beforeConnect = yield* authControlPlane.listSessions(); + yield* sessionCredentials.markConnected(issued.sessionId); + const afterConnect = yield* authControlPlane.listSessions(); + + expect(beforeConnect[0]?.lastConnectedAt).toBeNull(); + expect(afterConnect[0]?.lastConnectedAt).not.toBeNull(); + }).pipe(Effect.provide(makeAuthControlPlaneLayer())), + ); +}); diff --git a/apps/server/src/auth/Layers/AuthControlPlane.ts b/apps/server/src/auth/Layers/AuthControlPlane.ts new file mode 100644 index 0000000000..98b2107800 --- /dev/null +++ b/apps/server/src/auth/Layers/AuthControlPlane.ts @@ -0,0 +1,176 @@ +import type { AuthClientSession, AuthPairingLink } from "@t3tools/contracts"; +import { DateTime, Effect, Layer } from "effect"; + +import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts"; +import { ServerSecretStoreLive } from "./ServerSecretStore.ts"; +import { SessionCredentialServiceLive } from "./SessionCredentialService.ts"; +import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts"; +import { SessionCredentialService } from "../Services/SessionCredentialService.ts"; +import { layerConfig as SqlitePersistenceLayerLive } from "../../persistence/Layers/Sqlite.ts"; +import { + AuthControlPlane, + AuthControlPlaneError, + AuthControlPlaneShape, + DEFAULT_SESSION_SUBJECT, + IssuedBearerSession, + IssuedPairingLink, +} from "../Services/AuthControlPlane.ts"; + +const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => { + if (left.role !== right.role) { + return left.role === "owner" ? -1 : 1; + } + if (left.connected !== right.connected) { + return left.connected ? -1 : 1; + } + return right.issuedAt.epochMilliseconds - left.issuedAt.epochMilliseconds; +}; + +const toAuthControlPlaneError = + (message: string) => + (cause: unknown): AuthControlPlaneError => + new AuthControlPlaneError({ + message, + cause, + }); + +export const makeAuthControlPlane = Effect.gen(function* () { + const bootstrapCredentials = yield* BootstrapCredentialService; + const sessions = yield* SessionCredentialService; + + const createPairingLink: AuthControlPlaneShape["createPairingLink"] = (input) => + Effect.gen(function* () { + const createdAt = yield* DateTime.now; + const issued = yield* bootstrapCredentials.issueOneTimeToken({ + role: input?.role ?? "client", + subject: input?.subject ?? "one-time-token", + ...(input?.ttl ? { ttl: input.ttl } : {}), + ...(input?.label ? { label: input.label } : {}), + }); + return { + id: issued.id, + credential: issued.credential, + role: input?.role ?? "client", + subject: input?.subject ?? "one-time-token", + ...(issued.label ? { label: issued.label } : {}), + createdAt: DateTime.toUtc(createdAt), + expiresAt: DateTime.toUtc(issued.expiresAt), + } satisfies IssuedPairingLink; + }).pipe(Effect.mapError(toAuthControlPlaneError("Failed to create pairing link."))); + + const listPairingLinks: AuthControlPlaneShape["listPairingLinks"] = (input) => + bootstrapCredentials.listActive().pipe( + Effect.map((pairingLinks) => + pairingLinks + .filter((pairingLink) => (input?.role ? pairingLink.role === input.role : true)) + .filter((pairingLink) => !input?.excludeSubjects?.includes(pairingLink.subject)) + .map((pairingLink) => + pairingLink.label + ? ({ + id: pairingLink.id, + credential: pairingLink.credential, + role: pairingLink.role, + subject: pairingLink.subject, + label: pairingLink.label, + createdAt: pairingLink.createdAt, + expiresAt: pairingLink.expiresAt, + } satisfies AuthPairingLink) + : ({ + id: pairingLink.id, + credential: pairingLink.credential, + role: pairingLink.role, + subject: pairingLink.subject, + createdAt: pairingLink.createdAt, + expiresAt: pairingLink.expiresAt, + } satisfies AuthPairingLink), + ) + .toSorted( + (left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds, + ), + ), + Effect.mapError(toAuthControlPlaneError("Failed to list pairing links.")), + ); + + const revokePairingLink: AuthControlPlaneShape["revokePairingLink"] = (id) => + bootstrapCredentials + .revoke(id) + .pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke pairing link."))); + + const issueSession: AuthControlPlaneShape["issueSession"] = (input) => + sessions + .issue({ + subject: input?.subject ?? DEFAULT_SESSION_SUBJECT, + method: "bearer-session-token", + role: input?.role ?? "owner", + client: { + ...(input?.label ? { label: input.label } : {}), + deviceType: "bot", + }, + ...(input?.ttl ? { ttl: input.ttl } : {}), + }) + .pipe( + Effect.flatMap((issued) => { + if (issued.method !== "bearer-session-token") { + return Effect.fail( + new AuthControlPlaneError({ + message: "CLI session issuance produced an unexpected session method.", + }), + ); + } + + return Effect.succeed({ + sessionId: issued.sessionId, + token: issued.token, + method: "bearer-session-token" as const, + role: issued.role, + subject: input?.subject ?? DEFAULT_SESSION_SUBJECT, + client: issued.client, + expiresAt: DateTime.toUtc(issued.expiresAt), + } satisfies IssuedBearerSession); + }), + Effect.mapError(toAuthControlPlaneError("Failed to issue session token.")), + ); + + const listSessions: AuthControlPlaneShape["listSessions"] = () => + sessions.listActive().pipe( + Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)), + Effect.mapError(toAuthControlPlaneError("Failed to list sessions.")), + ); + + const revokeSession: AuthControlPlaneShape["revokeSession"] = (sessionId) => + sessions + .revoke(sessionId) + .pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke session."))); + + const revokeOtherSessionsExcept: AuthControlPlaneShape["revokeOtherSessionsExcept"] = ( + sessionId, + ) => + sessions + .revokeAllExcept(sessionId) + .pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke other sessions."))); + + return { + createPairingLink, + listPairingLinks, + revokePairingLink, + issueSession, + listSessions, + revokeSession, + revokeOtherSessionsExcept, + } satisfies AuthControlPlaneShape; +}); + +export const AuthCoreLive = Layer.mergeAll( + BootstrapCredentialServiceLive, + SessionCredentialServiceLive, +); + +export const AuthStorageLive = Layer.mergeAll(ServerSecretStoreLive, SqlitePersistenceLayerLive); + +export const AuthRuntimeLive = AuthCoreLive.pipe(Layer.provideMerge(AuthStorageLive)); + +export const AuthControlPlaneLive = Layer.effect(AuthControlPlane, makeAuthControlPlane); + +export const AuthControlPlaneRuntimeLive = AuthControlPlaneLive.pipe( + Layer.provideMerge(AuthRuntimeLive), +); diff --git a/apps/server/src/auth/Layers/BootstrapCredentialService.test.ts b/apps/server/src/auth/Layers/BootstrapCredentialService.test.ts new file mode 100644 index 0000000000..ec110ee96f --- /dev/null +++ b/apps/server/src/auth/Layers/BootstrapCredentialService.test.ts @@ -0,0 +1,151 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { Duration, Effect, Layer } from "effect"; +import { TestClock } from "effect/testing"; + +import type { ServerConfigShape } from "../../config.ts"; +import { ServerConfig } from "../../config.ts"; +import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; +import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts"; +import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts"; + +const makeServerConfigLayer = ( + overrides?: Partial>, +) => + Layer.effect( + ServerConfig, + Effect.gen(function* () { + const config = yield* ServerConfig; + return { + ...config, + ...overrides, + } satisfies ServerConfigShape; + }), + ).pipe( + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-bootstrap-test-" })), + ); + +const makeBootstrapCredentialLayer = ( + overrides?: Partial>, +) => + BootstrapCredentialServiceLive.pipe( + Layer.provide(SqlitePersistenceMemory), + Layer.provide(makeServerConfigLayer(overrides)), + ); + +it.layer(NodeServices.layer)("BootstrapCredentialServiceLive", (it) => { + it.effect("issues pairing tokens in a short manual-entry format", () => + Effect.gen(function* () { + const bootstrapCredentials = yield* BootstrapCredentialService; + const issued = yield* bootstrapCredentials.issueOneTimeToken(); + + expect(issued.credential).toMatch(/^[23456789ABCDEFGHJKLMNPQRSTUVWXYZ]{12}$/); + }).pipe(Effect.provide(makeBootstrapCredentialLayer())), + ); + + it.effect("issues one-time bootstrap tokens that can only be consumed once", () => + Effect.gen(function* () { + const bootstrapCredentials = yield* BootstrapCredentialService; + const issued = yield* bootstrapCredentials.issueOneTimeToken({ label: "Julius iPhone" }); + const first = yield* bootstrapCredentials.consume(issued.credential); + const second = yield* Effect.flip(bootstrapCredentials.consume(issued.credential)); + + expect(first.method).toBe("one-time-token"); + expect(first.role).toBe("client"); + expect(first.subject).toBe("one-time-token"); + expect(first.label).toBe("Julius iPhone"); + expect(issued.label).toBe("Julius iPhone"); + expect(second._tag).toBe("BootstrapCredentialError"); + expect(second.message).toContain("Unknown bootstrap credential"); + }).pipe(Effect.provide(makeBootstrapCredentialLayer())), + ); + + it.effect("atomically consumes a one-time token when multiple requests race", () => + Effect.gen(function* () { + const bootstrapCredentials = yield* BootstrapCredentialService; + const token = yield* bootstrapCredentials.issueOneTimeToken(); + const results = yield* Effect.all( + Array.from({ length: 8 }, () => + Effect.result(bootstrapCredentials.consume(token.credential)), + ), + { + concurrency: "unbounded", + }, + ); + + const successes = results.filter((result) => result._tag === "Success"); + const failures = results.filter((result) => result._tag === "Failure"); + + expect(successes).toHaveLength(1); + expect(failures).toHaveLength(7); + for (const failure of failures) { + expect(failure.failure._tag).toBe("BootstrapCredentialError"); + expect(failure.failure.message).toContain("Unknown bootstrap credential"); + } + }).pipe(Effect.provide(makeBootstrapCredentialLayer())), + ); + + it.effect("seeds the desktop bootstrap credential as a one-time grant", () => + Effect.gen(function* () { + const bootstrapCredentials = yield* BootstrapCredentialService; + const first = yield* bootstrapCredentials.consume("desktop-bootstrap-token"); + const second = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token")); + + expect(first.method).toBe("desktop-bootstrap"); + expect(first.role).toBe("owner"); + expect(first.subject).toBe("desktop-bootstrap"); + expect(second._tag).toBe("BootstrapCredentialError"); + expect(second.status).toBe(401); + }).pipe( + Effect.provide( + makeBootstrapCredentialLayer({ + desktopBootstrapToken: "desktop-bootstrap-token", + }), + ), + ), + ); + + it.effect("reports seeded desktop bootstrap credentials as expired after their ttl", () => + Effect.gen(function* () { + const bootstrapCredentials = yield* BootstrapCredentialService; + + yield* TestClock.adjust(Duration.minutes(6)); + const expired = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token")); + + expect(expired._tag).toBe("BootstrapCredentialError"); + expect(expired.status).toBe(401); + expect(expired.message).toContain("Bootstrap credential expired"); + }).pipe( + Effect.provide( + Layer.merge( + makeBootstrapCredentialLayer({ + desktopBootstrapToken: "desktop-bootstrap-token", + }), + TestClock.layer(), + ), + ), + ), + ); + + it.effect("lists and revokes active pairing links", () => + Effect.gen(function* () { + const bootstrapCredentials = yield* BootstrapCredentialService; + const first = yield* bootstrapCredentials.issueOneTimeToken(); + const second = yield* bootstrapCredentials.issueOneTimeToken({ role: "owner" }); + + const activeBeforeRevoke = yield* bootstrapCredentials.listActive(); + expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(first.id); + expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(second.id); + + const revoked = yield* bootstrapCredentials.revoke(first.id); + const activeAfterRevoke = yield* bootstrapCredentials.listActive(); + const revokedConsume = yield* Effect.flip(bootstrapCredentials.consume(first.credential)); + + expect(revoked).toBe(true); + expect(activeAfterRevoke.map((entry) => entry.id)).not.toContain(first.id); + expect(activeAfterRevoke.map((entry) => entry.id)).toContain(second.id); + expect(revokedConsume.message).toContain("no longer available"); + expect(revokedConsume.status).toBe(401); + }).pipe(Effect.provide(makeBootstrapCredentialLayer())), + ); +}); diff --git a/apps/server/src/auth/Layers/BootstrapCredentialService.ts b/apps/server/src/auth/Layers/BootstrapCredentialService.ts new file mode 100644 index 0000000000..5539f62c70 --- /dev/null +++ b/apps/server/src/auth/Layers/BootstrapCredentialService.ts @@ -0,0 +1,296 @@ +import type { AuthPairingLink } from "@t3tools/contracts"; +import { DateTime, Duration, Effect, Layer, PubSub, Ref, Stream } from "effect"; +import { Option } from "effect"; + +import { ServerConfig } from "../../config.ts"; +import { AuthPairingLinkRepositoryLive } from "../../persistence/Layers/AuthPairingLinks.ts"; +import { AuthPairingLinkRepository } from "../../persistence/Services/AuthPairingLinks.ts"; +import { + BootstrapCredentialError, + BootstrapCredentialService, + type BootstrapCredentialChange, + type BootstrapCredentialServiceShape, + type BootstrapGrant, + type IssuedBootstrapCredential, +} from "../Services/BootstrapCredentialService.ts"; + +interface StoredBootstrapGrant extends BootstrapGrant { + readonly remainingUses: number | "unbounded"; +} + +type ConsumeResult = + | { + readonly _tag: "error"; + readonly reason: "not-found" | "expired"; + readonly error: BootstrapCredentialError; + } + | { + readonly _tag: "success"; + readonly grant: BootstrapGrant; + }; + +const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5); +const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; +const PAIRING_TOKEN_LENGTH = 12; + +const generatePairingToken = (): string => { + const randomBytes = crypto.getRandomValues(new Uint8Array(PAIRING_TOKEN_LENGTH)); + + return Array.from(randomBytes, (value) => PAIRING_TOKEN_ALPHABET[value & 31]).join(""); +}; + +export const makeBootstrapCredentialService = Effect.gen(function* () { + const config = yield* ServerConfig; + const pairingLinks = yield* AuthPairingLinkRepository; + const seededGrantsRef = yield* Ref.make(new Map()); + const changesPubSub = yield* PubSub.unbounded(); + + const invalidBootstrapCredentialError = (message: string) => + new BootstrapCredentialError({ + message, + status: 401, + }); + + const internalBootstrapCredentialError = (message: string, cause: unknown) => + new BootstrapCredentialError({ + message, + status: 500, + cause, + }); + + const seedGrant = (credential: string, grant: StoredBootstrapGrant) => + Ref.update(seededGrantsRef, (current) => { + const next = new Map(current); + next.set(credential, grant); + return next; + }); + + const emitUpsert = (pairingLink: AuthPairingLink) => + PubSub.publish(changesPubSub, { + type: "pairingLinkUpserted", + pairingLink, + }).pipe(Effect.asVoid); + + const emitRemoved = (id: string) => + PubSub.publish(changesPubSub, { + type: "pairingLinkRemoved", + id, + }).pipe(Effect.asVoid); + + if (config.desktopBootstrapToken) { + const now = yield* DateTime.now; + yield* seedGrant(config.desktopBootstrapToken, { + method: "desktop-bootstrap", + role: "owner", + subject: "desktop-bootstrap", + expiresAt: DateTime.add(now, { + milliseconds: Duration.toMillis(DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES), + }), + remainingUses: 1, + }); + } + + const toBootstrapCredentialError = (message: string) => (cause: unknown) => + internalBootstrapCredentialError(message, cause); + + const listActive: BootstrapCredentialServiceShape["listActive"] = () => + Effect.gen(function* () { + const now = yield* DateTime.now; + const rows = yield* pairingLinks.listActive({ now }); + + return rows.map((row) => + row.label + ? ({ + id: row.id, + credential: row.credential, + role: row.role, + subject: row.subject, + label: row.label, + createdAt: row.createdAt, + expiresAt: row.expiresAt, + } satisfies AuthPairingLink) + : ({ + id: row.id, + credential: row.credential, + role: row.role, + subject: row.subject, + createdAt: row.createdAt, + expiresAt: row.expiresAt, + } satisfies AuthPairingLink), + ); + }).pipe(Effect.mapError(toBootstrapCredentialError("Failed to load active pairing links."))); + + const revoke: BootstrapCredentialServiceShape["revoke"] = (id) => + Effect.gen(function* () { + const revokedAt = yield* DateTime.now; + const revoked = yield* pairingLinks.revoke({ + id, + revokedAt, + }); + if (revoked) { + yield* emitRemoved(id); + } + return revoked; + }).pipe(Effect.mapError(toBootstrapCredentialError("Failed to revoke pairing link."))); + + const issueOneTimeToken: BootstrapCredentialServiceShape["issueOneTimeToken"] = (input) => + Effect.gen(function* () { + const id = crypto.randomUUID(); + const credential = generatePairingToken(); + const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES; + const now = yield* DateTime.now; + const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) }); + const issued: IssuedBootstrapCredential = { + id, + credential, + ...(input?.label ? { label: input.label } : {}), + expiresAt, + }; + yield* pairingLinks.create({ + id, + credential, + method: "one-time-token", + role: input?.role ?? "client", + subject: input?.subject ?? "one-time-token", + label: input?.label ?? null, + createdAt: now, + expiresAt: expiresAt, + }); + yield* emitUpsert({ + id, + credential, + role: input?.role ?? "client", + subject: input?.subject ?? "one-time-token", + ...(input?.label ? { label: input.label } : {}), + createdAt: now, + expiresAt, + }); + return issued; + }).pipe(Effect.mapError(toBootstrapCredentialError("Failed to issue pairing credential."))); + + const consume: BootstrapCredentialServiceShape["consume"] = (credential) => + Effect.gen(function* () { + const now = yield* DateTime.now; + const seededResult: ConsumeResult = yield* Ref.modify( + seededGrantsRef, + (current): readonly [ConsumeResult, Map] => { + const grant = current.get(credential); + if (!grant) { + return [ + { + _tag: "error", + reason: "not-found", + error: invalidBootstrapCredentialError("Unknown bootstrap credential."), + }, + current, + ]; + } + + const next = new Map(current); + if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) { + next.delete(credential); + return [ + { + _tag: "error", + reason: "expired", + error: invalidBootstrapCredentialError("Bootstrap credential expired."), + }, + next, + ]; + } + + const remainingUses = grant.remainingUses; + if (typeof remainingUses === "number") { + if (remainingUses <= 1) { + next.delete(credential); + } else { + next.set(credential, { + ...grant, + remainingUses: remainingUses - 1, + }); + } + } + + return [ + { + _tag: "success", + grant: { + method: grant.method, + role: grant.role, + subject: grant.subject, + ...(grant.label ? { label: grant.label } : {}), + expiresAt: grant.expiresAt, + } satisfies BootstrapGrant, + }, + next, + ]; + }, + ); + + if (seededResult._tag === "success") { + return seededResult.grant; + } + if (seededResult.reason !== "not-found") { + return yield* seededResult.error; + } + + const consumed = yield* pairingLinks.consumeAvailable({ + credential, + consumedAt: now, + now, + }); + + if (Option.isSome(consumed)) { + yield* emitRemoved(consumed.value.id); + return { + method: consumed.value.method, + role: consumed.value.role, + subject: consumed.value.subject, + ...(consumed.value.label ? { label: consumed.value.label } : {}), + expiresAt: consumed.value.expiresAt, + } satisfies BootstrapGrant; + } + + const matching = yield* pairingLinks.getByCredential({ credential }); + if (Option.isNone(matching)) { + return yield* invalidBootstrapCredentialError("Unknown bootstrap credential."); + } + + if (matching.value.revokedAt !== null) { + return yield* invalidBootstrapCredentialError( + "Bootstrap credential is no longer available.", + ); + } + + if (matching.value.consumedAt !== null) { + return yield* invalidBootstrapCredentialError("Unknown bootstrap credential."); + } + + if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) { + return yield* invalidBootstrapCredentialError("Bootstrap credential expired."); + } + + return yield* invalidBootstrapCredentialError("Bootstrap credential is no longer available."); + }).pipe( + Effect.mapError((cause) => + cause instanceof BootstrapCredentialError + ? cause + : internalBootstrapCredentialError("Failed to consume bootstrap credential.", cause), + ), + ); + + return { + issueOneTimeToken, + listActive, + get streamChanges() { + return Stream.fromPubSub(changesPubSub); + }, + revoke, + consume, + } satisfies BootstrapCredentialServiceShape; +}); + +export const BootstrapCredentialServiceLive = Layer.effect( + BootstrapCredentialService, + makeBootstrapCredentialService, +).pipe(Layer.provideMerge(AuthPairingLinkRepositoryLive)); diff --git a/apps/server/src/auth/Layers/ServerAuth.test.ts b/apps/server/src/auth/Layers/ServerAuth.test.ts new file mode 100644 index 0000000000..0c3d71cc9f --- /dev/null +++ b/apps/server/src/auth/Layers/ServerAuth.test.ts @@ -0,0 +1,182 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { Effect, Layer } from "effect"; + +import type { ServerConfigShape } from "../../config.ts"; +import { ServerConfig } from "../../config.ts"; +import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; +import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts"; +import { ServerAuth, type ServerAuthShape } from "../Services/ServerAuth.ts"; +import { ServerAuthLive, toBootstrapExchangeAuthError } from "./ServerAuth.ts"; +import { ServerSecretStoreLive } from "./ServerSecretStore.ts"; + +const makeServerConfigLayer = (overrides?: Partial) => + Layer.effect( + ServerConfig, + Effect.gen(function* () { + const config = yield* ServerConfig; + return { + ...config, + ...overrides, + } satisfies ServerConfigShape; + }), + ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-server-test-" }))); + +const makeServerAuthLayer = (overrides?: Partial) => + ServerAuthLive.pipe( + Layer.provide(SqlitePersistenceMemory), + Layer.provide(ServerSecretStoreLive), + Layer.provide(makeServerConfigLayer(overrides)), + ); + +const makeCookieRequest = ( + sessionToken: string, +): Parameters[0] => + ({ + cookies: { + t3_session: sessionToken, + }, + headers: {}, + }) as unknown as Parameters[0]; + +const requestMetadata = { + deviceType: "desktop" as const, + os: "macOS", + browser: "Chrome", + ipAddress: "192.168.1.23", +}; + +it.layer(NodeServices.layer)("ServerAuthLive", (it) => { + it.effect("maps invalid bootstrap credential failures to 401", () => + Effect.sync(() => { + const error = toBootstrapExchangeAuthError( + new BootstrapCredentialError({ + message: "Unknown bootstrap credential.", + status: 401, + }), + ); + + expect(error.status).toBe(401); + expect(error.message).toBe("Invalid bootstrap credential."); + }), + ); + + it.effect("maps unexpected bootstrap failures to 500", () => + Effect.sync(() => { + const error = toBootstrapExchangeAuthError( + new BootstrapCredentialError({ + message: "Failed to consume bootstrap credential.", + status: 500, + cause: new Error("sqlite is unavailable"), + }), + ); + + expect(error.status).toBe(500); + expect(error.message).toBe("Failed to validate bootstrap credential."); + }), + ); + + it.effect("issues client pairing credentials by default", () => + Effect.gen(function* () { + const serverAuth = yield* ServerAuth; + + const pairingCredential = yield* serverAuth.issuePairingCredential(); + const exchanged = yield* serverAuth.exchangeBootstrapCredential( + pairingCredential.credential, + requestMetadata, + ); + const verified = yield* serverAuth.authenticateHttpRequest( + makeCookieRequest(exchanged.sessionToken), + ); + + expect(verified.sessionId.length).toBeGreaterThan(0); + expect(verified.role).toBe("client"); + expect(verified.subject).toBe("one-time-token"); + }).pipe(Effect.provide(makeServerAuthLayer())), + ); + + it.effect("issues startup pairing URLs that bootstrap owner sessions", () => + Effect.gen(function* () { + const serverAuth = yield* ServerAuth; + + const pairingUrl = yield* serverAuth.issueStartupPairingUrl("http://127.0.0.1:3773"); + const token = new URLSearchParams(new URL(pairingUrl).hash.slice(1)).get("token"); + const listedPairingLinks = yield* serverAuth.listPairingLinks(); + expect(token).toBeTruthy(); + expect( + listedPairingLinks.some((pairingLink) => pairingLink.subject === "owner-bootstrap"), + ).toBe(false); + + const exchanged = yield* serverAuth.exchangeBootstrapCredential(token ?? "", requestMetadata); + const verified = yield* serverAuth.authenticateHttpRequest( + makeCookieRequest(exchanged.sessionToken), + ); + + expect(verified.role).toBe("owner"); + expect(verified.subject).toBe("owner-bootstrap"); + }).pipe(Effect.provide(makeServerAuthLayer())), + ); + + it.effect("lists pairing links and revokes other client sessions while keeping the owner", () => + Effect.gen(function* () { + const serverAuth = yield* ServerAuth; + + const ownerExchange = yield* serverAuth.exchangeBootstrapCredential( + "desktop-bootstrap-token", + requestMetadata, + ); + const ownerSession = yield* serverAuth.authenticateHttpRequest( + makeCookieRequest(ownerExchange.sessionToken), + ); + const pairingCredential = yield* serverAuth.issuePairingCredential({ + label: "Julius iPhone", + }); + const listedPairingLinks = yield* serverAuth.listPairingLinks(); + const clientExchange = yield* serverAuth.exchangeBootstrapCredential( + pairingCredential.credential, + { + ...requestMetadata, + deviceType: "mobile", + os: "iOS", + browser: "Safari", + ipAddress: "192.168.1.88", + }, + ); + const clientSession = yield* serverAuth.authenticateHttpRequest( + makeCookieRequest(clientExchange.sessionToken), + ); + const clientsBeforeRevoke = yield* serverAuth.listClientSessions(ownerSession.sessionId); + const revokedCount = yield* serverAuth.revokeOtherClientSessions(ownerSession.sessionId); + const clientsAfterRevoke = yield* serverAuth.listClientSessions(ownerSession.sessionId); + + expect(listedPairingLinks.map((entry) => entry.id)).toContain(pairingCredential.id); + expect(listedPairingLinks.find((entry) => entry.id === pairingCredential.id)?.label).toBe( + "Julius iPhone", + ); + expect(clientsBeforeRevoke).toHaveLength(2); + expect( + clientsBeforeRevoke.find((entry) => entry.sessionId === ownerSession.sessionId)?.current, + ).toBe(true); + expect( + clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.current, + ).toBe(false); + expect( + clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client + .label, + ).toBe("Julius iPhone"); + expect( + clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client + .deviceType, + ).toBe("mobile"); + expect(revokedCount).toBe(1); + expect(clientsAfterRevoke).toHaveLength(1); + expect(clientsAfterRevoke[0]?.sessionId).toBe(ownerSession.sessionId); + }).pipe( + Effect.provide( + makeServerAuthLayer({ + desktopBootstrapToken: "desktop-bootstrap-token", + }), + ), + ), + ); +}); diff --git a/apps/server/src/auth/Layers/ServerAuth.ts b/apps/server/src/auth/Layers/ServerAuth.ts new file mode 100644 index 0000000000..cb1c6fa4c4 --- /dev/null +++ b/apps/server/src/auth/Layers/ServerAuth.ts @@ -0,0 +1,395 @@ +import { + type AuthBearerBootstrapResult, + type AuthClientSession, + type AuthBootstrapResult, + type AuthPairingCredentialResult, + type AuthSessionState, + type AuthWebSocketTokenResult, +} from "@t3tools/contracts"; +import { DateTime, Effect, Layer, Option } from "effect"; +import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest"; + +import { AuthControlPlane } from "../Services/AuthControlPlane.ts"; +import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts"; +import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts"; +import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts"; +import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts"; +import { + ServerAuth, + type AuthenticatedSession, + AuthError, + type ServerAuthShape, +} from "../Services/ServerAuth.ts"; +import { + SessionCredentialError, + SessionCredentialService, +} from "../Services/SessionCredentialService.ts"; +import { AuthControlPlaneLive, AuthCoreLive } from "./AuthControlPlane.ts"; + +type BootstrapExchangeResult = { + readonly response: AuthBootstrapResult; + readonly sessionToken: string; +}; + +const AUTHORIZATION_PREFIX = "Bearer "; +const WEBSOCKET_TOKEN_QUERY_PARAM = "wsToken"; + +export function toBootstrapExchangeAuthError(cause: BootstrapCredentialError): AuthError { + if (cause.status === 500) { + return new AuthError({ + message: "Failed to validate bootstrap credential.", + status: 500, + cause, + }); + } + + return new AuthError({ + message: "Invalid bootstrap credential.", + status: 401, + cause, + }); +} + +function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null { + const header = request.headers["authorization"]; + if (typeof header !== "string" || !header.startsWith(AUTHORIZATION_PREFIX)) { + return null; + } + const token = header.slice(AUTHORIZATION_PREFIX.length).trim(); + return token.length > 0 ? token : null; +} + +export const makeServerAuth = Effect.gen(function* () { + const policy = yield* ServerAuthPolicy; + const bootstrapCredentials = yield* BootstrapCredentialService; + const authControlPlane = yield* AuthControlPlane; + const sessions = yield* SessionCredentialService; + const descriptor = yield* policy.getDescriptor(); + + const authenticateToken = (token: string): Effect.Effect => + sessions.verify(token).pipe( + Effect.tapError((cause: SessionCredentialError) => + Effect.logWarning("Rejected authenticated session credential.").pipe( + Effect.annotateLogs({ + reason: cause.message, + }), + ), + ), + Effect.map((session) => ({ + sessionId: session.sessionId, + subject: session.subject, + method: session.method, + role: session.role, + ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}), + })), + Effect.mapError( + (cause) => + new AuthError({ + message: "Unauthorized request.", + status: 401, + cause, + }), + ), + ); + + const authenticateRequest = (request: HttpServerRequest.HttpServerRequest) => { + const cookieToken = request.cookies[sessions.cookieName]; + const bearerToken = parseBearerToken(request); + const credential = cookieToken ?? bearerToken; + if (!credential) { + return Effect.fail( + new AuthError({ + message: "Authentication required.", + status: 401, + }), + ); + } + return authenticateToken(credential); + }; + + const getSessionState: ServerAuthShape["getSessionState"] = (request) => + authenticateRequest(request).pipe( + Effect.map( + (session) => + ({ + authenticated: true, + auth: descriptor, + role: session.role, + sessionMethod: session.method, + ...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}), + }) satisfies AuthSessionState, + ), + Effect.catchTag("AuthError", () => + Effect.succeed({ + authenticated: false, + auth: descriptor, + } satisfies AuthSessionState), + ), + ); + + const exchangeBootstrapCredential: ServerAuthShape["exchangeBootstrapCredential"] = ( + credential, + requestMetadata, + ) => + bootstrapCredentials.consume(credential).pipe( + Effect.mapError(toBootstrapExchangeAuthError), + Effect.flatMap((grant) => + sessions + .issue({ + method: "browser-session-cookie", + subject: grant.subject, + role: grant.role, + client: { + ...requestMetadata, + ...(grant.label ? { label: grant.label } : {}), + }, + }) + .pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Failed to issue authenticated session.", + cause, + }), + ), + ), + ), + Effect.map( + (session) => + ({ + response: { + authenticated: true, + role: session.role, + sessionMethod: session.method, + expiresAt: DateTime.toUtc(session.expiresAt), + } satisfies AuthBootstrapResult, + sessionToken: session.token, + }) satisfies BootstrapExchangeResult, + ), + ); + + const exchangeBootstrapCredentialForBearerSession: ServerAuthShape["exchangeBootstrapCredentialForBearerSession"] = + (credential, requestMetadata) => + bootstrapCredentials.consume(credential).pipe( + Effect.mapError(toBootstrapExchangeAuthError), + Effect.flatMap((grant) => + sessions + .issue({ + method: "bearer-session-token", + subject: grant.subject, + role: grant.role, + client: { + ...requestMetadata, + ...(grant.label ? { label: grant.label } : {}), + }, + }) + .pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Failed to issue authenticated session.", + cause, + }), + ), + ), + ), + Effect.map( + (session) => + ({ + authenticated: true, + role: session.role, + sessionMethod: "bearer-session-token", + expiresAt: DateTime.toUtc(session.expiresAt), + sessionToken: session.token, + }) satisfies AuthBearerBootstrapResult, + ), + ); + + const issuePairingCredential: ServerAuthShape["issuePairingCredential"] = (input) => + authControlPlane + .createPairingLink({ + role: input?.role ?? "client", + subject: input?.role === "owner" ? "owner-bootstrap" : "one-time-token", + ...(input?.label ? { label: input.label } : {}), + }) + .pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Failed to issue pairing credential.", + cause, + }), + ), + Effect.map( + (issued) => + ({ + id: issued.id, + credential: issued.credential, + ...(issued.label ? { label: issued.label } : {}), + expiresAt: issued.expiresAt, + }) satisfies AuthPairingCredentialResult, + ), + ); + + const listPairingLinks: ServerAuthShape["listPairingLinks"] = () => + authControlPlane + .listPairingLinks({ + role: "client", + excludeSubjects: ["owner-bootstrap"], + }) + .pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Failed to load pairing links.", + cause, + }), + ), + ); + + const revokePairingLink: ServerAuthShape["revokePairingLink"] = (id) => + authControlPlane.revokePairingLink(id).pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Failed to revoke pairing link.", + cause, + }), + ), + ); + + const listClientSessions: ServerAuthShape["listClientSessions"] = (currentSessionId) => + authControlPlane.listSessions().pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Failed to load paired clients.", + cause, + }), + ), + Effect.map((clientSessions) => + clientSessions.map( + (clientSession): AuthClientSession => ({ + ...clientSession, + current: clientSession.sessionId === currentSessionId, + }), + ), + ), + ); + + const revokeClientSession: ServerAuthShape["revokeClientSession"] = ( + currentSessionId, + targetSessionId, + ) => + Effect.gen(function* () { + if (currentSessionId === targetSessionId) { + return yield* new AuthError({ + message: "Use revoke other clients to keep the current owner session active.", + status: 403, + }); + } + return yield* authControlPlane.revokeSession(targetSessionId).pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Failed to revoke client session.", + cause, + }), + ), + ); + }); + + const revokeOtherClientSessions: ServerAuthShape["revokeOtherClientSessions"] = ( + currentSessionId, + ) => + authControlPlane.revokeOtherSessionsExcept(currentSessionId).pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Failed to revoke other client sessions.", + cause, + }), + ), + ); + + const issueStartupPairingUrl: ServerAuthShape["issueStartupPairingUrl"] = (baseUrl) => + issuePairingCredential({ role: "owner" }).pipe( + Effect.map((issued) => { + const url = new URL(baseUrl); + url.pathname = "/pair"; + url.searchParams.delete("token"); + url.hash = new URLSearchParams([["token", issued.credential]]).toString(); + return url.toString(); + }), + ); + + const issueWebSocketToken: ServerAuthShape["issueWebSocketToken"] = (session) => + sessions.issueWebSocketToken(session.sessionId).pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Failed to issue websocket token.", + cause, + }), + ), + Effect.map( + (issued) => + ({ + token: issued.token, + expiresAt: DateTime.toUtc(issued.expiresAt), + }) satisfies AuthWebSocketTokenResult, + ), + ); + + const authenticateWebSocketUpgrade: ServerAuthShape["authenticateWebSocketUpgrade"] = (request) => + Effect.gen(function* () { + const requestUrl = HttpServerRequest.toURL(request); + if (Option.isSome(requestUrl)) { + const websocketToken = requestUrl.value.searchParams.get(WEBSOCKET_TOKEN_QUERY_PARAM); + if (websocketToken && websocketToken.trim().length > 0) { + return yield* sessions.verifyWebSocketToken(websocketToken).pipe( + Effect.map((session) => ({ + sessionId: session.sessionId, + subject: session.subject, + method: session.method, + role: session.role, + ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}), + })), + Effect.mapError( + (cause) => + new AuthError({ + message: "Unauthorized request.", + status: 401, + cause, + }), + ), + ); + } + } + + return yield* authenticateRequest(request); + }); + + return { + getDescriptor: () => Effect.succeed(descriptor), + getSessionState, + exchangeBootstrapCredential, + exchangeBootstrapCredentialForBearerSession, + issuePairingCredential, + listPairingLinks, + revokePairingLink, + listClientSessions, + revokeClientSession, + revokeOtherClientSessions, + authenticateHttpRequest: authenticateRequest, + authenticateWebSocketUpgrade, + issueWebSocketToken, + issueStartupPairingUrl, + } satisfies ServerAuthShape; +}); + +export const ServerAuthLive = Layer.effect(ServerAuth, makeServerAuth).pipe( + Layer.provideMerge(AuthControlPlaneLive), + Layer.provideMerge(AuthCoreLive), + Layer.provideMerge(ServerAuthPolicyLive), +); diff --git a/apps/server/src/auth/Layers/ServerAuthPolicy.test.ts b/apps/server/src/auth/Layers/ServerAuthPolicy.test.ts new file mode 100644 index 0000000000..13ca0233ee --- /dev/null +++ b/apps/server/src/auth/Layers/ServerAuthPolicy.test.ts @@ -0,0 +1,114 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { Effect, Layer } from "effect"; + +import type { ServerConfigShape } from "../../config.ts"; +import { ServerConfig } from "../../config.ts"; +import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts"; +import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts"; + +const makeServerAuthPolicyLayer = (overrides?: Partial) => + ServerAuthPolicyLive.pipe( + Layer.provide( + Layer.effect( + ServerConfig, + Effect.gen(function* () { + const config = yield* ServerConfig; + return { + ...config, + ...overrides, + } satisfies ServerConfigShape; + }), + ).pipe( + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-policy-test-" })), + ), + ), + ); + +it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => { + it.effect("uses desktop-managed-local policy for desktop mode", () => + Effect.gen(function* () { + const policy = yield* ServerAuthPolicy; + const descriptor = yield* policy.getDescriptor(); + + expect(descriptor.policy).toBe("desktop-managed-local"); + expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]); + expect(descriptor.sessionCookieName).toBe("t3_session_3773"); + }).pipe( + Effect.provide( + makeServerAuthPolicyLayer({ + mode: "desktop", + port: 3773, + }), + ), + ), + ); + + it.effect("uses remote-reachable policy for desktop mode when bound beyond loopback", () => + Effect.gen(function* () { + const policy = yield* ServerAuthPolicy; + const descriptor = yield* policy.getDescriptor(); + + expect(descriptor.policy).toBe("remote-reachable"); + expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap", "one-time-token"]); + }).pipe( + Effect.provide( + makeServerAuthPolicyLayer({ + mode: "desktop", + host: "0.0.0.0", + }), + ), + ), + ); + + it.effect("uses loopback-browser policy for loopback web hosts", () => + Effect.gen(function* () { + const policy = yield* ServerAuthPolicy; + const descriptor = yield* policy.getDescriptor(); + + expect(descriptor.policy).toBe("loopback-browser"); + expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]); + expect(descriptor.sessionCookieName).toBe("t3_session"); + }).pipe( + Effect.provide( + makeServerAuthPolicyLayer({ + mode: "web", + host: "127.0.0.1", + }), + ), + ), + ); + + it.effect("uses remote-reachable policy for wildcard web hosts", () => + Effect.gen(function* () { + const policy = yield* ServerAuthPolicy; + const descriptor = yield* policy.getDescriptor(); + + expect(descriptor.policy).toBe("remote-reachable"); + expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]); + }).pipe( + Effect.provide( + makeServerAuthPolicyLayer({ + mode: "web", + host: "0.0.0.0", + }), + ), + ), + ); + + it.effect("uses remote-reachable policy for non-loopback web hosts", () => + Effect.gen(function* () { + const policy = yield* ServerAuthPolicy; + const descriptor = yield* policy.getDescriptor(); + + expect(descriptor.policy).toBe("remote-reachable"); + }).pipe( + Effect.provide( + makeServerAuthPolicyLayer({ + mode: "web", + host: "192.168.1.50", + }), + ), + ), + ); +}); diff --git a/apps/server/src/auth/Layers/ServerAuthPolicy.ts b/apps/server/src/auth/Layers/ServerAuthPolicy.ts new file mode 100644 index 0000000000..43735b4761 --- /dev/null +++ b/apps/server/src/auth/Layers/ServerAuthPolicy.ts @@ -0,0 +1,44 @@ +import type { ServerAuthDescriptor } from "@t3tools/contracts"; +import { Effect, Layer } from "effect"; + +import { ServerConfig } from "../../config.ts"; +import { ServerAuthPolicy, type ServerAuthPolicyShape } from "../Services/ServerAuthPolicy.ts"; +import { resolveSessionCookieName } from "../utils.ts"; +import { isLoopbackHost, isWildcardHost } from "../../startupAccess.ts"; + +export const makeServerAuthPolicy = Effect.gen(function* () { + const config = yield* ServerConfig; + const isRemoteReachable = isWildcardHost(config.host) || !isLoopbackHost(config.host); + + const policy = + config.mode === "desktop" + ? isRemoteReachable + ? "remote-reachable" + : "desktop-managed-local" + : isRemoteReachable + ? "remote-reachable" + : "loopback-browser"; + + const bootstrapMethods: ServerAuthDescriptor["bootstrapMethods"] = + policy === "desktop-managed-local" + ? ["desktop-bootstrap"] + : config.mode === "desktop" && policy === "remote-reachable" + ? ["desktop-bootstrap", "one-time-token"] + : ["one-time-token"]; + + const descriptor: ServerAuthDescriptor = { + policy, + bootstrapMethods, + sessionMethods: ["browser-session-cookie", "bearer-session-token"], + sessionCookieName: resolveSessionCookieName({ + mode: config.mode, + port: config.port, + }), + }; + + return { + getDescriptor: () => Effect.succeed(descriptor), + } satisfies ServerAuthPolicyShape; +}); + +export const ServerAuthPolicyLive = Layer.effect(ServerAuthPolicy, makeServerAuthPolicy); diff --git a/apps/server/src/auth/Layers/ServerSecretStore.test.ts b/apps/server/src/auth/Layers/ServerSecretStore.test.ts new file mode 100644 index 0000000000..7e6352eec2 --- /dev/null +++ b/apps/server/src/auth/Layers/ServerSecretStore.test.ts @@ -0,0 +1,263 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { Cause, Deferred, Effect, FileSystem, Layer, Ref } from "effect"; +import * as PlatformError from "effect/PlatformError"; + +import { ServerConfig } from "../../config.ts"; +import { SecretStoreError, ServerSecretStore } from "../Services/ServerSecretStore.ts"; +import { ServerSecretStoreLive } from "./ServerSecretStore.ts"; + +const makeServerConfigLayer = () => + ServerConfig.layerTest(process.cwd(), { prefix: "t3-secret-store-test-" }); + +const makeServerSecretStoreLayer = () => + Layer.provide(ServerSecretStoreLive, makeServerConfigLayer()); + +const PermissionDeniedFileSystemLayer = Layer.effect( + FileSystem.FileSystem, + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + + return { + ...fileSystem, + readFile: (path) => + Effect.fail( + PlatformError.systemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method: "readFile", + pathOrDescriptor: path, + description: "Permission denied while reading secret file.", + }), + ), + } satisfies FileSystem.FileSystem; + }), +).pipe(Layer.provide(NodeServices.layer)); + +const makePermissionDeniedSecretStoreLayer = () => + ServerSecretStoreLive.pipe( + Layer.provide(makeServerConfigLayer()), + Layer.provideMerge(PermissionDeniedFileSystemLayer), + ); + +const RenameFailureFileSystemLayer = Layer.effect( + FileSystem.FileSystem, + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + + return { + ...fileSystem, + rename: (from, to) => + Effect.fail( + PlatformError.systemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method: "rename", + pathOrDescriptor: `${String(from)} -> ${String(to)}`, + description: "Permission denied while persisting secret file.", + }), + ), + } satisfies FileSystem.FileSystem; + }), +).pipe(Layer.provide(NodeServices.layer)); + +const makeRenameFailureSecretStoreLayer = () => + ServerSecretStoreLive.pipe( + Layer.provide(makeServerConfigLayer()), + Layer.provideMerge(RenameFailureFileSystemLayer), + ); + +const RemoveFailureFileSystemLayer = Layer.effect( + FileSystem.FileSystem, + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + + return { + ...fileSystem, + remove: (path, options) => + Effect.fail( + PlatformError.systemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method: "remove", + pathOrDescriptor: String(path), + description: `Permission denied while removing secret file.${options ? " options-set" : ""}`, + }), + ), + } satisfies FileSystem.FileSystem; + }), +).pipe(Layer.provide(NodeServices.layer)); + +const makeRemoveFailureSecretStoreLayer = () => + ServerSecretStoreLive.pipe( + Layer.provide(makeServerConfigLayer()), + Layer.provideMerge(RemoveFailureFileSystemLayer), + ); + +const ConcurrentReadMissFileSystemLayer = Layer.effect( + FileSystem.FileSystem, + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const readCountRef = yield* Ref.make(0); + const readBarrier = yield* Deferred.make(); + + return { + ...fileSystem, + readFile: (path) => + String(path).endsWith("/session-signing-key.bin") + ? Ref.updateAndGet(readCountRef, (count) => count + 1).pipe( + Effect.flatMap((count) => { + if (count > 2) { + return fileSystem.readFile(path); + } + return Effect.gen(function* () { + if (count === 2) { + yield* Deferred.succeed(readBarrier, void 0); + } + yield* Deferred.await(readBarrier); + return yield* Effect.failCause( + Cause.fail( + PlatformError.systemError({ + _tag: "NotFound", + module: "FileSystem", + method: "readFile", + pathOrDescriptor: String(path), + description: "Secret file does not exist yet.", + }), + ), + ); + }); + }), + ) + : fileSystem.readFile(path), + } satisfies FileSystem.FileSystem; + }), +).pipe(Layer.provide(NodeServices.layer)); + +const makeConcurrentCreateSecretStoreLayer = () => + ServerSecretStoreLive.pipe( + Layer.provide(makeServerConfigLayer()), + Layer.provideMerge(ConcurrentReadMissFileSystemLayer), + ); + +it.layer(NodeServices.layer)("ServerSecretStoreLive", (it) => { + it.effect("returns null when a secret file does not exist", () => + Effect.gen(function* () { + const secretStore = yield* ServerSecretStore; + + const secret = yield* secretStore.get("missing-secret"); + + expect(secret).toBeNull(); + }).pipe(Effect.provide(makeServerSecretStoreLayer())), + ); + + it.effect("reuses an existing secret instead of regenerating it", () => + Effect.gen(function* () { + const secretStore = yield* ServerSecretStore; + + const first = yield* secretStore.getOrCreateRandom("session-signing-key", 32); + const second = yield* secretStore.getOrCreateRandom("session-signing-key", 32); + + expect(Array.from(second)).toEqual(Array.from(first)); + }).pipe(Effect.provide(makeServerSecretStoreLayer())), + ); + + it.effect("returns the persisted secret when concurrent creators race", () => + Effect.gen(function* () { + const secretStore = yield* ServerSecretStore; + + const [first, second] = yield* Effect.all( + [ + secretStore.getOrCreateRandom("session-signing-key", 32), + secretStore.getOrCreateRandom("session-signing-key", 32), + ], + { concurrency: "unbounded" }, + ); + const persisted = yield* secretStore.get("session-signing-key"); + + expect(persisted).not.toBeNull(); + expect(Array.from(first)).toEqual(Array.from(persisted ?? new Uint8Array())); + expect(Array.from(second)).toEqual(Array.from(persisted ?? new Uint8Array())); + }).pipe(Effect.provide(makeConcurrentCreateSecretStoreLayer())), + ); + + it.effect("uses restrictive permissions for the secret directory and files", () => + Effect.gen(function* () { + const chmodCalls: Array<{ readonly path: string; readonly mode: number }> = []; + const recordingFileSystemLayer = Layer.effect( + FileSystem.FileSystem, + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + + return { + ...fileSystem, + makeDirectory: () => Effect.void, + writeFile: () => Effect.void, + rename: () => Effect.void, + chmod: (path, mode) => + Effect.sync(() => { + chmodCalls.push({ path: String(path), mode }); + }), + } satisfies FileSystem.FileSystem; + }), + ).pipe(Layer.provide(NodeServices.layer)); + + const secretStore = yield* Effect.service(ServerSecretStore).pipe( + Effect.provide( + ServerSecretStoreLive.pipe( + Layer.provide(makeServerConfigLayer()), + Layer.provideMerge(recordingFileSystemLayer), + ), + ), + ); + + yield* secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3])); + + expect(chmodCalls.some((call) => call.mode === 0o700 && call.path.endsWith("/secrets"))).toBe( + true, + ); + expect(chmodCalls.filter((call) => call.mode === 0o600).length).toBeGreaterThanOrEqual(2); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("propagates read failures other than missing-file errors", () => + Effect.gen(function* () { + const secretStore = yield* ServerSecretStore; + + const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32)); + + expect(error).toBeInstanceOf(SecretStoreError); + expect(error.message).toContain("Failed to read secret session-signing-key."); + expect(error.cause).toBeInstanceOf(PlatformError.PlatformError); + expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied"); + }).pipe(Effect.provide(makePermissionDeniedSecretStoreLayer())), + ); + + it.effect("propagates write failures instead of treating them as success", () => + Effect.gen(function* () { + const secretStore = yield* ServerSecretStore; + + const error = yield* Effect.flip( + secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3])), + ); + + expect(error).toBeInstanceOf(SecretStoreError); + expect(error.message).toContain("Failed to persist secret session-signing-key."); + expect(error.cause).toBeInstanceOf(PlatformError.PlatformError); + expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied"); + }).pipe(Effect.provide(makeRenameFailureSecretStoreLayer())), + ); + + it.effect("propagates remove failures other than missing-file errors", () => + Effect.gen(function* () { + const secretStore = yield* ServerSecretStore; + + const error = yield* Effect.flip(secretStore.remove("session-signing-key")); + + expect(error).toBeInstanceOf(SecretStoreError); + expect(error.message).toContain("Failed to remove secret session-signing-key."); + expect(error.cause).toBeInstanceOf(PlatformError.PlatformError); + expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied"); + }).pipe(Effect.provide(makeRemoveFailureSecretStoreLayer())), + ); +}); diff --git a/apps/server/src/auth/Layers/ServerSecretStore.ts b/apps/server/src/auth/Layers/ServerSecretStore.ts new file mode 100644 index 0000000000..c8acf11bab --- /dev/null +++ b/apps/server/src/auth/Layers/ServerSecretStore.ts @@ -0,0 +1,148 @@ +import * as Crypto from "node:crypto"; + +import { Effect, FileSystem, Layer, Path, Predicate } from "effect"; +import * as PlatformError from "effect/PlatformError"; + +import { ServerConfig } from "../../config.ts"; +import { + SecretStoreError, + ServerSecretStore, + type ServerSecretStoreShape, +} from "../Services/ServerSecretStore.ts"; + +export const makeServerSecretStore = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const serverConfig = yield* ServerConfig; + + yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true }); + yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe( + Effect.mapError( + (cause) => + new SecretStoreError({ + message: `Failed to secure secrets directory ${serverConfig.secretsDir}.`, + cause, + }), + ), + ); + + const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`); + + const isPlatformError = (u: unknown): u is PlatformError.PlatformError => + Predicate.isTagged(u, "PlatformError"); + + const get: ServerSecretStoreShape["get"] = (name) => + fileSystem.readFile(resolveSecretPath(name)).pipe( + Effect.map((bytes) => Uint8Array.from(bytes)), + Effect.catch((cause) => + cause.reason._tag === "NotFound" + ? Effect.succeed(null) + : Effect.fail( + new SecretStoreError({ + message: `Failed to read secret ${name}.`, + cause, + }), + ), + ), + ); + + const set: ServerSecretStoreShape["set"] = (name, value) => { + const secretPath = resolveSecretPath(name); + const tempPath = `${secretPath}.${Crypto.randomUUID()}.tmp`; + return Effect.gen(function* () { + yield* fileSystem.writeFile(tempPath, value); + yield* fileSystem.chmod(tempPath, 0o600); + yield* fileSystem.rename(tempPath, secretPath); + yield* fileSystem.chmod(secretPath, 0o600); + }).pipe( + Effect.catch((cause) => + fileSystem.remove(tempPath).pipe( + Effect.ignore, + Effect.flatMap(() => + Effect.fail( + new SecretStoreError({ + message: `Failed to persist secret ${name}.`, + cause, + }), + ), + ), + ), + ), + ); + }; + + const create: ServerSecretStoreShape["set"] = (name, value) => { + const secretPath = resolveSecretPath(name); + return Effect.scoped( + Effect.gen(function* () { + const file = yield* fileSystem.open(secretPath, { + flag: "wx", + mode: 0o600, + }); + yield* file.writeAll(value); + yield* file.sync; + yield* fileSystem.chmod(secretPath, 0o600); + }), + ).pipe( + Effect.mapError( + (cause) => + new SecretStoreError({ + message: `Failed to persist secret ${name}.`, + cause, + }), + ), + ); + }; + + const getOrCreateRandom: ServerSecretStoreShape["getOrCreateRandom"] = (name, bytes) => + get(name).pipe( + Effect.flatMap((existing) => { + if (existing) { + return Effect.succeed(existing); + } + + const generated = Crypto.randomBytes(bytes); + return create(name, generated).pipe( + Effect.as(Uint8Array.from(generated)), + Effect.catchTag("SecretStoreError", (error) => + isPlatformError(error.cause) && error.cause.reason._tag === "AlreadyExists" + ? get(name).pipe( + Effect.flatMap((created) => + created !== null + ? Effect.succeed(created) + : Effect.fail( + new SecretStoreError({ + message: `Failed to read secret ${name} after concurrent creation.`, + }), + ), + ), + ) + : Effect.fail(error), + ), + ); + }), + ); + + const remove: ServerSecretStoreShape["remove"] = (name) => + fileSystem.remove(resolveSecretPath(name)).pipe( + Effect.catch((cause) => + cause.reason._tag === "NotFound" + ? Effect.void + : Effect.fail( + new SecretStoreError({ + message: `Failed to remove secret ${name}.`, + cause, + }), + ), + ), + ); + + return { + get, + set, + getOrCreateRandom, + remove, + } satisfies ServerSecretStoreShape; +}); + +export const ServerSecretStoreLive = Layer.effect(ServerSecretStore, makeServerSecretStore); diff --git a/apps/server/src/auth/Layers/SessionCredentialService.test.ts b/apps/server/src/auth/Layers/SessionCredentialService.test.ts new file mode 100644 index 0000000000..bafd9c85c2 --- /dev/null +++ b/apps/server/src/auth/Layers/SessionCredentialService.test.ts @@ -0,0 +1,191 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { Duration, Effect, Layer } from "effect"; +import { TestClock } from "effect/testing"; + +import type { ServerConfigShape } from "../../config.ts"; +import { ServerConfig } from "../../config.ts"; +import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; +import { SessionCredentialService } from "../Services/SessionCredentialService.ts"; +import { ServerSecretStoreLive } from "./ServerSecretStore.ts"; +import { SessionCredentialServiceLive } from "./SessionCredentialService.ts"; + +const makeServerConfigLayer = ( + overrides?: Partial>, +) => + Layer.effect( + ServerConfig, + Effect.gen(function* () { + const config = yield* ServerConfig; + return { + ...config, + ...overrides, + } satisfies ServerConfigShape; + }), + ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-session-test-" }))); + +const makeSessionCredentialLayer = ( + overrides?: Partial>, +) => + SessionCredentialServiceLive.pipe( + Layer.provide(SqlitePersistenceMemory), + Layer.provide(ServerSecretStoreLive), + Layer.provide(makeServerConfigLayer(overrides)), + ); + +it.layer(NodeServices.layer)("SessionCredentialServiceLive", (it) => { + it.effect("issues and verifies signed browser session tokens", () => + Effect.gen(function* () { + const sessions = yield* SessionCredentialService; + const issued = yield* sessions.issue({ + subject: "desktop-bootstrap", + role: "owner", + client: { + label: "Desktop app", + deviceType: "desktop", + os: "macOS", + browser: "Electron", + ipAddress: "127.0.0.1", + }, + }); + const verified = yield* sessions.verify(issued.token); + + expect(verified.method).toBe("browser-session-cookie"); + expect(verified.subject).toBe("desktop-bootstrap"); + expect(verified.role).toBe("owner"); + expect(verified.client.label).toBe("Desktop app"); + expect(verified.client.browser).toBe("Electron"); + expect(verified.expiresAt?.toString()).toBe(issued.expiresAt.toString()); + }).pipe(Effect.provide(makeSessionCredentialLayer())), + ); + it.effect("rejects malformed session tokens", () => + Effect.gen(function* () { + const sessions = yield* SessionCredentialService; + const error = yield* Effect.flip(sessions.verify("not-a-session-token")); + + expect(error._tag).toBe("SessionCredentialError"); + expect(error.message).toContain("Malformed session token"); + }).pipe(Effect.provide(makeSessionCredentialLayer())), + ); + it.effect("verifies session tokens against the Effect clock", () => + Effect.gen(function* () { + const sessions = yield* SessionCredentialService; + const issued = yield* sessions.issue({ + method: "bearer-session-token", + subject: "test-clock", + }); + const verified = yield* sessions.verify(issued.token); + + expect(verified.method).toBe("bearer-session-token"); + expect(verified.subject).toBe("test-clock"); + expect(verified.role).toBe("client"); + }).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))), + ); + + it.effect("rejects websocket tokens once the parent session has expired", () => + Effect.gen(function* () { + const sessions = yield* SessionCredentialService; + const issued = yield* sessions.issue({ + method: "bearer-session-token", + subject: "short-lived", + ttl: Duration.seconds(1), + }); + const websocket = yield* sessions.issueWebSocketToken(issued.sessionId); + + yield* TestClock.adjust(Duration.seconds(2)); + + const error = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token)); + expect(error.message).toContain("expired"); + }).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))), + ); + + it.effect("lists active sessions, tracks connectivity, and revokes other sessions", () => + Effect.gen(function* () { + const sessions = yield* SessionCredentialService; + const owner = yield* sessions.issue({ + subject: "desktop-bootstrap", + role: "owner", + client: { + label: "Desktop app", + deviceType: "desktop", + os: "macOS", + browser: "Electron", + }, + }); + const client = yield* sessions.issue({ + subject: "one-time-token", + role: "client", + client: { + label: "Julius iPhone", + deviceType: "mobile", + os: "iOS", + browser: "Safari", + ipAddress: "192.168.1.88", + }, + }); + + yield* sessions.markConnected(client.sessionId); + const beforeRevoke = yield* sessions.listActive(); + const revokedCount = yield* sessions.revokeAllExcept(owner.sessionId); + const afterRevoke = yield* sessions.listActive(); + const revokedClient = yield* Effect.flip(sessions.verify(client.token)); + + expect(beforeRevoke).toHaveLength(2); + expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.connected).toBe( + true, + ); + expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.client.label).toBe( + "Julius iPhone", + ); + expect( + beforeRevoke.find((entry) => entry.sessionId === owner.sessionId)?.client.deviceType, + ).toBe("desktop"); + expect(revokedCount).toBe(1); + expect(afterRevoke).toHaveLength(1); + expect(afterRevoke[0]?.sessionId).toBe(owner.sessionId); + expect(revokedClient.message).toContain("revoked"); + }).pipe(Effect.provide(makeSessionCredentialLayer())), + ); + + it.effect("persists lastConnectedAt on first connect and updates it after reconnect", () => + Effect.gen(function* () { + const sessions = yield* SessionCredentialService; + const issued = yield* sessions.issue({ + subject: "reconnect-test", + method: "bearer-session-token", + }); + + const beforeConnect = yield* sessions.listActive(); + expect(beforeConnect[0]?.lastConnectedAt).toBeNull(); + + yield* TestClock.adjust(Duration.seconds(1)); + yield* sessions.markConnected(issued.sessionId); + const firstConnect = yield* sessions.listActive(); + const firstConnectedAt = firstConnect[0]?.lastConnectedAt; + + expect(firstConnect[0]?.connected).toBe(true); + expect(firstConnectedAt).not.toBeNull(); + + yield* TestClock.adjust(Duration.seconds(1)); + yield* sessions.markConnected(issued.sessionId); + const stillConnected = yield* sessions.listActive(); + + expect(stillConnected[0]?.lastConnectedAt?.toString()).toBe(firstConnectedAt?.toString()); + + yield* sessions.markDisconnected(issued.sessionId); + yield* sessions.markDisconnected(issued.sessionId); + const afterDisconnect = yield* sessions.listActive(); + + expect(afterDisconnect[0]?.connected).toBe(false); + expect(afterDisconnect[0]?.lastConnectedAt?.toString()).toBe(firstConnectedAt?.toString()); + + yield* TestClock.adjust(Duration.seconds(1)); + yield* sessions.markConnected(issued.sessionId); + const afterReconnect = yield* sessions.listActive(); + + expect(afterReconnect[0]?.connected).toBe(true); + expect(afterReconnect[0]?.lastConnectedAt).not.toBeNull(); + expect(afterReconnect[0]?.lastConnectedAt?.toString()).not.toBe(firstConnectedAt?.toString()); + }).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))), + ); +}); diff --git a/apps/server/src/auth/Layers/SessionCredentialService.ts b/apps/server/src/auth/Layers/SessionCredentialService.ts new file mode 100644 index 0000000000..5ff4bbffff --- /dev/null +++ b/apps/server/src/auth/Layers/SessionCredentialService.ts @@ -0,0 +1,500 @@ +import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "@t3tools/contracts"; +import { Clock, DateTime, Duration, Effect, Layer, PubSub, Ref, Schema, Stream } from "effect"; +import { Option } from "effect"; + +import { ServerConfig } from "../../config.ts"; +import { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts"; +import { AuthSessionRepository } from "../../persistence/Services/AuthSessions.ts"; +import { ServerSecretStore } from "../Services/ServerSecretStore.ts"; +import { + SessionCredentialError, + SessionCredentialService, + type IssuedSession, + type SessionCredentialChange, + type SessionCredentialServiceShape, + type VerifiedSession, +} from "../Services/SessionCredentialService.ts"; +import { + base64UrlDecodeUtf8, + base64UrlEncode, + resolveSessionCookieName, + signPayload, + timingSafeEqualBase64Url, +} from "../utils.ts"; + +const SIGNING_SECRET_NAME = "server-signing-key"; +const DEFAULT_SESSION_TTL = Duration.days(30); +const DEFAULT_WEBSOCKET_TOKEN_TTL = Duration.minutes(5); + +const SessionClaims = Schema.Struct({ + v: Schema.Literal(1), + kind: Schema.Literal("session"), + sid: AuthSessionId, + sub: Schema.String, + role: Schema.Literals(["owner", "client"]), + method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]), + iat: Schema.Number, + exp: Schema.Number, +}); +type SessionClaims = typeof SessionClaims.Type; + +const WebSocketClaims = Schema.Struct({ + v: Schema.Literal(1), + kind: Schema.Literal("websocket"), + sid: AuthSessionId, + iat: Schema.Number, + exp: Schema.Number, +}); +type WebSocketClaims = typeof WebSocketClaims.Type; + +const decodeSessionClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(SessionClaims)); +const decodeWebSocketClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(WebSocketClaims)); + +function createDefaultClientMetadata(): AuthClientMetadata { + return { + deviceType: "unknown", + }; +} + +function toClientMetadata(record: { + readonly label: string | null; + readonly ipAddress: string | null; + readonly userAgent: string | null; + readonly deviceType: AuthClientMetadata["deviceType"]; + readonly os: string | null; + readonly browser: string | null; +}): AuthClientMetadata { + return { + ...(record.label ? { label: record.label } : {}), + ...(record.ipAddress ? { ipAddress: record.ipAddress } : {}), + ...(record.userAgent ? { userAgent: record.userAgent } : {}), + deviceType: record.deviceType, + ...(record.os ? { os: record.os } : {}), + ...(record.browser ? { browser: record.browser } : {}), + }; +} + +function toAuthClientSession(input: Omit): AuthClientSession { + return { + ...input, + current: false, + }; +} + +export const makeSessionCredentialService = Effect.gen(function* () { + const serverConfig = yield* ServerConfig; + const secretStore = yield* ServerSecretStore; + const authSessions = yield* AuthSessionRepository; + const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32); + const connectedSessionsRef = yield* Ref.make(new Map()); + const changesPubSub = yield* PubSub.unbounded(); + const cookieName = resolveSessionCookieName({ + mode: serverConfig.mode, + port: serverConfig.port, + }); + + const toSessionCredentialError = (message: string) => (cause: unknown) => + new SessionCredentialError({ + message, + cause, + }); + + const emitUpsert = (clientSession: AuthClientSession) => + PubSub.publish(changesPubSub, { + type: "clientUpserted", + clientSession, + }).pipe(Effect.asVoid); + + const emitRemoved = (sessionId: AuthSessionId) => + PubSub.publish(changesPubSub, { + type: "clientRemoved", + sessionId, + }).pipe(Effect.asVoid); + + const loadActiveSession = (sessionId: AuthSessionId) => + Effect.gen(function* () { + const row = yield* authSessions.getById({ sessionId }); + if (Option.isNone(row) || row.value.revokedAt !== null) { + return Option.none(); + } + + const connectedSessions = yield* Ref.get(connectedSessionsRef); + return Option.some( + toAuthClientSession({ + sessionId: row.value.sessionId, + subject: row.value.subject, + role: row.value.role, + method: row.value.method, + client: toClientMetadata(row.value.client), + issuedAt: row.value.issuedAt, + expiresAt: row.value.expiresAt, + lastConnectedAt: row.value.lastConnectedAt, + connected: connectedSessions.has(row.value.sessionId), + }), + ); + }); + + const markConnected: SessionCredentialServiceShape["markConnected"] = (sessionId) => + Ref.modify(connectedSessionsRef, (current) => { + const next = new Map(current); + const wasDisconnected = !next.has(sessionId); + next.set(sessionId, (next.get(sessionId) ?? 0) + 1); + return [wasDisconnected, next] as const; + }).pipe( + Effect.flatMap((wasDisconnected) => + wasDisconnected + ? DateTime.now.pipe( + Effect.flatMap((lastConnectedAt) => + authSessions.setLastConnectedAt({ + sessionId, + lastConnectedAt, + }), + ), + ) + : Effect.void, + ), + Effect.flatMap(() => loadActiveSession(sessionId)), + Effect.flatMap((session) => + Option.isSome(session) ? emitUpsert(session.value) : Effect.void, + ), + Effect.catchCause((cause) => + Effect.logError("Failed to publish connected-session auth update.").pipe( + Effect.annotateLogs({ + sessionId, + cause, + }), + ), + ), + ); + + const markDisconnected: SessionCredentialServiceShape["markDisconnected"] = (sessionId) => + Ref.update(connectedSessionsRef, (current) => { + const next = new Map(current); + const remaining = (next.get(sessionId) ?? 0) - 1; + if (remaining > 0) { + next.set(sessionId, remaining); + } else { + next.delete(sessionId); + } + return next; + }).pipe( + Effect.flatMap(() => loadActiveSession(sessionId)), + Effect.flatMap((session) => + Option.isSome(session) ? emitUpsert(session.value) : Effect.void, + ), + Effect.catchCause((cause) => + Effect.logError("Failed to publish disconnected-session auth update.").pipe( + Effect.annotateLogs({ + sessionId, + cause, + }), + ), + ), + ); + + const issue: SessionCredentialServiceShape["issue"] = (input) => + Effect.gen(function* () { + const sessionId = AuthSessionId.make(crypto.randomUUID()); + const issuedAt = yield* DateTime.now; + const expiresAt = DateTime.add(issuedAt, { + milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL), + }); + const claims: SessionClaims = { + v: 1, + kind: "session", + sid: sessionId, + sub: input?.subject ?? "browser", + role: input?.role ?? "client", + method: input?.method ?? "browser-session-cookie", + iat: issuedAt.epochMilliseconds, + exp: expiresAt.epochMilliseconds, + }; + const encodedPayload = base64UrlEncode(JSON.stringify(claims)); + const signature = signPayload(encodedPayload, signingSecret); + const client = input?.client ?? createDefaultClientMetadata(); + yield* authSessions.create({ + sessionId, + subject: claims.sub, + role: claims.role, + method: claims.method, + client: { + label: client.label ?? null, + ipAddress: client.ipAddress ?? null, + userAgent: client.userAgent ?? null, + deviceType: client.deviceType, + os: client.os ?? null, + browser: client.browser ?? null, + }, + issuedAt, + expiresAt, + }); + yield* emitUpsert( + toAuthClientSession({ + sessionId, + subject: claims.sub, + role: claims.role, + method: claims.method, + client, + issuedAt, + expiresAt, + lastConnectedAt: null, + connected: false, + }), + ); + + return { + sessionId, + token: `${encodedPayload}.${signature}`, + method: claims.method, + client, + expiresAt: expiresAt, + role: claims.role, + } satisfies IssuedSession; + }).pipe(Effect.mapError(toSessionCredentialError("Failed to issue session credential."))); + + const verify: SessionCredentialServiceShape["verify"] = (token) => + Effect.gen(function* () { + const [encodedPayload, signature] = token.split("."); + if (!encodedPayload || !signature) { + return yield* new SessionCredentialError({ + message: "Malformed session token.", + }); + } + + const expectedSignature = signPayload(encodedPayload, signingSecret); + if (!timingSafeEqualBase64Url(signature, expectedSignature)) { + return yield* new SessionCredentialError({ + message: "Invalid session token signature.", + }); + } + + const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe( + Effect.mapError( + (cause) => + new SessionCredentialError({ + message: "Invalid session token payload.", + cause, + }), + ), + ); + + const now = yield* Clock.currentTimeMillis; + if (claims.exp <= now) { + return yield* new SessionCredentialError({ + message: "Session token expired.", + }); + } + + const row = yield* authSessions.getById({ sessionId: claims.sid }); + if (Option.isNone(row)) { + return yield* new SessionCredentialError({ + message: "Unknown session token.", + }); + } + if (row.value.revokedAt !== null) { + return yield* new SessionCredentialError({ + message: "Session token revoked.", + }); + } + + return { + sessionId: claims.sid, + token, + method: claims.method, + client: toClientMetadata(row.value.client), + expiresAt: DateTime.makeUnsafe(claims.exp), + subject: claims.sub, + role: claims.role, + } satisfies VerifiedSession; + }).pipe( + Effect.mapError((cause) => + cause instanceof SessionCredentialError + ? cause + : new SessionCredentialError({ + message: "Failed to verify session credential.", + cause, + }), + ), + ); + + const issueWebSocketToken: SessionCredentialServiceShape["issueWebSocketToken"] = ( + sessionId, + input, + ) => + Effect.gen(function* () { + const issuedAt = yield* DateTime.now; + const expiresAt = DateTime.add(issuedAt, { + milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL), + }); + const claims: WebSocketClaims = { + v: 1, + kind: "websocket", + sid: sessionId, + iat: issuedAt.epochMilliseconds, + exp: expiresAt.epochMilliseconds, + }; + const encodedPayload = base64UrlEncode(JSON.stringify(claims)); + const signature = signPayload(encodedPayload, signingSecret); + return { + token: `${encodedPayload}.${signature}`, + expiresAt, + }; + }).pipe(Effect.mapError(toSessionCredentialError("Failed to issue websocket token."))); + + const verifyWebSocketToken: SessionCredentialServiceShape["verifyWebSocketToken"] = (token) => + Effect.gen(function* () { + const [encodedPayload, signature] = token.split("."); + if (!encodedPayload || !signature) { + return yield* new SessionCredentialError({ + message: "Malformed websocket token.", + }); + } + + const expectedSignature = signPayload(encodedPayload, signingSecret); + if (!timingSafeEqualBase64Url(signature, expectedSignature)) { + return yield* new SessionCredentialError({ + message: "Invalid websocket token signature.", + }); + } + + const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe( + Effect.mapError( + (cause) => + new SessionCredentialError({ + message: "Invalid websocket token payload.", + cause, + }), + ), + ); + + const now = yield* Clock.currentTimeMillis; + if (claims.exp <= now) { + return yield* new SessionCredentialError({ + message: "Websocket token expired.", + }); + } + + const row = yield* authSessions.getById({ sessionId: claims.sid }); + if (Option.isNone(row)) { + return yield* new SessionCredentialError({ + message: "Unknown websocket session.", + }); + } + if (row.value.expiresAt.epochMilliseconds <= now) { + return yield* new SessionCredentialError({ + message: "Websocket session expired.", + }); + } + if (row.value.revokedAt !== null) { + return yield* new SessionCredentialError({ + message: "Websocket session revoked.", + }); + } + + return { + sessionId: row.value.sessionId, + token, + method: row.value.method, + client: toClientMetadata(row.value.client), + expiresAt: row.value.expiresAt, + subject: row.value.subject, + role: row.value.role, + } satisfies VerifiedSession; + }).pipe( + Effect.mapError((cause) => + cause instanceof SessionCredentialError + ? cause + : new SessionCredentialError({ + message: "Failed to verify websocket token.", + cause, + }), + ), + ); + + const listActive: SessionCredentialServiceShape["listActive"] = () => + Effect.gen(function* () { + const now = yield* DateTime.now; + const connectedSessions = yield* Ref.get(connectedSessionsRef); + const rows = yield* authSessions.listActive({ now }); + + return rows.map((row) => + toAuthClientSession({ + sessionId: row.sessionId, + subject: row.subject, + role: row.role, + method: row.method, + client: toClientMetadata(row.client), + issuedAt: row.issuedAt, + expiresAt: row.expiresAt, + lastConnectedAt: row.lastConnectedAt, + connected: connectedSessions.has(row.sessionId), + }), + ); + }).pipe(Effect.mapError(toSessionCredentialError("Failed to list active sessions."))); + + const revoke: SessionCredentialServiceShape["revoke"] = (sessionId) => + Effect.gen(function* () { + const revokedAt = yield* DateTime.now; + const revoked = yield* authSessions.revoke({ + sessionId, + revokedAt, + }); + if (revoked) { + yield* Ref.update(connectedSessionsRef, (current) => { + const next = new Map(current); + next.delete(sessionId); + return next; + }); + yield* emitRemoved(sessionId); + } + return revoked; + }).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke session."))); + + const revokeAllExcept: SessionCredentialServiceShape["revokeAllExcept"] = (sessionId) => + Effect.gen(function* () { + const revokedAt = yield* DateTime.now; + const revokedSessionIds = yield* authSessions.revokeAllExcept({ + currentSessionId: sessionId, + revokedAt, + }); + if (revokedSessionIds.length > 0) { + yield* Ref.update(connectedSessionsRef, (current) => { + const next = new Map(current); + for (const revokedSessionId of revokedSessionIds) { + next.delete(revokedSessionId); + } + return next; + }); + yield* Effect.forEach( + revokedSessionIds, + (revokedSessionId) => emitRemoved(revokedSessionId), + { + concurrency: "unbounded", + discard: true, + }, + ); + } + return revokedSessionIds.length; + }).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke other sessions."))); + + return { + cookieName, + issue, + verify, + issueWebSocketToken, + verifyWebSocketToken, + listActive, + get streamChanges() { + return Stream.fromPubSub(changesPubSub); + }, + revoke, + revokeAllExcept, + markConnected, + markDisconnected, + } satisfies SessionCredentialServiceShape; +}); + +export const SessionCredentialServiceLive = Layer.effect( + SessionCredentialService, + makeSessionCredentialService, +).pipe(Layer.provideMerge(AuthSessionRepositoryLive)); diff --git a/apps/server/src/auth/Services/AuthControlPlane.ts b/apps/server/src/auth/Services/AuthControlPlane.ts new file mode 100644 index 0000000000..b59e330bca --- /dev/null +++ b/apps/server/src/auth/Services/AuthControlPlane.ts @@ -0,0 +1,69 @@ +import type { + AuthClientMetadata, + AuthClientSession, + AuthPairingLink, + AuthSessionId, +} from "@t3tools/contracts"; +import { Data, DateTime, Duration, Effect, Context } from "effect"; +import { SessionRole } from "./SessionCredentialService"; + +export const DEFAULT_SESSION_SUBJECT = "cli-issued-session"; + +export interface IssuedPairingLink { + readonly id: string; + readonly credential: string; + readonly role: SessionRole; + readonly subject: string; + readonly label?: string; + readonly createdAt: DateTime.Utc; + readonly expiresAt: DateTime.Utc; +} + +export interface IssuedBearerSession { + readonly sessionId: AuthSessionId; + readonly token: string; + readonly method: "bearer-session-token"; + readonly role: SessionRole; + readonly subject: string; + readonly client: AuthClientMetadata; + readonly expiresAt: DateTime.Utc; +} + +export class AuthControlPlaneError extends Data.TaggedError("AuthControlPlaneError")<{ + readonly message: string; + readonly cause?: unknown; +}> {} + +export interface AuthControlPlaneShape { + readonly createPairingLink: (input?: { + readonly ttl?: Duration.Duration; + readonly label?: string; + readonly role?: SessionRole; + readonly subject?: string; + }) => Effect.Effect; + readonly listPairingLinks: (input?: { + readonly role?: SessionRole; + readonly excludeSubjects?: ReadonlyArray; + }) => Effect.Effect, AuthControlPlaneError>; + readonly revokePairingLink: (id: string) => Effect.Effect; + readonly issueSession: (input?: { + readonly ttl?: Duration.Duration; + readonly subject?: string; + readonly role?: SessionRole; + readonly label?: string; + }) => Effect.Effect; + readonly listSessions: () => Effect.Effect< + ReadonlyArray, + AuthControlPlaneError + >; + readonly revokeSession: ( + sessionId: AuthSessionId, + ) => Effect.Effect; + readonly revokeOtherSessionsExcept: ( + sessionId: AuthSessionId, + ) => Effect.Effect; +} + +export class AuthControlPlane extends Context.Service()( + "t3/AuthControlPlane", +) {} diff --git a/apps/server/src/auth/Services/BootstrapCredentialService.ts b/apps/server/src/auth/Services/BootstrapCredentialService.ts new file mode 100644 index 0000000000..bcb6119a22 --- /dev/null +++ b/apps/server/src/auth/Services/BootstrapCredentialService.ts @@ -0,0 +1,57 @@ +import type { AuthPairingLink, ServerAuthBootstrapMethod } from "@t3tools/contracts"; +import { Data, DateTime, Duration, Context } from "effect"; +import type { Effect, Stream } from "effect"; + +export type BootstrapCredentialRole = "owner" | "client"; + +export interface BootstrapGrant { + readonly method: ServerAuthBootstrapMethod; + readonly role: BootstrapCredentialRole; + readonly subject: string; + readonly label?: string; + readonly expiresAt: DateTime.DateTime; +} + +export class BootstrapCredentialError extends Data.TaggedError("BootstrapCredentialError")<{ + readonly message: string; + readonly status?: 401 | 500; + readonly cause?: unknown; +}> {} + +export interface IssuedBootstrapCredential { + readonly id: string; + readonly credential: string; + readonly label?: string; + readonly expiresAt: DateTime.Utc; +} + +export type BootstrapCredentialChange = + | { + readonly type: "pairingLinkUpserted"; + readonly pairingLink: AuthPairingLink; + } + | { + readonly type: "pairingLinkRemoved"; + readonly id: string; + }; + +export interface BootstrapCredentialServiceShape { + readonly issueOneTimeToken: (input?: { + readonly ttl?: Duration.Duration; + readonly role?: BootstrapCredentialRole; + readonly subject?: string; + readonly label?: string; + }) => Effect.Effect; + readonly listActive: () => Effect.Effect< + ReadonlyArray, + BootstrapCredentialError + >; + readonly streamChanges: Stream.Stream; + readonly revoke: (id: string) => Effect.Effect; + readonly consume: (credential: string) => Effect.Effect; +} + +export class BootstrapCredentialService extends Context.Service< + BootstrapCredentialService, + BootstrapCredentialServiceShape +>()("t3/auth/Services/BootstrapCredentialService") {} diff --git a/apps/server/src/auth/Services/ServerAuth.ts b/apps/server/src/auth/Services/ServerAuth.ts new file mode 100644 index 0000000000..07be98269b --- /dev/null +++ b/apps/server/src/auth/Services/ServerAuth.ts @@ -0,0 +1,84 @@ +import type { + AuthBearerBootstrapResult, + AuthBootstrapResult, + AuthClientMetadata, + AuthClientSession, + AuthCreatePairingCredentialInput, + AuthPairingLink, + AuthPairingCredentialResult, + AuthSessionId, + AuthSessionState, + ServerAuthDescriptor, + ServerAuthSessionMethod, + AuthWebSocketTokenResult, +} from "@t3tools/contracts"; +import { Data, DateTime, Context } from "effect"; +import type { Effect } from "effect"; +import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest"; +import type { SessionRole } from "./SessionCredentialService.ts"; + +export interface AuthenticatedSession { + readonly sessionId: AuthSessionId; + readonly subject: string; + readonly method: ServerAuthSessionMethod; + readonly role: SessionRole; + readonly expiresAt?: DateTime.DateTime; +} + +export class AuthError extends Data.TaggedError("AuthError")<{ + readonly message: string; + readonly status?: 400 | 401 | 403 | 500; + readonly cause?: unknown; +}> {} + +export interface ServerAuthShape { + readonly getDescriptor: () => Effect.Effect; + readonly getSessionState: ( + request: HttpServerRequest.HttpServerRequest, + ) => Effect.Effect; + readonly exchangeBootstrapCredential: ( + credential: string, + requestMetadata: AuthClientMetadata, + ) => Effect.Effect< + { + readonly response: AuthBootstrapResult; + readonly sessionToken: string; + }, + AuthError + >; + readonly exchangeBootstrapCredentialForBearerSession: ( + credential: string, + requestMetadata: AuthClientMetadata, + ) => Effect.Effect; + readonly issuePairingCredential: ( + input?: AuthCreatePairingCredentialInput & { + readonly role?: SessionRole; + }, + ) => Effect.Effect; + readonly listPairingLinks: () => Effect.Effect, AuthError>; + readonly revokePairingLink: (id: string) => Effect.Effect; + readonly listClientSessions: ( + currentSessionId: AuthSessionId, + ) => Effect.Effect, AuthError>; + readonly revokeClientSession: ( + currentSessionId: AuthSessionId, + targetSessionId: AuthSessionId, + ) => Effect.Effect; + readonly revokeOtherClientSessions: ( + currentSessionId: AuthSessionId, + ) => Effect.Effect; + readonly authenticateHttpRequest: ( + request: HttpServerRequest.HttpServerRequest, + ) => Effect.Effect; + readonly authenticateWebSocketUpgrade: ( + request: HttpServerRequest.HttpServerRequest, + ) => Effect.Effect; + readonly issueWebSocketToken: ( + session: AuthenticatedSession, + ) => Effect.Effect; + readonly issueStartupPairingUrl: (baseUrl: string) => Effect.Effect; +} + +export class ServerAuth extends Context.Service()( + "t3/auth/Services/ServerAuth", +) {} diff --git a/apps/server/src/auth/Services/ServerAuthPolicy.ts b/apps/server/src/auth/Services/ServerAuthPolicy.ts new file mode 100644 index 0000000000..530d776998 --- /dev/null +++ b/apps/server/src/auth/Services/ServerAuthPolicy.ts @@ -0,0 +1,11 @@ +import type { ServerAuthDescriptor } from "@t3tools/contracts"; +import { Context } from "effect"; +import type { Effect } from "effect"; + +export interface ServerAuthPolicyShape { + readonly getDescriptor: () => Effect.Effect; +} + +export class ServerAuthPolicy extends Context.Service()( + "t3/auth/Services/ServerAuthPolicy", +) {} diff --git a/apps/server/src/auth/Services/ServerSecretStore.ts b/apps/server/src/auth/Services/ServerSecretStore.ts new file mode 100644 index 0000000000..7d97b4c3a1 --- /dev/null +++ b/apps/server/src/auth/Services/ServerSecretStore.ts @@ -0,0 +1,21 @@ +import { Data, Context } from "effect"; +import type { Effect } from "effect"; + +export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{ + readonly message: string; + readonly cause?: unknown; +}> {} + +export interface ServerSecretStoreShape { + readonly get: (name: string) => Effect.Effect; + readonly set: (name: string, value: Uint8Array) => Effect.Effect; + readonly getOrCreateRandom: ( + name: string, + bytes: number, + ) => Effect.Effect; + readonly remove: (name: string) => Effect.Effect; +} + +export class ServerSecretStore extends Context.Service()( + "t3/auth/Services/ServerSecretStore", +) {} diff --git a/apps/server/src/auth/Services/SessionCredentialService.ts b/apps/server/src/auth/Services/SessionCredentialService.ts new file mode 100644 index 0000000000..3d72b5a636 --- /dev/null +++ b/apps/server/src/auth/Services/SessionCredentialService.ts @@ -0,0 +1,87 @@ +import type { + AuthClientMetadata, + AuthClientSession, + AuthSessionId, + ServerAuthSessionMethod, +} from "@t3tools/contracts"; +import { Data, DateTime, Duration, Context } from "effect"; +import type { Effect, Stream } from "effect"; + +export type SessionRole = "owner" | "client"; + +export interface IssuedSession { + readonly sessionId: AuthSessionId; + readonly token: string; + readonly method: ServerAuthSessionMethod; + readonly client: AuthClientMetadata; + readonly expiresAt: DateTime.DateTime; + readonly role: SessionRole; +} + +export interface VerifiedSession { + readonly sessionId: AuthSessionId; + readonly token: string; + readonly method: ServerAuthSessionMethod; + readonly client: AuthClientMetadata; + readonly expiresAt?: DateTime.DateTime; + readonly subject: string; + readonly role: SessionRole; +} + +export type SessionCredentialChange = + | { + readonly type: "clientUpserted"; + readonly clientSession: AuthClientSession; + } + | { + readonly type: "clientRemoved"; + readonly sessionId: AuthSessionId; + }; + +export class SessionCredentialError extends Data.TaggedError("SessionCredentialError")<{ + readonly message: string; + readonly cause?: unknown; +}> {} + +export interface SessionCredentialServiceShape { + readonly cookieName: string; + readonly issue: (input?: { + readonly ttl?: Duration.Duration; + readonly subject?: string; + readonly method?: ServerAuthSessionMethod; + readonly role?: SessionRole; + readonly client?: AuthClientMetadata; + }) => Effect.Effect; + readonly verify: (token: string) => Effect.Effect; + readonly issueWebSocketToken: ( + sessionId: AuthSessionId, + input?: { + readonly ttl?: Duration.Duration; + }, + ) => Effect.Effect< + { + readonly token: string; + readonly expiresAt: DateTime.DateTime; + }, + SessionCredentialError + >; + readonly verifyWebSocketToken: ( + token: string, + ) => Effect.Effect; + readonly listActive: () => Effect.Effect< + ReadonlyArray, + SessionCredentialError + >; + readonly streamChanges: Stream.Stream; + readonly revoke: (sessionId: AuthSessionId) => Effect.Effect; + readonly revokeAllExcept: ( + sessionId: AuthSessionId, + ) => Effect.Effect; + readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect; + readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect; +} + +export class SessionCredentialService extends Context.Service< + SessionCredentialService, + SessionCredentialServiceShape +>()("t3/auth/Services/SessionCredentialService") {} diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.ts new file mode 100644 index 0000000000..76c14646e9 --- /dev/null +++ b/apps/server/src/auth/http.ts @@ -0,0 +1,254 @@ +import { + type AuthBearerBootstrapResult, + AuthBootstrapInput, + AuthCreatePairingCredentialInput, + AuthRevokeClientSessionInput, + AuthRevokePairingLinkInput, + type AuthWebSocketTokenResult, +} from "@t3tools/contracts"; +import { DateTime, Effect, Schema } from "effect"; +import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http"; + +import { AuthError, ServerAuth } from "./Services/ServerAuth.ts"; +import { SessionCredentialService } from "./Services/SessionCredentialService.ts"; +import { deriveAuthClientMetadata } from "./utils.ts"; + +export const respondToAuthError = (error: AuthError) => + Effect.gen(function* () { + if ((error.status ?? 500) >= 500) { + yield* Effect.logError("auth route failed", { + message: error.message, + cause: error.cause, + }); + } + return HttpServerResponse.jsonUnsafe( + { + error: error.message, + }, + { status: error.status ?? 500 }, + ); + }); + +export const authSessionRouteLayer = HttpRouter.add( + "GET", + "/api/auth/session", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const serverAuth = yield* ServerAuth; + const session = yield* serverAuth.getSessionState(request); + return HttpServerResponse.jsonUnsafe(session, { status: 200 }); + }), +); + +const PairingCredentialRequestHeaders = Schema.Struct({ + "content-length": Schema.optionalKey(Schema.String), + "content-type": Schema.optionalKey(Schema.String), + "transfer-encoding": Schema.optionalKey(Schema.String), +}); + +function hasRequestBody(headers: typeof PairingCredentialRequestHeaders.Type) { + const contentLengthHeader = headers["content-length"]; + if (typeof contentLengthHeader === "string") { + const contentLength = Number.parseInt(contentLengthHeader, 10); + if (Number.isFinite(contentLength)) { + return contentLength > 0; + } + } + return typeof headers["transfer-encoding"] === "string"; +} + +export const authBootstrapRouteLayer = HttpRouter.add( + "POST", + "/api/auth/bootstrap", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const serverAuth = yield* ServerAuth; + const sessions = yield* SessionCredentialService; + const payload = yield* HttpServerRequest.schemaBodyJson(AuthBootstrapInput).pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Invalid bootstrap payload.", + status: 400, + cause, + }), + ), + ); + const result = yield* serverAuth.exchangeBootstrapCredential( + payload.credential, + deriveAuthClientMetadata({ request }), + ); + + return yield* HttpServerResponse.jsonUnsafe(result.response, { status: 200 }).pipe( + HttpServerResponse.setCookie(sessions.cookieName, result.sessionToken, { + expires: DateTime.toDate(result.response.expiresAt), + httpOnly: true, + path: "/", + sameSite: "lax", + }), + ); + }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))), +); + +export const authBearerBootstrapRouteLayer = HttpRouter.add( + "POST", + "/api/auth/bootstrap/bearer", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const serverAuth = yield* ServerAuth; + const payload = yield* HttpServerRequest.schemaBodyJson(AuthBootstrapInput).pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Invalid bootstrap payload.", + status: 400, + cause, + }), + ), + ); + const result = yield* serverAuth.exchangeBootstrapCredentialForBearerSession( + payload.credential, + deriveAuthClientMetadata({ request }), + ); + return HttpServerResponse.jsonUnsafe(result satisfies AuthBearerBootstrapResult, { + status: 200, + }); + }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))), +); + +export const authWebSocketTokenRouteLayer = HttpRouter.add( + "POST", + "/api/auth/ws-token", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const serverAuth = yield* ServerAuth; + const session = yield* serverAuth.authenticateHttpRequest(request); + const result = yield* serverAuth.issueWebSocketToken(session); + return HttpServerResponse.jsonUnsafe(result satisfies AuthWebSocketTokenResult, { + status: 200, + }); + }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))), +); + +export const authPairingCredentialRouteLayer = HttpRouter.add( + "POST", + "/api/auth/pairing-token", + Effect.gen(function* () { + const serverAuth = yield* ServerAuth; + const request = yield* HttpServerRequest.HttpServerRequest; + const session = yield* serverAuth.authenticateHttpRequest(request); + if (session.role !== "owner") { + return yield* new AuthError({ + message: "Only owner sessions can create pairing credentials.", + status: 403, + }); + } + const headers = yield* HttpServerRequest.schemaHeaders(PairingCredentialRequestHeaders).pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Invalid pairing credential request headers.", + status: 400, + cause, + }), + ), + ); + const payload = hasRequestBody(headers) + ? yield* HttpServerRequest.schemaBodyJson(AuthCreatePairingCredentialInput).pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Invalid pairing credential payload.", + status: 400, + cause, + }), + ), + ) + : {}; + const result = yield* serverAuth.issuePairingCredential(payload); + return HttpServerResponse.jsonUnsafe(result, { status: 200 }); + }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))), +); + +const authenticateOwnerSession = Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const serverAuth = yield* ServerAuth; + const session = yield* serverAuth.authenticateHttpRequest(request); + if (session.role !== "owner") { + return yield* new AuthError({ + message: "Only owner sessions can manage network access.", + status: 403, + }); + } + return { serverAuth, session } as const; +}); + +export const authPairingLinksRouteLayer = HttpRouter.add( + "GET", + "/api/auth/pairing-links", + Effect.gen(function* () { + const { serverAuth } = yield* authenticateOwnerSession; + const pairingLinks = yield* serverAuth.listPairingLinks(); + return HttpServerResponse.jsonUnsafe(pairingLinks, { status: 200 }); + }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))), +); + +export const authPairingLinksRevokeRouteLayer = HttpRouter.add( + "POST", + "/api/auth/pairing-links/revoke", + Effect.gen(function* () { + const { serverAuth } = yield* authenticateOwnerSession; + const payload = yield* HttpServerRequest.schemaBodyJson(AuthRevokePairingLinkInput).pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Invalid revoke pairing link payload.", + status: 400, + cause, + }), + ), + ); + const revoked = yield* serverAuth.revokePairingLink(payload.id); + return HttpServerResponse.jsonUnsafe({ revoked }, { status: 200 }); + }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))), +); + +export const authClientsRouteLayer = HttpRouter.add( + "GET", + "/api/auth/clients", + Effect.gen(function* () { + const { serverAuth, session } = yield* authenticateOwnerSession; + const clients = yield* serverAuth.listClientSessions(session.sessionId); + return HttpServerResponse.jsonUnsafe(clients, { status: 200 }); + }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))), +); + +export const authClientsRevokeRouteLayer = HttpRouter.add( + "POST", + "/api/auth/clients/revoke", + Effect.gen(function* () { + const { serverAuth, session } = yield* authenticateOwnerSession; + const payload = yield* HttpServerRequest.schemaBodyJson(AuthRevokeClientSessionInput).pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Invalid revoke client payload.", + status: 400, + cause, + }), + ), + ); + const revoked = yield* serverAuth.revokeClientSession(session.sessionId, payload.sessionId); + return HttpServerResponse.jsonUnsafe({ revoked }, { status: 200 }); + }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))), +); + +export const authClientsRevokeOthersRouteLayer = HttpRouter.add( + "POST", + "/api/auth/clients/revoke-others", + Effect.gen(function* () { + const { serverAuth, session } = yield* authenticateOwnerSession; + const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId); + return HttpServerResponse.jsonUnsafe({ revokedCount }, { status: 200 }); + }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))), +); diff --git a/apps/server/src/auth/utils.test.ts b/apps/server/src/auth/utils.test.ts new file mode 100644 index 0000000000..a767b77de1 --- /dev/null +++ b/apps/server/src/auth/utils.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from "vitest"; + +import { deriveAuthClientMetadata } from "./utils"; + +describe("deriveAuthClientMetadata", () => { + it("labels Electron user agents as Electron instead of Chrome", () => { + const metadata = deriveAuthClientMetadata({ + request: { + headers: { + "user-agent": + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) t3code/0.0.15 Chrome/136.0.7103.93 Electron/36.3.2 Safari/537.36", + }, + source: { + remoteAddress: "::ffff:127.0.0.1", + }, + } as never, + }); + + expect(metadata).toMatchObject({ + browser: "Electron", + deviceType: "desktop", + ipAddress: "127.0.0.1", + os: "macOS", + }); + }); +}); diff --git a/apps/server/src/auth/utils.ts b/apps/server/src/auth/utils.ts new file mode 100644 index 0000000000..2c76a81f65 --- /dev/null +++ b/apps/server/src/auth/utils.ts @@ -0,0 +1,132 @@ +import type { AuthClientMetadata, AuthClientMetadataDeviceType } from "@t3tools/contracts"; +import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest"; +import * as Crypto from "node:crypto"; + +const SESSION_COOKIE_NAME = "t3_session"; + +export function resolveSessionCookieName(input: { + readonly mode: "web" | "desktop"; + readonly port: number; +}): string { + if (input.mode !== "desktop") { + return SESSION_COOKIE_NAME; + } + + return `${SESSION_COOKIE_NAME}_${input.port}`; +} + +export function base64UrlEncode(input: string | Uint8Array): string { + const buffer = typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.from(input); + return buffer.toString("base64url"); +} + +export function base64UrlDecodeUtf8(input: string): string { + return Buffer.from(input, "base64url").toString("utf8"); +} + +export function signPayload(payload: string, secret: Uint8Array): string { + return Crypto.createHmac("sha256", Buffer.from(secret)).update(payload).digest("base64url"); +} + +export function timingSafeEqualBase64Url(left: string, right: string): boolean { + const leftBuffer = Buffer.from(left, "base64url"); + const rightBuffer = Buffer.from(right, "base64url"); + if (leftBuffer.length !== rightBuffer.length) { + return false; + } + return Crypto.timingSafeEqual(leftBuffer, rightBuffer); +} + +function normalizeNonEmptyString(value: string | null | undefined): string | undefined { + if (typeof value !== "string") { + return undefined; + } + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : undefined; +} + +function normalizeIpAddress(value: string | null | undefined): string | undefined { + const normalized = normalizeNonEmptyString(value); + if (!normalized) { + return undefined; + } + return normalized.startsWith("::ffff:") ? normalized.slice("::ffff:".length) : normalized; +} + +function inferDeviceType(userAgent: string | undefined): AuthClientMetadataDeviceType { + if (!userAgent) { + return "unknown"; + } + + const normalized = userAgent.toLowerCase(); + if (/bot|crawler|spider|slurp|curl|wget/.test(normalized)) { + return "bot"; + } + if (/ipad|tablet/.test(normalized)) { + return "tablet"; + } + if (/iphone|android.+mobile|mobile/.test(normalized)) { + return "mobile"; + } + return "desktop"; +} + +function inferBrowser(userAgent: string | undefined): string | undefined { + if (!userAgent) { + return undefined; + } + const normalized = userAgent.toLowerCase(); + if (/edg\//.test(normalized)) return "Edge"; + if (/opr\//.test(normalized)) return "Opera"; + if (/firefox\//.test(normalized)) return "Firefox"; + if (/electron\//.test(normalized)) return "Electron"; + if (/chrome\//.test(normalized) || /crios\//.test(normalized)) return "Chrome"; + if (/safari\//.test(normalized) && !/chrome\//.test(normalized)) return "Safari"; + return undefined; +} + +function inferOs(userAgent: string | undefined): string | undefined { + if (!userAgent) { + return undefined; + } + const normalized = userAgent.toLowerCase(); + if (/iphone|ipad|ipod/.test(normalized)) return "iOS"; + if (/android/.test(normalized)) return "Android"; + if (/mac os x|macintosh/.test(normalized)) return "macOS"; + if (/windows nt/.test(normalized)) return "Windows"; + if (/linux/.test(normalized)) return "Linux"; + return undefined; +} + +function readRemoteAddressFromSource(source: unknown): string | undefined { + if (!source || typeof source !== "object") { + return undefined; + } + + const candidate = source as { + readonly remoteAddress?: string | null; + readonly socket?: { + readonly remoteAddress?: string | null; + }; + }; + + return normalizeIpAddress(candidate.socket?.remoteAddress ?? candidate.remoteAddress); +} + +export function deriveAuthClientMetadata(input: { + readonly request: HttpServerRequest.HttpServerRequest; + readonly label?: string; +}): AuthClientMetadata { + const userAgent = normalizeNonEmptyString(input.request.headers["user-agent"]); + const ipAddress = readRemoteAddressFromSource(input.request.source); + const os = inferOs(userAgent); + const browser = inferBrowser(userAgent); + return { + ...(input.label ? { label: input.label } : {}), + ...(ipAddress ? { ipAddress } : {}), + ...(userAgent ? { userAgent } : {}), + deviceType: inferDeviceType(userAgent), + ...(os ? { os } : {}), + ...(browser ? { browser } : {}), + }; +} diff --git a/apps/server/src/bin.ts b/apps/server/src/bin.ts new file mode 100644 index 0000000000..063d43326c --- /dev/null +++ b/apps/server/src/bin.ts @@ -0,0 +1,17 @@ +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { Command } from "effect/unstable/cli"; + +import { NetService } from "@t3tools/shared/Net"; +import { cli } from "./cli"; +import { version } from "../package.json" with { type: "json" }; + +const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer); + +Command.run(cli, { version }).pipe( + Effect.scoped, + Effect.provide(CliRuntimeLayer), + NodeRuntime.runMain, +); diff --git a/apps/server/src/checkpointing/Errors.ts b/apps/server/src/checkpointing/Errors.ts index 782d0918e6..cb873559c1 100644 --- a/apps/server/src/checkpointing/Errors.ts +++ b/apps/server/src/checkpointing/Errors.ts @@ -1,6 +1,6 @@ import { Schema } from "effect"; import type { ProjectionRepositoryError } from "../persistence/Errors.ts"; -import { GitCommandError } from "../git/Errors.ts"; +import { GitCommandError } from "@t3tools/contracts"; /** * CheckpointUnavailableError - Expected checkpoint does not exist. diff --git a/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts b/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts index 9fb2500ce4..21cbe1509a 100644 --- a/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts +++ b/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts @@ -1,83 +1,38 @@ -import { - CheckpointRef, - DEFAULT_PROVIDER_INTERACTION_MODE, - ProjectId, - ThreadId, - TurnId, - type OrchestrationReadModel, -} from "@t3tools/contracts"; -import { Effect, Layer } from "effect"; +import { CheckpointRef, ProjectId, ThreadId, TurnId } from "@t3tools/contracts"; +import { Effect, Layer, Option } from "effect"; import { describe, expect, it } from "vitest"; -import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts"; +import { + ProjectionSnapshotQuery, + type ProjectionThreadCheckpointContext, +} from "../../orchestration/Services/ProjectionSnapshotQuery.ts"; import { checkpointRefForThreadTurn } from "../Utils.ts"; import { CheckpointDiffQueryLive } from "./CheckpointDiffQuery.ts"; import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts"; import { CheckpointDiffQuery } from "../Services/CheckpointDiffQuery.ts"; -function makeSnapshot(input: { +function makeThreadCheckpointContext(input: { readonly projectId: ProjectId; readonly threadId: ThreadId; readonly workspaceRoot: string; readonly worktreePath: string | null; readonly checkpointTurnCount: number; readonly checkpointRef: CheckpointRef; -}): OrchestrationReadModel { +}): ProjectionThreadCheckpointContext { return { - snapshotSequence: 0, - updatedAt: "2026-01-01T00:00:00.000Z", - projects: [ + threadId: input.threadId, + projectId: input.projectId, + workspaceRoot: input.workspaceRoot, + worktreePath: input.worktreePath, + checkpoints: [ { - id: input.projectId, - title: "Project", - workspaceRoot: input.workspaceRoot, - defaultModelSelection: null, - scripts: [], - createdAt: "2026-01-01T00:00:00.000Z", - updatedAt: "2026-01-01T00:00:00.000Z", - deletedAt: null, - }, - ], - threads: [ - { - id: input.threadId, - projectId: input.projectId, - title: "Thread", - modelSelection: { - provider: "codex", - model: "gpt-5-codex", - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "full-access", - branch: null, - worktreePath: input.worktreePath, - latestTurn: { - turnId: TurnId.makeUnsafe("turn-1"), - state: "completed", - requestedAt: "2026-01-01T00:00:00.000Z", - startedAt: "2026-01-01T00:00:00.000Z", - completedAt: "2026-01-01T00:00:00.000Z", - assistantMessageId: null, - }, - createdAt: "2026-01-01T00:00:00.000Z", - updatedAt: "2026-01-01T00:00:00.000Z", - archivedAt: null, - deletedAt: null, - messages: [], - activities: [], - proposedPlans: [], - checkpoints: [ - { - turnId: TurnId.makeUnsafe("turn-1"), - checkpointTurnCount: input.checkpointTurnCount, - checkpointRef: input.checkpointRef, - status: "ready", - files: [], - assistantMessageId: null, - completedAt: "2026-01-01T00:00:00.000Z", - }, - ], - session: null, + turnId: TurnId.make("turn-1"), + checkpointTurnCount: input.checkpointTurnCount, + checkpointRef: input.checkpointRef, + status: "ready", + files: [], + assistantMessageId: null, + completedAt: "2026-01-01T00:00:00.000Z", }, ], }; @@ -85,8 +40,8 @@ function makeSnapshot(input: { describe("CheckpointDiffQueryLive", () => { it("computes diffs using canonical turn-0 checkpoint refs", async () => { - const projectId = ProjectId.makeUnsafe("project-1"); - const threadId = ThreadId.makeUnsafe("thread-1"); + const projectId = ProjectId.make("project-1"); + const threadId = ThreadId.make("thread-1"); const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1); const hasCheckpointRefCalls: Array = []; const diffCheckpointsCalls: Array<{ @@ -95,7 +50,7 @@ describe("CheckpointDiffQueryLive", () => { readonly cwd: string; }> = []; - const snapshot = makeSnapshot({ + const threadCheckpointContext = makeThreadCheckpointContext({ projectId, threadId, workspaceRoot: "/tmp/workspace", @@ -125,7 +80,12 @@ describe("CheckpointDiffQueryLive", () => { Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)), Layer.provideMerge( Layer.succeed(ProjectionSnapshotQuery, { - getSnapshot: () => Effect.succeed(snapshot), + getSnapshot: () => + Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"), + getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }), + getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()), + getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()), + getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)), }), ), ); @@ -159,7 +119,7 @@ describe("CheckpointDiffQueryLive", () => { }); it("fails when the thread is missing from the snapshot", async () => { - const threadId = ThreadId.makeUnsafe("thread-missing"); + const threadId = ThreadId.make("thread-missing"); const checkpointStore: CheckpointStoreShape = { isGitRepository: () => Effect.succeed(true), @@ -175,12 +135,11 @@ describe("CheckpointDiffQueryLive", () => { Layer.provideMerge( Layer.succeed(ProjectionSnapshotQuery, { getSnapshot: () => - Effect.succeed({ - snapshotSequence: 0, - projects: [], - threads: [], - updatedAt: "2026-01-01T00:00:00.000Z", - } satisfies OrchestrationReadModel), + Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"), + getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }), + getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()), + getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()), + getThreadCheckpointContext: () => Effect.succeed(Option.none()), }), ), ); diff --git a/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts b/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts index 5cf26c86da..1c2edee469 100644 --- a/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts +++ b/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts @@ -4,11 +4,11 @@ import { type OrchestrationGetFullThreadDiffResult, type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType, } from "@t3tools/contracts"; -import { Effect, Layer, Schema } from "effect"; +import { Effect, Layer, Option, Schema } from "effect"; import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts"; import { CheckpointInvariantError, CheckpointUnavailableError } from "../Errors.ts"; -import { checkpointRefForThreadTurn, resolveThreadWorkspaceCwd } from "../Utils.ts"; +import { checkpointRefForThreadTurn } from "../Utils.ts"; import { CheckpointStore } from "../Services/CheckpointStore.ts"; import { CheckpointDiffQuery, @@ -21,8 +21,8 @@ const make = Effect.gen(function* () { const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; const checkpointStore = yield* CheckpointStore; - const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = (input) => - Effect.gen(function* () { + const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")( + function* (input) { const operation = "CheckpointDiffQuery.getTurnDiff"; if (input.fromTurnCount === input.toTurnCount) { @@ -41,16 +41,17 @@ const make = Effect.gen(function* () { return emptyDiff; } - const snapshot = yield* projectionSnapshotQuery.getSnapshot(); - const thread = snapshot.threads.find((entry) => entry.id === input.threadId); - if (!thread) { + const threadContext = yield* projectionSnapshotQuery.getThreadCheckpointContext( + input.threadId, + ); + if (Option.isNone(threadContext)) { return yield* new CheckpointInvariantError({ operation, detail: `Thread '${input.threadId}' not found.`, }); } - const maxTurnCount = thread.checkpoints.reduce( + const maxTurnCount = threadContext.value.checkpoints.reduce( (max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount), 0, ); @@ -62,10 +63,7 @@ const make = Effect.gen(function* () { }); } - const workspaceCwd = resolveThreadWorkspaceCwd({ - thread, - projects: snapshot.projects, - }); + const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot; if (!workspaceCwd) { return yield* new CheckpointInvariantError({ operation, @@ -76,7 +74,7 @@ const make = Effect.gen(function* () { const fromCheckpointRef = input.fromTurnCount === 0 ? checkpointRefForThreadTurn(input.threadId, 0) - : thread.checkpoints.find( + : threadContext.value.checkpoints.find( (checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount, )?.checkpointRef; if (!fromCheckpointRef) { @@ -87,7 +85,7 @@ const make = Effect.gen(function* () { }); } - const toCheckpointRef = thread.checkpoints.find( + const toCheckpointRef = threadContext.value.checkpoints.find( (checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount, )?.checkpointRef; if (!toCheckpointRef) { @@ -149,7 +147,8 @@ const make = Effect.gen(function* () { } return turnDiff; - }); + }, + ); const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = ( input: OrchestrationGetFullThreadDiffInput, diff --git a/apps/server/src/checkpointing/Layers/CheckpointStore.test.ts b/apps/server/src/checkpointing/Layers/CheckpointStore.test.ts index c430dbbde0..fe377eb1ec 100644 --- a/apps/server/src/checkpointing/Layers/CheckpointStore.test.ts +++ b/apps/server/src/checkpointing/Layers/CheckpointStore.test.ts @@ -10,7 +10,7 @@ import { CheckpointStoreLive } from "./CheckpointStore.ts"; import { CheckpointStore } from "../Services/CheckpointStore.ts"; import { GitCoreLive } from "../../git/Layers/GitCore.ts"; import { GitCore } from "../../git/Services/GitCore.ts"; -import { GitCommandError } from "../../git/Errors.ts"; +import { GitCommandError } from "@t3tools/contracts"; import { ServerConfig } from "../../config.ts"; import { ThreadId } from "@t3tools/contracts"; @@ -80,7 +80,7 @@ function initRepoWithCommit( }); } -function buildLargeText(lineCount = 20_000): string { +function buildLargeText(lineCount = 5_000): string { return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`) .join("\n") .concat("\n"); @@ -93,7 +93,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => { const tmp = yield* makeTmpDir(); yield* initRepoWithCommit(tmp); const checkpointStore = yield* CheckpointStore; - const threadId = ThreadId.makeUnsafe("thread-checkpoint-store"); + const threadId = ThreadId.make("thread-checkpoint-store"); const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0); const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1); @@ -115,7 +115,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => { expect(diff).toContain("diff --git"); expect(diff).not.toContain("[truncated]"); - expect(diff).toContain("+line 19999"); + expect(diff).toContain("+line 04999"); }), ); }); diff --git a/apps/server/src/checkpointing/Layers/CheckpointStore.ts b/apps/server/src/checkpointing/Layers/CheckpointStore.ts index b20204780c..184ec96323 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"; @@ -86,139 +86,140 @@ const makeCheckpointStore = Effect.gen(function* () { Effect.catch(() => Effect.succeed(false)), ); - const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = (input) => - Effect.gen(function* () { - const operation = "CheckpointStore.captureCheckpoint"; + const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn( + "captureCheckpoint", + )(function* (input) { + const operation = "CheckpointStore.captureCheckpoint"; - yield* Effect.acquireUseRelease( - fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }), - (tempDir) => - Effect.gen(function* () { - const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`); - const commitEnv: NodeJS.ProcessEnv = { - ...process.env, - GIT_INDEX_FILE: tempIndexPath, - GIT_AUTHOR_NAME: "T3 Code", - GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com", - GIT_COMMITTER_NAME: "T3 Code", - GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com", - }; + yield* Effect.acquireUseRelease( + fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }), + Effect.fn("captureCheckpoint.withTempDirectory")(function* (tempDir) { + const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`); + const commitEnv: NodeJS.ProcessEnv = { + ...process.env, + GIT_INDEX_FILE: tempIndexPath, + GIT_AUTHOR_NAME: "T3 Code", + GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com", + GIT_COMMITTER_NAME: "T3 Code", + GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com", + }; - const headExists = yield* hasHeadCommit(input.cwd); - if (headExists) { - yield* git.execute({ - operation, - cwd: input.cwd, - args: ["read-tree", "HEAD"], - env: commitEnv, - }); - } + const headExists = yield* hasHeadCommit(input.cwd); + if (headExists) { + yield* git.execute({ + operation, + cwd: input.cwd, + args: ["read-tree", "HEAD"], + env: commitEnv, + }); + } - yield* git.execute({ - operation, - cwd: input.cwd, - args: ["add", "-A", "--", "."], - env: commitEnv, - }); + yield* git.execute({ + operation, + cwd: input.cwd, + args: ["add", "-A", "--", "."], + env: commitEnv, + }); - const writeTreeResult = yield* git.execute({ - operation, - cwd: input.cwd, - args: ["write-tree"], - env: commitEnv, - }); - const treeOid = writeTreeResult.stdout.trim(); - if (treeOid.length === 0) { - return yield* new GitCommandError({ - operation, - command: "git write-tree", - cwd: input.cwd, - detail: "git write-tree returned an empty tree oid.", - }); - } + const writeTreeResult = yield* git.execute({ + operation, + cwd: input.cwd, + args: ["write-tree"], + env: commitEnv, + }); + const treeOid = writeTreeResult.stdout.trim(); + if (treeOid.length === 0) { + return yield* new GitCommandError({ + operation, + command: "git write-tree", + cwd: input.cwd, + detail: "git write-tree returned an empty tree oid.", + }); + } - const message = `t3 checkpoint ref=${input.checkpointRef}`; - const commitTreeResult = yield* git.execute({ - operation, - cwd: input.cwd, - args: ["commit-tree", treeOid, "-m", message], - env: commitEnv, - }); - const commitOid = commitTreeResult.stdout.trim(); - if (commitOid.length === 0) { - return yield* new GitCommandError({ - operation, - command: "git commit-tree", - cwd: input.cwd, - detail: "git commit-tree returned an empty commit oid.", - }); - } + const message = `t3 checkpoint ref=${input.checkpointRef}`; + const commitTreeResult = yield* git.execute({ + operation, + cwd: input.cwd, + args: ["commit-tree", treeOid, "-m", message], + env: commitEnv, + }); + const commitOid = commitTreeResult.stdout.trim(); + if (commitOid.length === 0) { + return yield* new GitCommandError({ + operation, + command: "git commit-tree", + cwd: input.cwd, + detail: "git commit-tree returned an empty commit oid.", + }); + } - yield* git.execute({ - operation, - cwd: input.cwd, - args: ["update-ref", input.checkpointRef, commitOid], - }); - }), - (tempDir) => fs.remove(tempDir, { recursive: true }), - ).pipe( - Effect.catchTags({ - PlatformError: (error) => - Effect.fail( - new CheckpointInvariantError({ - operation: "CheckpointStore.captureCheckpoint", - detail: "Failed to capture checkpoint.", - cause: error, - }), - ), - }), - ); - }); + yield* git.execute({ + operation, + cwd: input.cwd, + args: ["update-ref", input.checkpointRef, commitOid], + }); + }), + (tempDir) => fs.remove(tempDir, { recursive: true }), + ).pipe( + Effect.catchTags({ + PlatformError: (error) => + Effect.fail( + new CheckpointInvariantError({ + operation: "CheckpointStore.captureCheckpoint", + detail: "Failed to capture checkpoint.", + cause: error, + }), + ), + }), + ); + }); const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) => resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe( Effect.map((commit) => commit !== null), ); - const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = (input) => - Effect.gen(function* () { - const operation = "CheckpointStore.restoreCheckpoint"; + const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = Effect.fn( + "restoreCheckpoint", + )(function* (input) { + const operation = "CheckpointStore.restoreCheckpoint"; - let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef); + let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef); - if (!commitOid && input.fallbackToHead === true) { - commitOid = yield* resolveHeadCommit(input.cwd); - } + if (!commitOid && input.fallbackToHead === true) { + commitOid = yield* resolveHeadCommit(input.cwd); + } - if (!commitOid) { - return false; - } + if (!commitOid) { + return false; + } - yield* git.execute({ - operation, - cwd: input.cwd, - args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."], - }); - yield* git.execute({ - operation, - cwd: input.cwd, - args: ["clean", "-fd", "--", "."], - }); - - const headExists = yield* hasHeadCommit(input.cwd); - if (headExists) { - yield* git.execute({ - operation, - cwd: input.cwd, - args: ["reset", "--quiet", "--", "."], - }); - } - - return true; + yield* git.execute({ + operation, + cwd: input.cwd, + args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."], + }); + yield* git.execute({ + operation, + cwd: input.cwd, + args: ["clean", "-fd", "--", "."], }); - const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = (input) => - Effect.gen(function* () { + const headExists = yield* hasHeadCommit(input.cwd); + if (headExists) { + yield* git.execute({ + operation, + cwd: input.cwd, + args: ["reset", "--quiet", "--", "."], + }); + } + + return true; + }); + + const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = Effect.fn("diffCheckpoints")( + function* (input) { const operation = "CheckpointStore.diffCheckpoints"; let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef); @@ -247,24 +248,26 @@ const makeCheckpointStore = Effect.gen(function* () { }); return result.stdout; - }); + }, + ); - const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = (input) => - Effect.gen(function* () { - const operation = "CheckpointStore.deleteCheckpointRefs"; + const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = Effect.fn( + "deleteCheckpointRefs", + )(function* (input) { + const operation = "CheckpointStore.deleteCheckpointRefs"; - yield* Effect.forEach( - input.checkpointRefs, - (checkpointRef) => - git.execute({ - operation, - cwd: input.cwd, - args: ["update-ref", "-d", checkpointRef], - allowNonZeroExit: true, - }), - { discard: true }, - ); - }); + yield* Effect.forEach( + input.checkpointRefs, + (checkpointRef) => + git.execute({ + operation, + cwd: input.cwd, + args: ["update-ref", "-d", checkpointRef], + allowNonZeroExit: true, + }), + { discard: true }, + ); + }); return { isGitRepository, diff --git a/apps/server/src/checkpointing/Services/CheckpointDiffQuery.ts b/apps/server/src/checkpointing/Services/CheckpointDiffQuery.ts index 2204294a43..d865256ac5 100644 --- a/apps/server/src/checkpointing/Services/CheckpointDiffQuery.ts +++ b/apps/server/src/checkpointing/Services/CheckpointDiffQuery.ts @@ -12,7 +12,7 @@ import type { OrchestrationGetTurnDiffInput, OrchestrationGetTurnDiffResult, } from "@t3tools/contracts"; -import { ServiceMap } from "effect"; +import { Context } from "effect"; import type { Effect } from "effect"; import type { CheckpointServiceError } from "../Errors.ts"; @@ -43,7 +43,7 @@ export interface CheckpointDiffQueryShape { /** * CheckpointDiffQuery - Service tag for checkpoint diff queries. */ -export class CheckpointDiffQuery extends ServiceMap.Service< +export class CheckpointDiffQuery extends Context.Service< CheckpointDiffQuery, CheckpointDiffQueryShape >()("t3/checkpointing/Services/CheckpointDiffQuery") {} diff --git a/apps/server/src/checkpointing/Services/CheckpointStore.ts b/apps/server/src/checkpointing/Services/CheckpointStore.ts index 284198c145..d9a43fa4e9 100644 --- a/apps/server/src/checkpointing/Services/CheckpointStore.ts +++ b/apps/server/src/checkpointing/Services/CheckpointStore.ts @@ -5,12 +5,12 @@ * workspace thread timeline. It does not store user-facing checkpoint metadata * and does not coordinate provider conversation rollback. * - * Uses Effect `ServiceMap.Service` for dependency injection and exposes typed + * Uses Effect `Context.Service` for dependency injection and exposes typed * domain errors for checkpoint storage operations. * * @module CheckpointStore */ -import { ServiceMap } from "effect"; +import { Context } from "effect"; import type { Effect } from "effect"; import type { CheckpointStoreError } from "../Errors.ts"; @@ -95,6 +95,6 @@ export interface CheckpointStoreShape { /** * CheckpointStore - Service tag for checkpoint persistence and restore operations. */ -export class CheckpointStore extends ServiceMap.Service()( +export class CheckpointStore extends Context.Service()( "t3/checkpointing/Services/CheckpointStore", ) {} diff --git a/apps/server/src/checkpointing/Utils.ts b/apps/server/src/checkpointing/Utils.ts index 3cd92f8510..c709aa3735 100644 --- a/apps/server/src/checkpointing/Utils.ts +++ b/apps/server/src/checkpointing/Utils.ts @@ -4,7 +4,7 @@ import { CheckpointRef, ProjectId, type ThreadId } from "@t3tools/contracts"; export const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints"; export function checkpointRefForThreadTurn(threadId: ThreadId, turnCount: number): CheckpointRef { - return CheckpointRef.makeUnsafe( + return CheckpointRef.make( `${CHECKPOINT_REFS_PREFIX}/${Encoding.encodeBase64Url(threadId)}/turn/${turnCount}`, ); } diff --git a/apps/server/src/cli-config.test.ts b/apps/server/src/cli-config.test.ts new file mode 100644 index 0000000000..6fa6e0c96b --- /dev/null +++ b/apps/server/src/cli-config.test.ts @@ -0,0 +1,528 @@ +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 defaultObservabilityConfig = { + traceMinLevel: "Info", + traceTimingEnabled: true, + traceBatchWindowMs: 200, + traceMaxBytes: 10 * 1024 * 1024, + traceMaxFiles: 10, + otlpTracesUrl: undefined, + otlpMetricsUrl: undefined, + otlpExportIntervalMs: 10_000, + otlpServiceName: "t3-server", + } as const; + + 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(), + cwd: Option.none(), + devUrl: Option.none(), + noBrowser: 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_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false", + T3CODE_LOG_WS_EVENTS: "true", + }, + }), + ), + NetService.layer, + ), + ), + ); + + expect(resolved).toEqual({ + logLevel: "Warn", + ...defaultObservabilityConfig, + 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, + startupPresentation: "browser", + desktopBootstrapToken: undefined, + 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), + cwd: Option.none(), + devUrl: Option.some(new URL("http://127.0.0.1:4173")), + noBrowser: Option.some(true), + 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_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false", + T3CODE_LOG_WS_EVENTS: "false", + }, + }), + ), + NetService.layer, + ), + ), + ); + + expect(resolved).toEqual({ + logLevel: "Debug", + ...defaultObservabilityConfig, + 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, + startupPresentation: "browser", + desktopBootstrapToken: undefined, + autoBootstrapProjectFromCwd: true, + logWebSocketEvents: true, + }); + }), + ); + + it.effect("preserves explicit false CLI boolean flags over env and bootstrap values", () => + Effect.gen(function* () { + const { join } = yield* Path.Path; + const baseDir = join(os.tmpdir(), "t3-cli-config-false-flags"); + const fd = yield* openBootstrapFd({ + noBrowser: true, + autoBootstrapProjectFromCwd: true, + logWebSocketEvents: true, + }); + 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), + cwd: Option.none(), + devUrl: Option.some(new URL("http://127.0.0.1:4173")), + noBrowser: Option.some(false), + bootstrapFd: Option.none(), + autoBootstrapProjectFromCwd: Option.some(false), + logWebSocketEvents: Option.some(false), + }, + Option.none(), + ).pipe( + Effect.provide( + Layer.mergeAll( + ConfigProvider.layer( + ConfigProvider.fromEnv({ + env: { + T3CODE_BOOTSTRAP_FD: String(fd), + T3CODE_NO_BROWSER: "true", + T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true", + T3CODE_LOG_WS_EVENTS: "true", + }, + }), + ), + NetService.layer, + ), + ), + ); + + expect(resolved).toEqual({ + logLevel: "Info", + ...defaultObservabilityConfig, + 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: false, + startupPresentation: "browser", + desktopBootstrapToken: undefined, + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: false, + }); + }), + ); + + 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, + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: true, + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + }); + 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(), + cwd: Option.none(), + devUrl: Option.none(), + noBrowser: 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", + ...defaultObservabilityConfig, + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + 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, + startupPresentation: "browser", + desktopBootstrapToken: undefined, + 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 customCwd = path.join(baseDir, "nested", "project"); + + const resolved = yield* resolveServerConfig( + { + mode: Option.some("desktop"), + port: Option.some(4888), + host: Option.none(), + baseDir: Option.some(baseDir), + cwd: Option.some(customCwd), + devUrl: Option.some(new URL("http://127.0.0.1:5173")), + noBrowser: 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 [ + customCwd, + resolved.stateDir, + resolved.logsDir, + resolved.providerLogsDir, + resolved.terminalLogsDir, + resolved.attachmentsDir, + resolved.worktreesDir, + path.dirname(resolved.serverLogPath), + path.dirname(resolved.serverTracePath), + ]) { + expect(yield* fs.exists(directory)).toBe(true); + } + expect(resolved.cwd).toBe(path.resolve(customCwd)); + }), + ); + + 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, + 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(), + cwd: Option.none(), + devUrl: Option.some(new URL("http://127.0.0.1:4173")), + noBrowser: Option.none(), + 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", + ...defaultObservabilityConfig, + 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, + startupPresentation: "browser", + desktopBootstrapToken: undefined, + autoBootstrapProjectFromCwd: true, + logWebSocketEvents: true, + }); + }), + ); + + it.effect("falls back to persisted observability settings when env vars are absent", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-settings-" }); + const derivedPaths = yield* deriveServerPaths(baseDir, undefined); + yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }); + yield* fs.writeFileString( + derivedPaths.settingsPath, + `${JSON.stringify({ + observability: { + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + }, + })}\n`, + ); + + const resolved = yield* resolveServerConfig( + { + mode: Option.some("desktop"), + port: Option.some(4888), + host: Option.none(), + baseDir: Option.some(baseDir), + cwd: Option.none(), + devUrl: Option.none(), + noBrowser: 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, + ), + ), + ); + + expect(resolved.otlpTracesUrl).toBe("http://localhost:4318/v1/traces"); + expect(resolved.otlpMetricsUrl).toBe("http://localhost:4318/v1/metrics"); + expect(resolved).toEqual({ + logLevel: "Info", + ...defaultObservabilityConfig, + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + mode: "desktop", + port: 4888, + cwd: process.cwd(), + baseDir, + ...derivedPaths, + host: "127.0.0.1", + staticDir: resolved.staticDir, + devUrl: undefined, + noBrowser: true, + startupPresentation: "browser", + desktopBootstrapToken: undefined, + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: false, + }); + }), + ); + + it.effect("forces noBrowser and disables auto-bootstrap for headless startup presentation", () => + Effect.gen(function* () { + const { join } = yield* Path.Path; + const baseDir = join(os.tmpdir(), "t3-cli-config-headless-base"); + const derivedPaths = yield* deriveServerPaths(baseDir, undefined); + + const resolved = yield* resolveServerConfig( + { + mode: Option.some("web"), + port: Option.some(3773), + host: Option.none(), + baseDir: Option.some(baseDir), + cwd: Option.none(), + devUrl: Option.none(), + noBrowser: Option.none(), + bootstrapFd: Option.none(), + autoBootstrapProjectFromCwd: Option.none(), + logWebSocketEvents: Option.none(), + }, + Option.none(), + { + startupPresentation: "headless", + }, + ).pipe( + Effect.provide( + Layer.mergeAll( + ConfigProvider.layer( + ConfigProvider.fromEnv({ + env: { + T3CODE_NO_BROWSER: "false", + T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true", + }, + }), + ), + NetService.layer, + ), + ), + ); + + expect(resolved).toEqual({ + logLevel: "Info", + ...defaultObservabilityConfig, + mode: "web", + port: 3773, + cwd: process.cwd(), + baseDir, + ...derivedPaths, + host: undefined, + staticDir: resolved.staticDir, + devUrl: undefined, + noBrowser: true, + startupPresentation: "headless", + desktopBootstrapToken: undefined, + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: false, + }); + }), + ); +}); diff --git a/apps/server/src/cli.test.ts b/apps/server/src/cli.test.ts new file mode 100644 index 0000000000..7ebde01067 --- /dev/null +++ b/apps/server/src/cli.test.ts @@ -0,0 +1,356 @@ +import * as NodeHttp from "node:http"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; +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 HttpRouter from "effect/unstable/http/HttpRouter"; +import * as HttpServer from "effect/unstable/http/HttpServer"; +import * as CliError from "effect/unstable/cli/CliError"; +import * as TestConsole from "effect/testing/TestConsole"; +import { Command } from "effect/unstable/cli"; + +import { cli } from "./cli.ts"; +import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts"; +import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts"; +import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts"; +import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts"; +import { + orchestrationDispatchRouteLayer, + orchestrationSnapshotRouteLayer, +} from "./orchestration/http.ts"; +import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts"; +import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts"; +import { + makePersistedServerRuntimeState, + persistServerRuntimeState, +} from "./serverRuntimeState.ts"; +import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts"; +import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts"; +import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts"; + +const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer); + +const runCli = (args: ReadonlyArray) => Command.runWith(cli, { version: "0.0.0" })(args); +const runCliWithRuntime = (args: ReadonlyArray) => + runCli(args).pipe(Effect.provide(CliRuntimeLayer)); + +const captureStdout = (effect: Effect.Effect) => + Effect.gen(function* () { + const result = yield* effect; + const output = + (yield* TestConsole.logLines).findLast((line): line is string => typeof line === "string") ?? + ""; + return { result, output }; + }).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer))); + +const makeCliTestServerConfig = (baseDir: string) => + Effect.gen(function* () { + const derivedPaths = yield* deriveServerPaths(baseDir, undefined); + return { + logLevel: "Info", + traceMinLevel: "Info", + traceTimingEnabled: true, + traceBatchWindowMs: 200, + traceMaxBytes: 10 * 1024 * 1024, + traceMaxFiles: 10, + otlpTracesUrl: undefined, + otlpMetricsUrl: undefined, + otlpExportIntervalMs: 10_000, + otlpServiceName: "t3-server", + mode: "web", + port: 0, + host: "127.0.0.1", + cwd: process.cwd(), + baseDir, + ...derivedPaths, + staticDir: undefined, + devUrl: undefined, + noBrowser: true, + startupPresentation: "browser", + desktopBootstrapToken: undefined, + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: false, + } satisfies ServerConfigShape; + }); + +const makeProjectPersistenceLayer = (config: ServerConfigShape) => + Layer.mergeAll( + OrchestrationLayerLive.pipe( + Layer.provideMerge(RepositoryIdentityResolverLive), + Layer.provideMerge(SqlitePersistenceLayerLive), + ), + WorkspacePathsLive, + ).pipe( + Layer.provideMerge(NodeServices.layer), + Layer.provide(Layer.succeed(ServerConfig, config)), + ); + +const readPersistedSnapshot = (baseDir: string) => + Effect.gen(function* () { + const config = yield* makeCliTestServerConfig(baseDir); + return yield* Effect.gen(function* () { + const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; + return yield* projectionSnapshotQuery.getSnapshot(); + }).pipe(Effect.provide(makeProjectPersistenceLayer(config))); + }); + +const withLiveProjectCliServer = (baseDir: string, run: () => Effect.Effect) => + Effect.gen(function* () { + const config = yield* makeCliTestServerConfig(baseDir); + const routesLayer = Layer.mergeAll( + orchestrationSnapshotRouteLayer, + orchestrationDispatchRouteLayer, + ); + const appLayer = HttpRouter.serve(routesLayer, { + disableListenLog: true, + disableLogger: true, + }).pipe( + Layer.provideMerge( + ServerAuthLive.pipe( + Layer.provideMerge(SqlitePersistenceLayerLive), + Layer.provide(ServerSecretStoreLive), + ), + ), + Layer.provideMerge(makeProjectPersistenceLayer(config)), + Layer.provideMerge( + NodeHttpServer.layer(NodeHttp.createServer, { + host: "127.0.0.1", + port: 0, + }), + ), + Layer.provideMerge(NodeServices.layer), + Layer.provide(Layer.succeed(ServerConfig, config)), + ); + + return yield* Effect.scoped( + Effect.gen(function* () { + const server = yield* HttpServer.HttpServer; + const address = server.address; + if (typeof address === "string" || !("port" in address)) { + assert.fail(`Expected TCP address, got ${address}`); + } + yield* persistServerRuntimeState({ + path: config.serverRuntimeStatePath, + state: makePersistedServerRuntimeState({ + config, + port: address.port, + }), + }); + return yield* run(); + }).pipe(Effect.provide(Layer.mergeAll(appLayer, NodeServices.layer))), + ); + }); + +it.layer(NodeServices.layer)("cli log-level parsing", (it) => { + it.effect("accepts the built-in lowercase log-level flag values", () => + runCliWithRuntime(["--log-level", "debug", "--version"]), + ); + + it.effect("accepts canonical --no- boolean negation", () => + runCliWithRuntime(["--no-log-websocket-events", "--version"]), + ); + + it.effect("rejects invalid log-level casing before launching the server", () => + Effect.gen(function* () { + const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(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"); + }), + ); + + it.effect("executes auth pairing subcommands and redacts secrets from list output", () => + Effect.gen(function* () { + const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-pairing-test-")); + + const createdOutput = yield* captureStdout( + runCli(["auth", "pairing", "create", "--base-dir", baseDir, "--json"]), + ); + const created = JSON.parse(createdOutput.output) as { + readonly id: string; + readonly credential: string; + }; + const listedOutput = yield* captureStdout( + runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]), + ); + const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{ + readonly id: string; + readonly credential?: string; + }>; + + assert.equal(typeof created.id, "string"); + assert.equal(typeof created.credential, "string"); + assert.equal(created.credential.length > 0, true); + assert.equal(listed.length, 1); + assert.equal(listed[0]?.id, created.id); + assert.equal("credential" in (listed[0] ?? {}), false); + }), + ); + + it.effect("executes auth session subcommands and redacts secrets from list output", () => + Effect.gen(function* () { + const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-session-test-")); + + const issuedOutput = yield* captureStdout( + runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"]), + ); + const issued = JSON.parse(issuedOutput.output) as { + readonly sessionId: string; + readonly token: string; + readonly role: string; + }; + const listedOutput = yield* captureStdout( + runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]), + ); + const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{ + readonly sessionId: string; + readonly token?: string; + readonly role: string; + }>; + + assert.equal(typeof issued.sessionId, "string"); + assert.equal(typeof issued.token, "string"); + assert.equal(issued.role, "owner"); + assert.equal(listed.length, 1); + assert.equal(listed[0]?.sessionId, issued.sessionId); + assert.equal(listed[0]?.role, "owner"); + assert.equal("token" in (listed[0] ?? {}), false); + }), + ); + + it.effect("rejects invalid ttl values before running auth commands", () => + Effect.gen(function* () { + const error = yield* runCliWithRuntime(["auth", "pairing", "create", "--ttl", "soon"]).pipe( + Effect.flip, + ); + + if (!CliError.isCliError(error)) { + assert.fail(`Expected CliError, got ${String(error)}`); + } + if (error._tag !== "ShowHelp") { + assert.fail(`Expected ShowHelp, got ${error._tag}`); + } + assert.deepEqual(error.commandPath, ["t3", "auth", "pairing", "create"]); + const ttlError = error.errors[0] as CliError.CliError | undefined; + if (!ttlError || ttlError._tag !== "InvalidValue") { + assert.fail(`Expected InvalidValue, got ${String(ttlError?._tag)}`); + } + assert.equal(ttlError.option, "ttl"); + assert.equal(ttlError.value, "soon"); + assert.isTrue(ttlError.message.includes("Invalid duration")); + assert.isTrue(ttlError.message.includes("5m, 1h, 30d, or 15 minutes")); + }), + ); + + it.effect("adds, renames, and removes projects offline through the orchestration engine", () => + Effect.gen(function* () { + const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-projects-offline-test-")); + const workspaceRoot = mkdtempSync(join(tmpdir(), "t3-cli-projects-workspace-")); + + yield* runCliWithRuntime([ + "project", + "add", + workspaceRoot, + "--title", + "Alpha", + "--base-dir", + baseDir, + ]); + const afterAdd = yield* readPersistedSnapshot(baseDir); + const addedProject = afterAdd.projects.find( + (project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null, + ); + assert.isTrue(addedProject !== undefined); + assert.equal(addedProject?.title, "Alpha"); + + yield* runCliWithRuntime(["project", "rename", workspaceRoot, "Beta", "--base-dir", baseDir]); + const afterRename = yield* readPersistedSnapshot(baseDir); + const renamedProject = afterRename.projects.find( + (project) => project.id === addedProject?.id, + ); + assert.equal(renamedProject?.title, "Beta"); + assert.equal(renamedProject?.deletedAt, null); + + yield* runCliWithRuntime([ + "project", + "remove", + addedProject?.id ?? "", + "--base-dir", + baseDir, + ]); + const afterRemove = yield* readPersistedSnapshot(baseDir); + const removedProject = afterRemove.projects.find( + (project) => project.id === addedProject?.id, + ); + assert.isTrue((removedProject?.deletedAt ?? null) !== null); + }), + ); + + it.effect("routes project commands through a running server when runtime state is present", () => + Effect.gen(function* () { + const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-projects-live-test-")); + const workspaceRoot = mkdtempSync(join(tmpdir(), "t3-cli-projects-live-workspace-")); + + yield* withLiveProjectCliServer(baseDir, () => + Effect.gen(function* () { + yield* runCliWithRuntime([ + "project", + "add", + workspaceRoot, + "--title", + "Live Project", + "--base-dir", + baseDir, + ]); + const orchestrationEngine = yield* OrchestrationEngineService; + const readModel = yield* orchestrationEngine.getReadModel(); + const addedProject = readModel.projects.find( + (project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null, + ); + assert.isTrue(addedProject !== undefined); + assert.equal(addedProject?.title, "Live Project"); + }), + ); + }), + ); + + it.effect("rejects dev-url on project commands", () => + Effect.gen(function* () { + const workspaceRoot = mkdtempSync( + join(tmpdir(), "t3-cli-projects-unknown-option-workspace-"), + ); + const error = yield* runCliWithRuntime([ + "project", + "add", + workspaceRoot, + "--dev-url", + "http://127.0.0.1:5173", + ]).pipe(Effect.flip); + + if (!CliError.isCliError(error)) { + assert.fail(`Expected CliError, got ${String(error)}`); + } + if (error._tag !== "ShowHelp") { + assert.fail(`Expected ShowHelp, got ${error._tag}`); + } + assert.deepEqual(error.commandPath, ["t3", "project", "add"]); + const optionError = error.errors[0] as CliError.CliError | undefined; + if (!optionError || optionError._tag !== "UnrecognizedOption") { + assert.fail(`Expected UnrecognizedOption, got ${String(optionError?._tag)}`); + } + assert.equal(optionError.option, "--dev-url"); + }), + ); +}); diff --git a/apps/server/src/cli.ts b/apps/server/src/cli.ts new file mode 100644 index 0000000000..5f73750920 --- /dev/null +++ b/apps/server/src/cli.ts @@ -0,0 +1,1132 @@ +import { NetService } from "@t3tools/shared/Net"; +import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings"; +import { + AuthSessionId, + CommandId, + OrchestrationReadModel, + ProjectId, + type ClientOrchestrationCommand, +} from "@t3tools/contracts"; +import { + Config, + Console, + Duration, + Effect, + Exit, + FileSystem, + Layer, + LogLevel, + Option, + Path, + References, + Schema, + SchemaIssue, + SchemaTransformation, +} from "effect"; +import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli"; +import { + FetchHttpClient, + HttpClient, + HttpClientRequest, + HttpClientResponse, +} from "effect/unstable/http"; + +import { + DEFAULT_PORT, + deriveServerPaths, + ensureServerDirectories, + resolveStaticDir, + ServerConfig, + RuntimeMode, + type ServerConfigShape, + type StartupPresentation, +} from "./config"; +import { readBootstrapEnvelope } from "./bootstrap"; +import { expandHomePath, resolveBaseDir } from "./os-jank"; +import { runServer } from "./server"; +import { AuthControlPlaneRuntimeLive } from "./auth/Layers/AuthControlPlane.ts"; +import { + formatIssuedPairingCredential, + formatIssuedSession, + formatPairingCredentialList, + formatSessionList, +} from "./cliAuthFormat"; +import { AuthControlPlane, AuthControlPlaneShape } from "./auth/Services/AuthControlPlane.ts"; +import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts"; +import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts"; +import { OrchestrationLayerLive } from "./orchestration/runtimeLayer"; +import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts"; +import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts"; +import { getAutoBootstrapDefaultModelSelection } from "./serverRuntimeStartup"; +import { + clearPersistedServerRuntimeState, + readPersistedServerRuntimeState, +} from "./serverRuntimeState"; +import { WorkspacePaths } from "./workspace/Services/WorkspacePaths"; +import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths"; + +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), + desktopBootstrapToken: Schema.optional(Schema.String), + autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean), + logWebSocketEvents: Schema.optional(Schema.Boolean), + otlpTracesUrl: Schema.optional(Schema.String), + otlpMetricsUrl: Schema.optional(Schema.String), +}); + +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 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")), + traceMinLevel: Config.logLevel("T3CODE_TRACE_MIN_LEVEL").pipe(Config.withDefault("Info")), + traceTimingEnabled: Config.boolean("T3CODE_TRACE_TIMING_ENABLED").pipe(Config.withDefault(true)), + traceFile: Config.string("T3CODE_TRACE_FILE").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + traceMaxBytes: Config.int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)), + traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)), + traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(200)), + otlpTracesUrl: Config.string("T3CODE_OTLP_TRACES_URL").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + otlpMetricsUrl: Config.string("T3CODE_OTLP_METRICS_URL").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + otlpExportIntervalMs: Config.int("T3CODE_OTLP_EXPORT_INTERVAL_MS").pipe( + Config.withDefault(10_000), + ), + otlpServiceName: Config.string("T3CODE_OTLP_SERVICE_NAME").pipe(Config.withDefault("t3-server")), + 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), + ), + 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 cwd: Option.Option; + readonly devUrl: Option.Option; + readonly noBrowser: Option.Option; + readonly bootstrapFd: Option.Option; + readonly autoBootstrapProjectFromCwd: Option.Option; + readonly logWebSocketEvents: Option.Option; +} + +interface CliAuthLocationFlags { + readonly baseDir: Option.Option; + readonly devUrl?: Option.Option; +} + +const resolveOptionPrecedence = ( + ...values: ReadonlyArray> +): Option.Option => Option.firstSomeOf(values); + +const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: string) { + const fs = yield* FileSystem.FileSystem; + const exists = yield* fs.exists(settingsPath).pipe(Effect.orElseSucceed(() => false)); + if (!exists) { + return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined }; + } + + const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => "")); + return parsePersistedServerObservabilitySettings(raw); +}); + +export const resolveServerConfig = ( + flags: CliServerFlags, + cliLogLevel: Option.Option, + options?: { + readonly startupPresentation?: StartupPresentation; + readonly forceAutoBootstrapProjectFromCwd?: boolean; + }, +) => + Effect.gen(function* () { + const { findAvailablePort } = yield* NetService; + const path = yield* Path.Path; + const fs = yield* FileSystem.FileSystem; + const env = yield* EnvServerConfig; + const normalizedFlags = { + mode: flags.mode ?? Option.none(), + port: flags.port ?? Option.none(), + host: flags.host ?? Option.none(), + baseDir: flags.baseDir ?? Option.none(), + cwd: flags.cwd ?? Option.none(), + devUrl: flags.devUrl ?? Option.none(), + noBrowser: flags.noBrowser ?? Option.none(), + bootstrapFd: flags.bootstrapFd ?? Option.none(), + autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(), + logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(), + } satisfies CliServerFlags; + const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd; + const bootstrapEnvelope = + bootstrapFd !== undefined + ? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd) + : Option.none(); + const bootstrap = Option.getOrUndefined(bootstrapEnvelope); + + const mode: RuntimeMode = Option.getOrElse( + resolveOptionPrecedence( + normalizedFlags.mode, + Option.fromUndefinedOr(env.mode), + Option.fromUndefinedOr(bootstrap?.mode), + ), + () => "web", + ); + + const port = yield* Option.match( + resolveOptionPrecedence( + normalizedFlags.port, + Option.fromUndefinedOr(env.port), + 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( + normalizedFlags.devUrl, + Option.fromUndefinedOr(env.devUrl), + Option.fromUndefinedOr(bootstrap?.devUrl), + ), + () => undefined, + ); + const baseDir = yield* resolveBaseDir( + Option.getOrUndefined( + resolveOptionPrecedence( + normalizedFlags.baseDir, + Option.fromUndefinedOr(env.t3Home), + Option.fromUndefinedOr(bootstrap?.t3Home), + ), + ), + ); + const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd()); + const cwd = path.resolve(yield* expandHomePath(rawCwd.trim())); + yield* fs.makeDirectory(cwd, { recursive: true }); + const derivedPaths = yield* deriveServerPaths(baseDir, devUrl); + yield* ensureServerDirectories(derivedPaths); + const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings( + derivedPaths.settingsPath, + ); + const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath; + yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true }); + const startupPresentation = options?.startupPresentation ?? "browser"; + const isHeadlessStartup = startupPresentation === "headless"; + const noBrowser = Option.getOrElse( + resolveOptionPrecedence( + isHeadlessStartup ? Option.some(true) : Option.none(), + normalizedFlags.noBrowser, + Option.fromUndefinedOr(env.noBrowser), + Option.fromUndefinedOr(bootstrap?.noBrowser), + ), + () => mode === "desktop", + ); + const desktopBootstrapToken = bootstrap?.desktopBootstrapToken; + const autoBootstrapProjectFromCwd = Option.getOrElse( + resolveOptionPrecedence( + Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd), + isHeadlessStartup ? Option.some(false) : Option.none(), + normalizedFlags.autoBootstrapProjectFromCwd, + Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd), + Option.fromUndefinedOr(bootstrap?.autoBootstrapProjectFromCwd), + ), + () => mode === "web", + ); + const logWebSocketEvents = Option.getOrElse( + resolveOptionPrecedence( + normalizedFlags.logWebSocketEvents, + Option.fromUndefinedOr(env.logWebSocketEvents), + Option.fromUndefinedOr(bootstrap?.logWebSocketEvents), + ), + () => Boolean(devUrl), + ); + const staticDir = devUrl ? undefined : yield* resolveStaticDir(); + const host = Option.getOrElse( + resolveOptionPrecedence( + normalizedFlags.host, + Option.fromUndefinedOr(env.host), + Option.fromUndefinedOr(bootstrap?.host), + ), + () => (mode === "desktop" ? "127.0.0.1" : undefined), + ); + const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel); + + const config: ServerConfigShape = { + logLevel, + traceMinLevel: env.traceMinLevel, + traceTimingEnabled: env.traceTimingEnabled, + traceBatchWindowMs: env.traceBatchWindowMs, + traceMaxBytes: env.traceMaxBytes, + traceMaxFiles: env.traceMaxFiles, + otlpTracesUrl: + env.otlpTracesUrl ?? + bootstrap?.otlpTracesUrl ?? + persistedObservabilitySettings.otlpTracesUrl, + otlpMetricsUrl: + env.otlpMetricsUrl ?? + bootstrap?.otlpMetricsUrl ?? + persistedObservabilitySettings.otlpMetricsUrl, + otlpExportIntervalMs: env.otlpExportIntervalMs, + otlpServiceName: env.otlpServiceName, + mode, + port, + cwd, + baseDir, + ...derivedPaths, + serverTracePath, + host, + staticDir, + devUrl, + noBrowser, + startupPresentation, + desktopBootstrapToken, + autoBootstrapProjectFromCwd, + logWebSocketEvents, + }; + + return config; + }); + +const resolveCliAuthConfig = ( + flags: CliAuthLocationFlags, + cliLogLevel: Option.Option, +) => + resolveServerConfig( + { + mode: Option.none(), + port: Option.none(), + host: Option.none(), + baseDir: flags.baseDir, + cwd: Option.none(), + devUrl: flags.devUrl ?? Option.none(), + noBrowser: Option.none(), + bootstrapFd: Option.none(), + autoBootstrapProjectFromCwd: Option.none(), + logWebSocketEvents: Option.none(), + }, + cliLogLevel, + ); + +const DurationShorthandPattern = /^(?\d+)(?ms|s|m|h|d|w)$/i; + +const parseDurationInput = (value: string): Duration.Duration | null => { + const trimmed = value.trim(); + if (trimmed.length === 0) return null; + + const shorthand = DurationShorthandPattern.exec(trimmed); + const normalizedInput = shorthand?.groups + ? (() => { + const amountText = shorthand.groups.value; + const unitText = shorthand.groups.unit; + if (typeof amountText !== "string" || typeof unitText !== "string") { + return null; + } + + const amount = Number.parseInt(amountText, 10); + if (!Number.isFinite(amount)) return null; + + switch (unitText.toLowerCase()) { + case "ms": + return `${amount} millis`; + case "s": + return `${amount} seconds`; + case "m": + return `${amount} minutes`; + case "h": + return `${amount} hours`; + case "d": + return `${amount} days`; + case "w": + return `${amount} weeks`; + default: + return null; + } + })() + : (trimmed as Duration.Input); + + if (normalizedInput === null) return null; + + const decoded = Duration.fromInput(normalizedInput as Duration.Input); + return Option.isSome(decoded) ? decoded.value : null; +}; + +const DurationFromString = Schema.String.pipe( + Schema.decodeTo( + Schema.Duration, + SchemaTransformation.transformOrFail({ + decode: (value) => { + const duration = parseDurationInput(value); + if (duration !== null) { + return Effect.succeed(duration); + } + return Effect.fail( + new SchemaIssue.InvalidValue(Option.some(value), { + message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.", + }), + ); + }, + encode: (duration) => Effect.succeed(Duration.format(duration)), + }), + ), +); + +const runWithAuthControlPlane = ( + flags: CliAuthLocationFlags, + run: (authControlPlane: AuthControlPlaneShape) => Effect.Effect, + options?: { + readonly quietLogs?: boolean; + }, +) => + Effect.gen(function* () { + const logLevel = yield* GlobalFlag.LogLevel; + const config = yield* resolveCliAuthConfig(flags, logLevel); + const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel; + return yield* Effect.gen(function* () { + const authControlPlane = yield* AuthControlPlane; + return yield* run(authControlPlane); + }).pipe( + Effect.provide( + Layer.mergeAll(AuthControlPlaneRuntimeLive).pipe( + Layer.provide(Layer.succeed(ServerConfig, config)), + Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)), + ), + ), + ); + }); + +type ProjectMutationTarget = { + readonly id: ProjectId; + readonly title: string; + readonly workspaceRoot: string; +}; + +type ProjectCommandExecutionMode = "live" | "offline"; +type ProjectCliDispatchCommand = Extract< + ClientOrchestrationCommand, + { type: "project.create" | "project.meta.update" | "project.delete" } +>; + +const ProjectCliRuntimeLive = Layer.mergeAll( + WorkspacePathsLive, + OrchestrationLayerLive.pipe( + Layer.provideMerge(RepositoryIdentityResolverLive), + Layer.provideMerge(SqlitePersistenceLayerLive), + ), +); + +const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1); +const OrchestrationHttpErrorResponse = Schema.Struct({ + error: Schema.String, +}); + +const withProjectCliSessionToken = ( + authControlPlane: AuthControlPlaneShape, + run: (token: string) => Effect.Effect, +) => + Effect.acquireUseRelease( + authControlPlane.issueSession({ + role: "owner", + label: "t3 project cli", + }), + (issued) => run(issued.token), + (issued) => authControlPlane.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })), + ); + +const withProjectCliLiveServerTimeout = (effect: Effect.Effect) => + effect.pipe(Effect.timeout(PROJECT_CLI_LIVE_SERVER_TIMEOUT)); + +const runLiveServerRequest = ( + request: HttpClientRequest.HttpClientRequest, + handle: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect, +) => + Effect.gen(function* () { + const httpClient = yield* HttpClient.HttpClient; + const response = yield* httpClient.execute(request); + return yield* handle(response); + }).pipe(withProjectCliLiveServerTimeout); + +const decodeOrchestrationReadModelResponse = (response: HttpClientResponse.HttpClientResponse) => + HttpClientResponse.schemaBodyJson(OrchestrationReadModel)(response); + +const readErrorMessageFromResponse = (response: HttpClientResponse.HttpClientResponse) => + HttpClientResponse.schemaBodyJson(OrchestrationHttpErrorResponse)(response).pipe( + Effect.map((body) => body.error), + Effect.catch(() => Effect.succeed(null)), + Effect.map((body) => { + if (typeof body === "string" && body.trim().length > 0) { + return body; + } + return `Server request failed with status ${response.status}.`; + }), + ); + +const normalizeWorkspaceRootForProjectCommand = Effect.fn( + "normalizeWorkspaceRootForProjectCommand", +)(function* (workspaceRoot: string) { + const workspacePaths = yield* WorkspacePaths; + return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot); +}); + +const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* ( + workspaceRoot: string, + explicitTitle?: string, +) { + if (explicitTitle !== undefined) { + const trimmed = explicitTitle.trim(); + if (trimmed.length > 0) { + return trimmed; + } + return yield* Effect.fail(new Error("Project title cannot be empty.")); + } + + const path = yield* Path.Path; + const basename = path.basename(workspaceRoot).trim(); + return basename.length > 0 ? basename : "project"; +}); + +const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: { + readonly snapshot: OrchestrationReadModel; + readonly identifier: string; +}) { + const trimmedIdentifier = input.identifier.trim(); + if (trimmedIdentifier.length === 0) { + return yield* Effect.fail(new Error("Project identifier cannot be empty.")); + } + + const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null); + const exactIdMatch = activeProjects.find((project) => project.id === trimmedIdentifier); + if (exactIdMatch) { + return { + id: exactIdMatch.id, + title: exactIdMatch.title, + workspaceRoot: exactIdMatch.workspaceRoot, + } satisfies ProjectMutationTarget; + } + + const normalizedWorkspaceRootResult = yield* Effect.exit( + normalizeWorkspaceRootForProjectCommand(trimmedIdentifier), + ); + const normalizedWorkspaceRoot = Exit.isSuccess(normalizedWorkspaceRootResult) + ? normalizedWorkspaceRootResult.value + : null; + + const exactWorkspaceMatch = + normalizedWorkspaceRoot === null + ? undefined + : activeProjects.find((project) => project.workspaceRoot === normalizedWorkspaceRoot); + + const resolved = exactWorkspaceMatch; + if (!resolved) { + return yield* Effect.fail(new Error(`No active project found for '${trimmedIdentifier}'.`)); + } + + return { + id: resolved.id, + title: resolved.title, + workspaceRoot: resolved.workspaceRoot, + } satisfies ProjectMutationTarget; +}); + +const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) => + runLiveServerRequest( + HttpClientRequest.get(`${origin}/api/orchestration/snapshot`).pipe( + HttpClientRequest.acceptJson, + HttpClientRequest.bearerToken(bearerToken), + ), + HttpClientResponse.matchStatus({ + "2xx": decodeOrchestrationReadModelResponse, + orElse: (response) => + readErrorMessageFromResponse(response).pipe( + Effect.flatMap((message) => Effect.fail(new Error(message))), + ), + }), + ); + +const dispatchLiveOrchestrationCommand = ( + origin: string, + bearerToken: string, + command: ProjectCliDispatchCommand, +) => + HttpClientRequest.post(`${origin}/api/orchestration/dispatch`).pipe( + HttpClientRequest.acceptJson, + HttpClientRequest.bearerToken(bearerToken), + HttpClientRequest.bodyJson(command), + Effect.flatMap((request) => + runLiveServerRequest( + request, + HttpClientResponse.matchStatus({ + "2xx": () => Effect.void, + orElse: (response) => + readErrorMessageFromResponse(response).pipe( + Effect.flatMap((message) => Effect.fail(new Error(message))), + ), + }), + ), + ), + ); + +const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () { + const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; + return yield* projectionSnapshotQuery.getSnapshot(); +}); + +const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")( + function* (authControlPlane: AuthControlPlaneShape, config: ServerConfigShape) { + const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath); + if (Option.isNone(runtimeState)) { + return Option.none<{ readonly origin: string }>(); + } + + const attempt = withProjectCliSessionToken(authControlPlane, (token) => + fetchLiveOrchestrationSnapshot(runtimeState.value.origin, token).pipe( + Effect.as({ + origin: runtimeState.value.origin, + }), + ), + ); + + const attempted = yield* Effect.exit(attempt); + if (Exit.isSuccess(attempted)) { + return Option.some(attempted.value); + } + + yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath); + return Option.none<{ readonly origin: string }>(); + }, +); + +const runProjectMutation = Effect.fn("runProjectMutation")(function* ( + flags: CliAuthLocationFlags, + run: (input: { + readonly snapshot: OrchestrationReadModel; + readonly dispatch: ( + command: ProjectCliDispatchCommand, + ) => Effect.Effect; + readonly mode: ProjectCommandExecutionMode; + }) => Effect.Effect< + string, + Error, + FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | WorkspacePaths + >, +) { + const logLevel = yield* GlobalFlag.LogLevel; + const config = yield* resolveCliAuthConfig(flags, logLevel); + const minimumLogLevel = config.logLevel; + + return yield* Effect.gen(function* () { + const authControlPlane = yield* AuthControlPlane; + const liveMode = yield* tryResolveLiveProjectExecutionMode(authControlPlane, config); + + if (Option.isSome(liveMode)) { + return yield* withProjectCliSessionToken(authControlPlane, (token) => + Effect.gen(function* () { + const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token); + const output = yield* run({ + snapshot, + dispatch: (command) => + dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command), + mode: "live", + }); + yield* Console.log(output); + }), + ); + } + + const offlineRuntimeLayer = ProjectCliRuntimeLive.pipe( + Layer.provide(Layer.succeed(ServerConfig, config)), + Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)), + ); + + return yield* Effect.gen(function* () { + const snapshot = yield* getOfflineSnapshot(); + const orchestrationEngine = yield* OrchestrationEngineService; + const output = yield* run({ + snapshot, + dispatch: (command) => orchestrationEngine.dispatch(command), + mode: "offline", + }); + yield* Console.log(output); + }).pipe(Effect.provide(offlineRuntimeLayer)); + }).pipe( + Effect.provide( + Layer.mergeAll(AuthControlPlaneRuntimeLive, WorkspacePathsLive).pipe( + Layer.provideMerge(FetchHttpClient.layer), + Layer.provide(Layer.succeed(ServerConfig, config)), + Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)), + ), + ), + ); +}); + +const sharedServerLocationFlags = { + baseDir: baseDirFlag, + devUrl: devUrlFlag, +} as const; + +const projectLocationFlags = { + baseDir: baseDirFlag, +} as const; + +const sharedServerCommandFlags = { + mode: modeFlag, + port: portFlag, + host: hostFlag, + baseDir: baseDirFlag, + cwd: Argument.string("cwd").pipe( + Argument.withDescription( + "Working directory for provider sessions (defaults to the current directory).", + ), + Argument.optional, + ), + devUrl: devUrlFlag, + noBrowser: noBrowserFlag, + bootstrapFd: bootstrapFdFlag, + autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag, + logWebSocketEvents: logWebSocketEventsFlag, +} as const; + +const authLocationFlags = sharedServerLocationFlags; + +const ttlFlag = Flag.string("ttl").pipe( + Flag.withSchema(DurationFromString), + Flag.withDescription("TTL, for example `5m`, `1h`, `30d`, or `15 minutes`."), + Flag.optional, +); + +const jsonFlag = Flag.boolean("json").pipe( + Flag.withDescription("Emit JSON instead of human-readable output."), + Flag.withDefault(false), +); + +const sessionRoleFlag = Flag.choice("role", ["owner", "client"]).pipe( + Flag.withDescription("Role for the issued bearer session."), + Flag.withDefault("owner"), +); + +const labelFlag = Flag.string("label").pipe( + Flag.withDescription("Optional human-readable label."), + Flag.optional, +); + +const subjectFlag = Flag.string("subject").pipe( + Flag.withDescription("Optional session subject."), + Flag.optional, +); + +const baseUrlFlag = Flag.string("base-url").pipe( + Flag.withDescription("Optional public base URL used to print a ready `/pair#token=...` link."), + Flag.optional, +); + +const tokenOnlyFlag = Flag.boolean("token-only").pipe( + Flag.withDescription("Print only the issued bearer token."), + Flag.withDefault(false), +); + +const pairingCreateCommand = Command.make("create", { + ...authLocationFlags, + ttl: ttlFlag, + label: labelFlag, + baseUrl: baseUrlFlag, + json: jsonFlag, +}).pipe( + Command.withDescription("Issue a new client pairing token."), + Command.withHandler((flags) => + runWithAuthControlPlane( + flags, + (authControlPlane) => + Effect.gen(function* () { + const issued = yield* authControlPlane.createPairingLink({ + role: "client", + subject: "one-time-token", + ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}), + ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}), + }); + const output = formatIssuedPairingCredential(issued, { + json: flags.json, + ...(Option.isSome(flags.baseUrl) ? { baseUrl: flags.baseUrl.value } : {}), + }); + yield* Console.log(output); + }), + { + quietLogs: flags.json, + }, + ), + ), +); + +const pairingListCommand = Command.make("list", { + ...authLocationFlags, + json: jsonFlag, +}).pipe( + Command.withDescription("List active client pairing tokens without revealing their secrets."), + Command.withHandler((flags) => + runWithAuthControlPlane( + flags, + (authControlPlane) => + Effect.gen(function* () { + const pairingLinks = yield* authControlPlane.listPairingLinks({ role: "client" }); + yield* Console.log(formatPairingCredentialList(pairingLinks, { json: flags.json })); + }), + { + quietLogs: flags.json, + }, + ), + ), +); + +const pairingRevokeCommand = Command.make("revoke", { + ...authLocationFlags, + id: Argument.string("id").pipe(Argument.withDescription("Pairing credential id to revoke.")), +}).pipe( + Command.withDescription("Revoke an active client pairing token."), + Command.withHandler((flags) => + runWithAuthControlPlane(flags, (authControlPlane) => + Effect.gen(function* () { + const revoked = yield* authControlPlane.revokePairingLink(flags.id); + yield* Console.log( + revoked + ? `Revoked pairing credential ${flags.id}.\n` + : `No active pairing credential found for ${flags.id}.\n`, + ); + }), + ), + ), +); + +const pairingCommand = Command.make("pairing").pipe( + Command.withDescription("Manage one-time client pairing tokens."), + Command.withSubcommands([pairingCreateCommand, pairingListCommand, pairingRevokeCommand]), +); + +const sessionIssueCommand = Command.make("issue", { + ...authLocationFlags, + ttl: ttlFlag, + role: sessionRoleFlag, + label: labelFlag, + subject: subjectFlag, + tokenOnly: tokenOnlyFlag, + json: jsonFlag, +}).pipe( + Command.withDescription("Issue a bearer session token for headless or remote clients."), + Command.withHandler((flags) => + runWithAuthControlPlane( + flags, + (authControlPlane) => + Effect.gen(function* () { + const issued = yield* authControlPlane.issueSession({ + role: flags.role, + ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}), + ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}), + ...(Option.isSome(flags.subject) ? { subject: flags.subject.value } : {}), + }); + yield* Console.log( + formatIssuedSession(issued, { + json: flags.json, + tokenOnly: flags.tokenOnly, + }), + ); + }), + { + quietLogs: flags.json || flags.tokenOnly, + }, + ), + ), +); + +const sessionListCommand = Command.make("list", { + ...authLocationFlags, + json: jsonFlag, +}).pipe( + Command.withDescription("List active sessions without revealing bearer tokens."), + Command.withHandler((flags) => + runWithAuthControlPlane( + flags, + (authControlPlane) => + Effect.gen(function* () { + const sessions = yield* authControlPlane.listSessions(); + yield* Console.log(formatSessionList(sessions, { json: flags.json })); + }), + { + quietLogs: flags.json, + }, + ), + ), +); + +const sessionRevokeCommand = Command.make("revoke", { + ...authLocationFlags, + sessionId: Argument.string("session-id").pipe( + Argument.withDescription("Session id to revoke."), + Argument.withSchema(AuthSessionId), + ), +}).pipe( + Command.withDescription("Revoke an active session."), + Command.withHandler((flags) => + runWithAuthControlPlane(flags, (authControlPlane) => + Effect.gen(function* () { + const revoked = yield* authControlPlane.revokeSession(flags.sessionId); + yield* Console.log( + revoked + ? `Revoked session ${flags.sessionId}.\n` + : `No active session found for ${flags.sessionId}.\n`, + ); + }), + ), + ), +); + +const sessionCommand = Command.make("session").pipe( + Command.withDescription("Manage bearer sessions."), + Command.withSubcommands([sessionIssueCommand, sessionListCommand, sessionRevokeCommand]), +); + +const authCommand = Command.make("auth").pipe( + Command.withDescription("Manage the local auth control plane for headless deployments."), + Command.withSubcommands([pairingCommand, sessionCommand]), +); + +const projectAddCommand = Command.make("add", { + ...projectLocationFlags, + workspaceRoot: Argument.string("path").pipe( + Argument.withDescription("Workspace root to add as a project."), + ), + title: Flag.string("title").pipe(Flag.withDescription("Optional project title."), Flag.optional), +}).pipe( + Command.withDescription("Add a project."), + Command.withHandler((flags) => + runProjectMutation( + flags, + Effect.fn("projectAddMutation")(function* ({ + snapshot, + dispatch, + }: { + readonly snapshot: OrchestrationReadModel; + readonly dispatch: ( + command: ProjectCliDispatchCommand, + ) => Effect.Effect; + }) { + const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot); + const existingProject = snapshot.projects.find( + (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot, + ); + if (existingProject) { + return yield* Effect.fail( + new Error(`An active project already exists for '${workspaceRoot}'.`), + ); + } + + const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title)); + const projectId = ProjectId.make(crypto.randomUUID()); + yield* dispatch({ + type: "project.create", + commandId: CommandId.make(crypto.randomUUID()), + projectId, + title, + workspaceRoot, + defaultModelSelection: getAutoBootstrapDefaultModelSelection(), + createdAt: new Date().toISOString(), + }); + return `Added project ${projectId} (${title}) at ${workspaceRoot}.`; + }), + ), + ), +); + +const projectRemoveCommand = Command.make("remove", { + ...projectLocationFlags, + project: Argument.string("project").pipe( + Argument.withDescription("Project id or workspace root to remove."), + ), +}).pipe( + Command.withDescription("Remove a project."), + Command.withHandler((flags) => + runProjectMutation( + flags, + Effect.fn("projectRemoveMutation")(function* ({ + snapshot, + dispatch, + }: { + readonly snapshot: OrchestrationReadModel; + readonly dispatch: ( + command: ProjectCliDispatchCommand, + ) => Effect.Effect; + }) { + const project = yield* findActiveProjectTarget({ + snapshot, + identifier: flags.project, + }); + yield* dispatch({ + type: "project.delete", + commandId: CommandId.make(crypto.randomUUID()), + projectId: project.id, + }); + return `Removed project ${project.id} (${project.title}).`; + }), + ), + ), +); + +const projectRenameCommand = Command.make("rename", { + ...projectLocationFlags, + project: Argument.string("project").pipe( + Argument.withDescription("Project id or workspace root to rename."), + ), + title: Argument.string("title").pipe(Argument.withDescription("New project title.")), +}).pipe( + Command.withDescription("Rename a project."), + Command.withHandler((flags) => + runProjectMutation( + flags, + Effect.fn("projectRenameMutation")(function* ({ + snapshot, + dispatch, + }: { + readonly snapshot: OrchestrationReadModel; + readonly dispatch: ( + command: ProjectCliDispatchCommand, + ) => Effect.Effect; + }) { + const project = yield* findActiveProjectTarget({ + snapshot, + identifier: flags.project, + }); + const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title); + if (nextTitle === project.title) { + return `Project ${project.id} is already named ${nextTitle}.`; + } + + yield* dispatch({ + type: "project.meta.update", + commandId: CommandId.make(crypto.randomUUID()), + projectId: project.id, + title: nextTitle, + }); + return `Renamed project ${project.id} to ${nextTitle}.`; + }), + ), + ), +); + +const projectCommand = Command.make("project").pipe( + Command.withDescription("Manage projects."), + Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]), +); + +const runServerCommand = ( + flags: CliServerFlags, + options?: { + readonly startupPresentation?: StartupPresentation; + readonly forceAutoBootstrapProjectFromCwd?: boolean; + }, +) => + Effect.gen(function* () { + const logLevel = yield* GlobalFlag.LogLevel; + const config = yield* resolveServerConfig(flags, logLevel, options); + return yield* runServer.pipe(Effect.provideService(ServerConfig, config)); + }); + +const startCommand = Command.make("start", { ...sharedServerCommandFlags }).pipe( + Command.withDescription("Run the T3 Code server."), + Command.withHandler((flags) => runServerCommand(flags)), +); + +const serveCommand = Command.make("serve", { ...sharedServerCommandFlags }).pipe( + Command.withDescription( + "Run the T3 Code server without opening a browser and print headless pairing details.", + ), + Command.withHandler((flags) => + runServerCommand(flags, { + startupPresentation: "headless", + forceAutoBootstrapProjectFromCwd: false, + }), + ), +); + +export const cli = Command.make("t3", { ...sharedServerCommandFlags }).pipe( + Command.withDescription("Run the T3 Code server."), + Command.withHandler((flags) => runServerCommand(flags)), + Command.withSubcommands([startCommand, serveCommand, authCommand, projectCommand]), +); diff --git a/apps/server/src/cliAuthFormat.test.ts b/apps/server/src/cliAuthFormat.test.ts new file mode 100644 index 0000000000..017ced97e8 --- /dev/null +++ b/apps/server/src/cliAuthFormat.test.ts @@ -0,0 +1,88 @@ +import { expect, it } from "@effect/vitest"; +import { DateTime } from "effect"; + +import { + formatIssuedPairingCredential, + formatIssuedSession, + formatPairingCredentialList, + formatSessionList, +} from "./cliAuthFormat.ts"; + +it("formats issued pairing credentials with the secret and optional pair URL", () => { + const output = formatIssuedPairingCredential( + { + id: "pairing-1", + credential: "secret-pairing-token", + role: "client", + subject: "one-time-token", + createdAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")), + expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")), + }, + { baseUrl: "https://example.com", json: false }, + ); + + expect(output).toContain("secret-pairing-token"); + expect(output).toContain("https://example.com/pair#token=secret-pairing-token"); +}); + +it("formats pairing listings without exposing the secret token", () => { + const output = formatPairingCredentialList( + [ + { + id: "pairing-1", + credential: "secret-pairing-token", + subject: "one-time-token", + label: "Phone", + role: "client", + createdAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")), + expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")), + }, + ], + { json: false }, + ); + + expect(output).toContain("pairing-1"); + expect(output).not.toContain("secret-pairing-token"); +}); + +it("formats issued sessions with the bearer token but omits tokens from listings", () => { + const issuedOutput = formatIssuedSession( + { + sessionId: "session-1" as never, + token: "secret-session-token", + method: "bearer-session-token", + role: "owner", + subject: "cli-issued-session", + client: { + label: "deploy-bot", + deviceType: "bot", + }, + expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")), + }, + { json: false }, + ); + + const listedOutput = formatSessionList( + [ + { + sessionId: "session-1" as never, + method: "bearer-session-token", + role: "owner", + subject: "cli-issued-session", + client: { + label: "deploy-bot", + deviceType: "bot", + }, + connected: false, + current: false, + issuedAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")), + expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")), + lastConnectedAt: null, + }, + ], + { json: false }, + ); + + expect(issuedOutput).toContain("secret-session-token"); + expect(listedOutput).not.toContain("secret-session-token"); +}); diff --git a/apps/server/src/cliAuthFormat.ts b/apps/server/src/cliAuthFormat.ts new file mode 100644 index 0000000000..44356c5a8a --- /dev/null +++ b/apps/server/src/cliAuthFormat.ts @@ -0,0 +1,190 @@ +import type { AuthClientMetadata, AuthClientSession, AuthPairingLink } from "@t3tools/contracts"; +import { DateTime } from "effect"; + +import type { IssuedBearerSession, IssuedPairingLink } from "./auth/Services/AuthControlPlane.ts"; + +const newline = "\n"; + +function serializeOptionalFields(values: ReadonlyArray) { + return values.filter((value): value is string => typeof value === "string" && value.length > 0); +} + +function formatClientMetadata(metadata: AuthClientMetadata): string { + const details = serializeOptionalFields([ + metadata.label, + metadata.deviceType !== "unknown" ? metadata.deviceType : undefined, + metadata.os, + metadata.browser, + metadata.ipAddress, + ]); + return details.length > 0 ? details.join(" | ") : "unlabeled client"; +} + +function toIsoString(value: DateTime.DateTime | DateTime.Utc): string { + return DateTime.formatIso(DateTime.toUtc(value)); +} + +export function formatIssuedPairingCredential( + credential: IssuedPairingLink, + options?: { + readonly json?: boolean; + readonly baseUrl?: string; + }, +): string { + const pairUrl = + options?.baseUrl != null && options.baseUrl.length > 0 + ? (() => { + const url = new URL("/pair", options.baseUrl); + url.searchParams.delete("token"); + url.hash = new URLSearchParams([["token", credential.credential]]).toString(); + return url.toString(); + })() + : undefined; + + if (options?.json) { + return `${JSON.stringify( + { + id: credential.id, + credential: credential.credential, + ...(credential.label ? { label: credential.label } : {}), + role: credential.role, + expiresAt: toIsoString(credential.expiresAt), + ...(pairUrl ? { pairUrl } : {}), + }, + null, + 2, + )}${newline}`; + } + + return ( + [ + `Issued client pairing token ${credential.id}.`, + `Token: ${credential.credential}`, + ...(pairUrl ? [`Pair URL: ${pairUrl}`] : []), + `Expires at: ${credential.expiresAt}`, + ].join(newline) + newline + ); +} + +export function formatPairingCredentialList( + credentials: ReadonlyArray, + options?: { + readonly json?: boolean; + }, +): string { + if (options?.json) { + return `${JSON.stringify( + credentials.map((credential) => ({ + id: credential.id, + ...(credential.label ? { label: credential.label } : {}), + role: credential.role, + createdAt: toIsoString(credential.createdAt), + expiresAt: toIsoString(credential.expiresAt), + })), + null, + 2, + )}${newline}`; + } + + if (credentials.length === 0) { + return `No active pairing credentials.${newline}`; + } + + return ( + credentials + .map((credential) => + [ + `${credential.id}${credential.label ? ` (${credential.label})` : ""}`, + ` role: ${credential.role}`, + ` created: ${toIsoString(credential.createdAt)}`, + ` expires: ${toIsoString(credential.expiresAt)}`, + ].join(newline), + ) + .join(`${newline}${newline}`) + newline + ); +} + +export function formatIssuedSession( + session: IssuedBearerSession, + options?: { + readonly json?: boolean; + readonly tokenOnly?: boolean; + }, +): string { + if (options?.tokenOnly) { + return `${session.token}${newline}`; + } + + if (options?.json) { + return `${JSON.stringify( + { + sessionId: session.sessionId, + token: session.token, + method: session.method, + role: session.role, + subject: session.subject, + client: session.client, + expiresAt: toIsoString(session.expiresAt), + }, + null, + 2, + )}${newline}`; + } + + return ( + [ + `Issued ${session.role} bearer session ${session.sessionId}.`, + `Token: ${session.token}`, + `Subject: ${session.subject}`, + `Client: ${formatClientMetadata(session.client)}`, + `Expires at: ${toIsoString(session.expiresAt)}`, + ].join(newline) + newline + ); +} + +export function formatSessionList( + sessions: ReadonlyArray, + options?: { + readonly json?: boolean; + }, +): string { + if (options?.json) { + return `${JSON.stringify( + sessions.map((session) => ({ + sessionId: session.sessionId, + method: session.method, + role: session.role, + subject: session.subject, + client: session.client, + connected: session.connected, + issuedAt: toIsoString(session.issuedAt), + expiresAt: toIsoString(session.expiresAt), + lastConnectedAt: session.lastConnectedAt ? toIsoString(session.lastConnectedAt) : null, + })), + null, + 2, + )}${newline}`; + } + + if (sessions.length === 0) { + return `No active sessions.${newline}`; + } + + return ( + sessions + .map((session) => + [ + `${session.sessionId} [${session.role}]${session.connected ? " connected" : ""}`, + ` method: ${session.method}`, + ` subject: ${session.subject}`, + ` client: ${formatClientMetadata(session.client)}`, + ` issued: ${toIsoString(session.issuedAt)}`, + ` last connected: ${ + session.lastConnectedAt ? toIsoString(session.lastConnectedAt) : "never" + }`, + ` expires: ${toIsoString(session.expiresAt)}`, + ].join(newline), + ) + .join(`${newline}${newline}`) + newline + ); +} diff --git a/apps/server/src/codexAppServerManager.test.ts b/apps/server/src/codexAppServerManager.test.ts index 2f740a7407..ab3b7a569d 100644 --- a/apps/server/src/codexAppServerManager.test.ts +++ b/apps/server/src/codexAppServerManager.test.ts @@ -17,7 +17,7 @@ import { resolveCodexModelForAccount, } from "./codexAppServerManager"; -const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value); +const asThreadId = (value: string): ThreadId => ThreadId.make(value); function createSendTurnHarness() { const manager = new CodexAppServerManager(); @@ -111,9 +111,9 @@ function createPendingUserInputHarness() { }, pendingUserInputs: new Map([ [ - ApprovalRequestId.makeUnsafe("req-user-input-1"), + ApprovalRequestId.make("req-user-input-1"), { - requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"), + requestId: ApprovalRequestId.make("req-user-input-1"), jsonRpcId: 42, threadId: asThreadId("thread_1"), }, @@ -743,7 +743,7 @@ describe("respondToUserInput", () => { await manager.respondToUserInput( asThreadId("thread_1"), - ApprovalRequestId.makeUnsafe("req-user-input-1"), + ApprovalRequestId.make("req-user-input-1"), { scope: "All request methods", compat: "Keep current envelope", @@ -780,7 +780,7 @@ describe("respondToUserInput", () => { await manager.respondToUserInput( asThreadId("thread_1"), - ApprovalRequestId.makeUnsafe("req-user-input-1"), + ApprovalRequestId.make("req-user-input-1"), { scope: [], }, diff --git a/apps/server/src/codexAppServerManager.ts b/apps/server/src/codexAppServerManager.ts index c06a3d2614..43ffdb4a4c 100644 --- a/apps/server/src/codexAppServerManager.ts +++ b/apps/server/src/codexAppServerManager.ts @@ -19,7 +19,7 @@ import { ProviderInteractionMode, } from "@t3tools/contracts"; import { normalizeModelSlug } from "@t3tools/shared/model"; -import { Effect, ServiceMap } from "effect"; +import { Effect, Context } from "effect"; import { formatCodexCliUpgradeMessage, @@ -291,20 +291,26 @@ In Default mode, strongly prefer making reasonable assumptions and executing the `; function mapCodexRuntimeMode(runtimeMode: RuntimeMode): { - readonly approvalPolicy: "on-request" | "never"; - readonly sandbox: "workspace-write" | "danger-full-access"; + readonly approvalPolicy: "untrusted" | "on-request" | "never"; + readonly sandbox: "read-only" | "workspace-write" | "danger-full-access"; } { - if (runtimeMode === "approval-required") { - return { - approvalPolicy: "on-request", - sandbox: "workspace-write", - }; + switch (runtimeMode) { + case "approval-required": + return { + approvalPolicy: "untrusted", + sandbox: "read-only", + }; + case "auto-accept-edits": + return { + approvalPolicy: "on-request", + sandbox: "workspace-write", + }; + case "full-access": + return { + approvalPolicy: "never", + sandbox: "danger-full-access", + }; } - - return { - approvalPolicy: "never", - sandbox: "danger-full-access", - }; } export function normalizeCodexModelSlug( @@ -425,7 +431,7 @@ export class CodexAppServerManager extends EventEmitter(); private runPromise: (effect: Effect.Effect) => Promise; - constructor(services?: ServiceMap.ServiceMap) { + constructor(services?: Context.Context) { super(); this.runPromise = services ? Effect.runPromiseWith(services) : Effect.runPromise; } @@ -626,7 +632,7 @@ export class CodexAppServerManager extends EventEmitter { const turn = this.readObject(turnValue); const turnIdRaw = this.readString(turn, "id") ?? `${threadIdRaw}:turn:${index + 1}`; - const turnId = TurnId.makeUnsafe(turnIdRaw); + const turnId = TurnId.make(turnIdRaw); const items = this.readArray(turn, "items") ?? []; return { id: turnId, @@ -1576,9 +1582,9 @@ function readResumeThreadId(input: { } function toTurnId(value: string | undefined): TurnId | undefined { - return brandIfNonEmpty(value, TurnId.makeUnsafe); + return brandIfNonEmpty(value, TurnId.make); } function toProviderItemId(value: string | undefined): ProviderItemId | undefined { - return brandIfNonEmpty(value, ProviderItemId.makeUnsafe); + return brandIfNonEmpty(value, ProviderItemId.make); } diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index 29f82bccf1..c2e5ecee45 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -6,11 +6,15 @@ * * @module ServerConfig */ -import { Effect, FileSystem, Layer, Path, ServiceMap } from "effect"; +import { Effect, FileSystem, Layer, LogLevel, Path, Schema, Context } from "effect"; export const DEFAULT_PORT = 3773; -export type RuntimeMode = "web" | "desktop"; +export const RuntimeMode = Schema.Literals(["web", "desktop"]); +export type RuntimeMode = typeof RuntimeMode.Type; + +export const StartupPresentation = Schema.Literals(["browser", "headless"]); +export type StartupPresentation = typeof StartupPresentation.Type; /** * ServerDerivedPaths - Derived paths from the base directory. @@ -24,16 +28,30 @@ export interface ServerDerivedPaths { readonly attachmentsDir: string; readonly logsDir: string; readonly serverLogPath: string; + readonly serverTracePath: string; readonly providerLogsDir: string; readonly providerEventLogPath: string; readonly terminalLogsDir: string; readonly anonymousIdPath: string; + readonly environmentIdPath: string; + readonly serverRuntimeStatePath: string; + readonly secretsDir: string; } /** * ServerConfigShape - Process/runtime configuration required by the server. */ export interface ServerConfigShape extends ServerDerivedPaths { + readonly logLevel: LogLevel.LogLevel; + readonly traceMinLevel: LogLevel.LogLevel; + readonly traceTimingEnabled: boolean; + readonly traceBatchWindowMs: number; + readonly traceMaxBytes: number; + readonly traceMaxFiles: number; + readonly otlpTracesUrl: string | undefined; + readonly otlpMetricsUrl: string | undefined; + readonly otlpExportIntervalMs: number; + readonly otlpServiceName: string; readonly mode: RuntimeMode; readonly port: number; readonly host: string | undefined; @@ -42,7 +60,8 @@ export interface ServerConfigShape extends ServerDerivedPaths { readonly staticDir: string | undefined; readonly devUrl: URL | undefined; readonly noBrowser: boolean; - readonly authToken: string | undefined; + readonly startupPresentation: StartupPresentation; + readonly desktopBootstrapToken: string | undefined; readonly autoBootstrapProjectFromCwd: boolean; readonly logWebSocketEvents: boolean; } @@ -66,17 +85,42 @@ export const deriveServerPaths = Effect.fn(function* ( attachmentsDir, logsDir, serverLogPath: join(logsDir, "server.log"), + serverTracePath: join(logsDir, "server.trace.ndjson"), providerLogsDir, providerEventLogPath: join(providerLogsDir, "events.log"), terminalLogsDir: join(logsDir, "terminals"), anonymousIdPath: join(stateDir, "anonymous-id"), + environmentIdPath: join(stateDir, "environment-id"), + serverRuntimeStatePath: join(stateDir, "server-runtime.json"), + secretsDir: join(stateDir, "secrets"), }; }); +export const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + yield* Effect.all( + [ + fs.makeDirectory(derivedPaths.stateDir, { recursive: true }), + fs.makeDirectory(derivedPaths.logsDir, { recursive: true }), + fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }), + fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }), + fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }), + fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }), + fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }), + fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }), + fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }), + fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }), + ], + { concurrency: "unbounded" }, + ); +}); + /** * ServerConfig - Service tag for server runtime configuration. */ -export class ServerConfig extends ServiceMap.Service()( +export class ServerConfig extends Context.Service()( "t3/config/ServerConfig", ) { static readonly layerTest = (cwd: string, baseDirOrPrefix: string | { prefix: string }) => @@ -91,12 +135,19 @@ export class ServerConfig extends ServiceMap.Service + ServerEnvironmentLive.pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir))); + +const makeServerConfig = Effect.fn(function* (baseDir: string) { + const derivedPaths = yield* deriveServerPaths(baseDir, undefined); + + return { + ...derivedPaths, + logLevel: "Error", + traceMinLevel: "Info", + traceTimingEnabled: true, + traceBatchWindowMs: 200, + traceMaxBytes: 10 * 1024 * 1024, + traceMaxFiles: 10, + otlpTracesUrl: undefined, + otlpMetricsUrl: undefined, + otlpExportIntervalMs: 10_000, + otlpServiceName: "t3-server", + cwd: process.cwd(), + baseDir, + mode: "web", + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: false, + port: 0, + host: undefined, + desktopBootstrapToken: undefined, + staticDir: undefined, + devUrl: undefined, + noBrowser: false, + startupPresentation: "browser", + } satisfies ServerConfigShape; +}); + +it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => { + it.effect("persists the environment id across service restarts", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const baseDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-server-environment-test-", + }); + + const first = yield* Effect.gen(function* () { + const serverEnvironment = yield* ServerEnvironment; + return yield* serverEnvironment.getDescriptor; + }).pipe(Effect.provide(makeServerEnvironmentLayer(baseDir))); + const second = yield* Effect.gen(function* () { + const serverEnvironment = yield* ServerEnvironment; + return yield* serverEnvironment.getDescriptor; + }).pipe(Effect.provide(makeServerEnvironmentLayer(baseDir))); + + expect(first.environmentId).toBe(second.environmentId); + expect(second.capabilities.repositoryIdentity).toBe(true); + }), + ); + + it.effect("fails instead of overwriting a persisted id when reading the file errors", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const baseDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-server-environment-read-error-test-", + }); + const serverConfig = yield* makeServerConfig(baseDir); + const environmentIdPath = serverConfig.environmentIdPath; + yield* fileSystem.makeDirectory(nodePath.dirname(environmentIdPath), { recursive: true }); + yield* fileSystem.writeFileString(environmentIdPath, "persisted-environment-id\n"); + const writeAttempts: string[] = []; + const failingFileSystemLayer = FileSystem.layerNoop({ + exists: (path) => Effect.succeed(path === environmentIdPath), + readFileString: (path) => + path === environmentIdPath + ? Effect.fail( + PlatformError.systemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method: "readFileString", + description: "permission denied", + pathOrDescriptor: path, + }), + ) + : Effect.fail( + PlatformError.systemError({ + _tag: "NotFound", + module: "FileSystem", + method: "readFileString", + description: "not found", + pathOrDescriptor: path, + }), + ), + writeFileString: (path) => { + writeAttempts.push(path); + return Effect.void; + }, + }); + + const exit = yield* Effect.gen(function* () { + const serverEnvironment = yield* ServerEnvironment; + return yield* serverEnvironment.getDescriptor; + }).pipe( + Effect.provide( + ServerEnvironmentLive.pipe( + Layer.provide( + Layer.merge(Layer.succeed(ServerConfig, serverConfig), failingFileSystemLayer), + ), + ), + ), + Effect.exit, + ); + + expect(Exit.isFailure(exit)).toBe(true); + expect(writeAttempts).toEqual([]); + expect(yield* fileSystem.readFileString(environmentIdPath)).toBe( + "persisted-environment-id\n", + ); + }), + ); +}); diff --git a/apps/server/src/environment/Layers/ServerEnvironment.ts b/apps/server/src/environment/Layers/ServerEnvironment.ts new file mode 100644 index 0000000000..506fc45af7 --- /dev/null +++ b/apps/server/src/environment/Layers/ServerEnvironment.ts @@ -0,0 +1,92 @@ +import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts"; +import { Effect, FileSystem, Layer, Path, Random } from "effect"; + +import { ServerConfig } from "../../config.ts"; +import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/ServerEnvironment.ts"; +import { version } from "../../../package.json" with { type: "json" }; +import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts"; + +function platformOs(): ExecutionEnvironmentDescriptor["platform"]["os"] { + switch (process.platform) { + case "darwin": + return "darwin"; + case "linux": + return "linux"; + case "win32": + return "windows"; + default: + return "unknown"; + } +} + +function platformArch(): ExecutionEnvironmentDescriptor["platform"]["arch"] { + switch (process.arch) { + case "arm64": + return "arm64"; + case "x64": + return "x64"; + default: + return "other"; + } +} + +export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const serverConfig = yield* ServerConfig; + + const readPersistedEnvironmentId = Effect.gen(function* () { + const exists = yield* fileSystem + .exists(serverConfig.environmentIdPath) + .pipe(Effect.orElseSucceed(() => false)); + if (!exists) { + return null; + } + + const raw = yield* fileSystem + .readFileString(serverConfig.environmentIdPath) + .pipe(Effect.map((value) => value.trim())); + + return raw.length > 0 ? raw : null; + }); + + const persistEnvironmentId = (value: string) => + fileSystem.writeFileString(serverConfig.environmentIdPath, `${value}\n`); + + const environmentIdRaw = yield* Effect.gen(function* () { + const persisted = yield* readPersistedEnvironmentId; + if (persisted) { + return persisted; + } + + const generated = yield* Random.nextUUIDv4; + yield* persistEnvironmentId(generated); + return generated; + }); + + const environmentId = EnvironmentId.make(environmentIdRaw); + const cwdBaseName = path.basename(serverConfig.cwd).trim(); + const label = yield* resolveServerEnvironmentLabel({ + cwdBaseName, + }); + + const descriptor: ExecutionEnvironmentDescriptor = { + environmentId, + label, + platform: { + os: platformOs(), + arch: platformArch(), + }, + serverVersion: version, + capabilities: { + repositoryIdentity: true, + }, + }; + + return { + getEnvironmentId: Effect.succeed(environmentId), + getDescriptor: Effect.succeed(descriptor), + } satisfies ServerEnvironmentShape; +}); + +export const ServerEnvironmentLive = Layer.effect(ServerEnvironment, makeServerEnvironment()); diff --git a/apps/server/src/environment/Layers/ServerEnvironmentLabel.test.ts b/apps/server/src/environment/Layers/ServerEnvironmentLabel.test.ts new file mode 100644 index 0000000000..3d44713510 --- /dev/null +++ b/apps/server/src/environment/Layers/ServerEnvironmentLabel.test.ts @@ -0,0 +1,150 @@ +import { afterEach, describe, expect, it } from "@effect/vitest"; +import { Effect, FileSystem } from "effect"; +import { vi } from "vitest"; + +vi.mock("../../processRunner.ts", () => ({ + runProcess: vi.fn(), +})); + +import { runProcess } from "../../processRunner.ts"; +import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts"; + +const mockedRunProcess = vi.mocked(runProcess); +const NoopFileSystemLayer = FileSystem.layerNoop({}); + +afterEach(() => { + mockedRunProcess.mockReset(); +}); + +describe("resolveServerEnvironmentLabel", () => { + it.effect("uses hostname fallback regardless of launch mode", () => + Effect.gen(function* () { + const result = yield* resolveServerEnvironmentLabel({ + cwdBaseName: "t3code", + platform: "win32", + hostname: "macbook-pro", + }).pipe(Effect.provide(NoopFileSystemLayer)); + + expect(result).toBe("macbook-pro"); + }), + ); + + it.effect("prefers the macOS ComputerName", () => + Effect.gen(function* () { + mockedRunProcess.mockResolvedValueOnce({ + stdout: " Julius's MacBook Pro \n", + stderr: "", + code: 0, + signal: null, + timedOut: false, + }); + + const result = yield* resolveServerEnvironmentLabel({ + cwdBaseName: "t3code", + platform: "darwin", + hostname: "macbook-pro", + }).pipe(Effect.provide(NoopFileSystemLayer)); + + expect(result).toBe("Julius's MacBook Pro"); + expect(mockedRunProcess).toHaveBeenCalledWith( + "scutil", + ["--get", "ComputerName"], + expect.objectContaining({ allowNonZeroExit: true }), + ); + }), + ); + + it.effect("prefers Linux PRETTY_HOSTNAME from machine-info", () => + Effect.gen(function* () { + const result = yield* resolveServerEnvironmentLabel({ + cwdBaseName: "t3code", + platform: "linux", + hostname: "buildbox", + }).pipe( + Effect.provide( + FileSystem.layerNoop({ + exists: (path) => Effect.succeed(path === "/etc/machine-info"), + readFileString: (path) => + path === "/etc/machine-info" + ? Effect.succeed('PRETTY_HOSTNAME="Build Agent 01"\nICON_NAME="computer-vm"\n') + : Effect.succeed(""), + }), + ), + ); + + expect(result).toBe("Build Agent 01"); + expect(mockedRunProcess).not.toHaveBeenCalled(); + }), + ); + + it.effect("falls back to hostnamectl pretty hostname on Linux", () => + Effect.gen(function* () { + mockedRunProcess.mockResolvedValueOnce({ + stdout: "CI Runner\n", + stderr: "", + code: 0, + signal: null, + timedOut: false, + }); + + const result = yield* resolveServerEnvironmentLabel({ + cwdBaseName: "t3code", + platform: "linux", + hostname: "runner-01", + }).pipe(Effect.provide(NoopFileSystemLayer)); + + expect(result).toBe("CI Runner"); + expect(mockedRunProcess).toHaveBeenCalledWith( + "hostnamectl", + ["--pretty"], + expect.objectContaining({ allowNonZeroExit: true }), + ); + }), + ); + + it.effect("falls back to the hostname when friendly labels are unavailable", () => + Effect.gen(function* () { + const result = yield* resolveServerEnvironmentLabel({ + cwdBaseName: "t3code", + platform: "win32", + hostname: "JULIUS-LAPTOP", + }).pipe(Effect.provide(NoopFileSystemLayer)); + + expect(result).toBe("JULIUS-LAPTOP"); + }), + ); + + it.effect("falls back to the hostname when the friendly-label command is missing", () => + Effect.gen(function* () { + mockedRunProcess.mockRejectedValueOnce(new Error("spawn scutil ENOENT")); + + const result = yield* resolveServerEnvironmentLabel({ + cwdBaseName: "t3code", + platform: "darwin", + hostname: "macbook-pro", + }).pipe(Effect.provide(NoopFileSystemLayer)); + + expect(result).toBe("macbook-pro"); + }), + ); + + it.effect("falls back to the cwd basename when the hostname is blank", () => + Effect.gen(function* () { + mockedRunProcess.mockResolvedValueOnce({ + stdout: " ", + stderr: "", + code: 0, + signal: null, + timedOut: false, + }); + + const result = yield* resolveServerEnvironmentLabel({ + cwdBaseName: "t3code", + platform: "linux", + hostname: " ", + }).pipe(Effect.provide(NoopFileSystemLayer)); + + expect(result).toBe("t3code"); + }), + ); +}); diff --git a/apps/server/src/environment/Layers/ServerEnvironmentLabel.ts b/apps/server/src/environment/Layers/ServerEnvironmentLabel.ts new file mode 100644 index 0000000000..dc77658326 --- /dev/null +++ b/apps/server/src/environment/Layers/ServerEnvironmentLabel.ts @@ -0,0 +1,106 @@ +import * as OS from "node:os"; + +import { Effect, FileSystem } from "effect"; + +import { runProcess } from "../../processRunner.ts"; + +interface ResolveServerEnvironmentLabelInput { + readonly cwdBaseName: string; + readonly platform?: NodeJS.Platform; + readonly hostname?: string | null; +} + +function normalizeLabel(value: string | null | undefined): string | null { + const trimmed = value?.trim(); + return trimmed && trimmed.length > 0 ? trimmed : null; +} + +function parseMachineInfoValue(raw: string, key: string): string | null { + for (const line of raw.split(/\r?\n/g)) { + const trimmed = line.trim(); + if (trimmed.length === 0 || trimmed.startsWith("#") || !trimmed.startsWith(`${key}=`)) { + continue; + } + const value = trimmed.slice(key.length + 1).trim(); + if ( + (value.startsWith('"') && value.endsWith('"')) || + (value.startsWith("'") && value.endsWith("'")) + ) { + return normalizeLabel(value.slice(1, -1)); + } + return normalizeLabel(value); + } + return null; +} + +const readLinuxMachineInfo = Effect.fn("readLinuxMachineInfo")(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const exists = yield* fileSystem + .exists("/etc/machine-info") + .pipe(Effect.orElseSucceed(() => false)); + if (!exists) { + return null; + } + + return yield* fileSystem + .readFileString("/etc/machine-info") + .pipe(Effect.orElseSucceed(() => null)); +}); + +const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* ( + command: string, + args: readonly string[], +) { + const result = yield* Effect.tryPromise({ + try: () => + runProcess(command, args, { + allowNonZeroExit: true, + }), + catch: () => null, + }).pipe(Effect.orElseSucceed(() => null)); + + if (!result || result.code !== 0) { + return null; + } + + return normalizeLabel(result.stdout); +}); + +const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function* ( + platform: NodeJS.Platform, +) { + if (platform === "darwin") { + return yield* runFriendlyLabelCommand("scutil", ["--get", "ComputerName"]); + } + + if (platform === "linux") { + const machineInfo = normalizeLabel(yield* readLinuxMachineInfo()); + if (machineInfo) { + const prettyHostname = parseMachineInfoValue(machineInfo, "PRETTY_HOSTNAME"); + if (prettyHostname) { + return prettyHostname; + } + } + + return yield* runFriendlyLabelCommand("hostnamectl", ["--pretty"]); + } + + return null; +}); + +export const resolveServerEnvironmentLabel = Effect.fn("resolveServerEnvironmentLabel")(function* ( + input: ResolveServerEnvironmentLabelInput, +) { + const platform = input.platform ?? process.platform; + const friendlyHostLabel = yield* resolveFriendlyHostLabel(platform); + if (friendlyHostLabel) { + return friendlyHostLabel; + } + + const hostname = normalizeLabel(input.hostname ?? OS.hostname()); + if (hostname) { + return hostname; + } + + return normalizeLabel(input.cwdBaseName) ?? "T3 environment"; +}); diff --git a/apps/server/src/environment/Services/ServerEnvironment.ts b/apps/server/src/environment/Services/ServerEnvironment.ts new file mode 100644 index 0000000000..4858680333 --- /dev/null +++ b/apps/server/src/environment/Services/ServerEnvironment.ts @@ -0,0 +1,12 @@ +import type { EnvironmentId, ExecutionEnvironmentDescriptor } from "@t3tools/contracts"; +import { Context } from "effect"; +import type { Effect } from "effect"; + +export interface ServerEnvironmentShape { + readonly getEnvironmentId: Effect.Effect; + readonly getDescriptor: Effect.Effect; +} + +export class ServerEnvironment extends Context.Service()( + "t3/environment/Services/ServerEnvironment", +) {} diff --git a/apps/server/src/git/Errors.ts b/apps/server/src/git/Errors.ts deleted file mode 100644 index 15bf482f7b..0000000000 --- a/apps/server/src/git/Errors.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { Schema } from "effect"; - -/** - * GitCommandError - Git command execution failed. - */ -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}`; - } -} - -/** - * GitHubCliError - GitHub CLI execution or authentication failed. - */ -export class GitHubCliError extends Schema.TaggedErrorClass()("GitHubCliError", { - operation: Schema.String, - detail: Schema.String, - cause: Schema.optional(Schema.Defect), -}) { - override get message(): string { - return `GitHub CLI failed in ${this.operation}: ${this.detail}`; - } -} - -/** - * TextGenerationError - Commit or PR text generation failed. - */ -export class TextGenerationError extends Schema.TaggedErrorClass()( - "TextGenerationError", - { - operation: Schema.String, - detail: Schema.String, - cause: Schema.optional(Schema.Defect), - }, -) { - override get message(): string { - return `Text generation failed in ${this.operation}: ${this.detail}`; - } -} - -/** - * GitManagerError - Stacked Git workflow orchestration failed. - */ -export class GitManagerError extends Schema.TaggedErrorClass()("GitManagerError", { - operation: Schema.String, - detail: Schema.String, - cause: Schema.optional(Schema.Defect), -}) { - override get message(): string { - return `Git manager failed in ${this.operation}: ${this.detail}`; - } -} - -/** - * GitManagerServiceError - Errors emitted by stacked Git workflow orchestration. - */ -export type GitManagerServiceError = - | GitManagerError - | GitCommandError - | GitHubCliError - | TextGenerationError; diff --git a/apps/server/src/git/Layers/ClaudeTextGeneration.ts b/apps/server/src/git/Layers/ClaudeTextGeneration.ts index 19ed40e65b..99ca21b06d 100644 --- a/apps/server/src/git/Layers/ClaudeTextGeneration.ts +++ b/apps/server/src/git/Layers/ClaudeTextGeneration.ts @@ -14,7 +14,7 @@ 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, @@ -66,7 +66,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () { * Spawn the Claude CLI with structured JSON output and return the parsed, * schema-validated result. */ - const runClaudeJson = ({ + const runClaudeJson = Effect.fn("runClaudeJson")(function* ({ operation, cwd, prompt, @@ -82,131 +82,125 @@ const makeClaudeTextGeneration = Effect.gen(function* () { prompt: string; outputSchemaJson: S; modelSelection: ClaudeModelSelection; - }): Effect.Effect => - Effect.gen(function* () { - const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson)); - const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities( - getClaudeModelCapabilities(modelSelection.model), - modelSelection.options, - ); - const settings = { - ...(typeof normalizedOptions?.thinking === "boolean" - ? { alwaysThinkingEnabled: normalizedOptions.thinking } - : {}), - ...(normalizedOptions?.fastMode ? { fastMode: true } : {}), - }; + }): Effect.fn.Return { + const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson)); + const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities( + getClaudeModelCapabilities(modelSelection.model), + modelSelection.options, + ); + const settings = { + ...(typeof normalizedOptions?.thinking === "boolean" + ? { alwaysThinkingEnabled: normalizedOptions.thinking } + : {}), + ...(normalizedOptions?.fastMode ? { fastMode: true } : {}), + }; - const claudeSettings = yield* Effect.map( - serverSettingsService.getSettings, - (settings) => settings.providers.claudeAgent, - ).pipe(Effect.catch(() => Effect.undefined)); + const claudeSettings = yield* Effect.map( + serverSettingsService.getSettings, + (settings) => settings.providers.claudeAgent, + ).pipe(Effect.catch(() => Effect.undefined)); - const runClaudeCommand = Effect.gen(function* () { - const command = ChildProcess.make( - claudeSettings?.binaryPath || "claude", - [ - "-p", - "--output-format", - "json", - "--json-schema", - jsonSchemaStr, - "--model", - resolveApiModelId(modelSelection), - ...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []), - ...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []), - "--dangerously-skip-permissions", - ], - { - cwd, - shell: process.platform === "win32", - stdin: { - stream: Stream.encodeText(Stream.make(prompt)), - }, + const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () { + const command = ChildProcess.make( + claudeSettings?.binaryPath || "claude", + [ + "-p", + "--output-format", + "json", + "--json-schema", + jsonSchemaStr, + "--model", + resolveApiModelId(modelSelection), + ...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []), + ...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []), + "--dangerously-skip-permissions", + ], + { + cwd, + shell: process.platform === "win32", + stdin: { + stream: Stream.encodeText(Stream.make(prompt)), }, + }, + ); + + const child = yield* commandSpawner + .spawn(command) + .pipe( + Effect.mapError((cause) => + normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"), + ), ); - const child = yield* commandSpawner - .spawn(command) - .pipe( + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + readStreamAsString(operation, child.stdout), + readStreamAsString(operation, child.stderr), + child.exitCode.pipe( Effect.mapError((cause) => - normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"), + normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"), ), - ); + ), + ], + { concurrency: "unbounded" }, + ); - const [stdout, stderr, exitCode] = yield* Effect.all( - [ - readStreamAsString(operation, child.stdout), - readStreamAsString(operation, child.stderr), - child.exitCode.pipe( - Effect.mapError((cause) => - normalizeCliError( - "claude", - operation, - cause, - "Failed to read Claude CLI exit code", - ), - ), + if (exitCode !== 0) { + const stderrDetail = stderr.trim(); + const stdoutDetail = stdout.trim(); + const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail; + return yield* new TextGenerationError({ + operation, + detail: + detail.length > 0 + ? `Claude CLI command failed: ${detail}` + : `Claude CLI command failed with code ${exitCode}.`, + }); + } + + return stdout; + }); + + const rawStdout = yield* runClaudeCommand().pipe( + Effect.scoped, + Effect.timeoutOption(CLAUDE_TIMEOUT_MS), + Effect.flatMap( + Option.match({ + onNone: () => + Effect.fail( + new TextGenerationError({ operation, detail: "Claude CLI request timed out." }), ), - ], - { concurrency: "unbounded" }, - ); + onSome: (value) => Effect.succeed(value), + }), + ), + ); - if (exitCode !== 0) { - const stderrDetail = stderr.trim(); - const stdoutDetail = stdout.trim(); - const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail; - return yield* new TextGenerationError({ + const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))( + rawStdout, + ).pipe( + Effect.catchTag("SchemaError", (cause) => + Effect.fail( + new TextGenerationError({ operation, - detail: - detail.length > 0 - ? `Claude CLI command failed: ${detail}` - : `Claude CLI command failed with code ${exitCode}.`, - }); - } - - return stdout; - }); - - const rawStdout = yield* runClaudeCommand.pipe( - Effect.scoped, - Effect.timeoutOption(CLAUDE_TIMEOUT_MS), - Effect.flatMap( - Option.match({ - onNone: () => - Effect.fail( - new TextGenerationError({ operation, detail: "Claude CLI request timed out." }), - ), - onSome: (value) => Effect.succeed(value), + detail: "Claude CLI returned unexpected output format.", + cause, }), ), - ); + ), + ); - const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))( - rawStdout, - ).pipe( - Effect.catchTag("SchemaError", (cause) => - Effect.fail( - new TextGenerationError({ - operation, - detail: "Claude CLI returned unexpected output format.", - cause, - }), - ), + return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe( + Effect.catchTag("SchemaError", (cause) => + Effect.fail( + new TextGenerationError({ + operation, + detail: "Claude returned invalid structured output.", + cause, + }), ), - ); - - return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe( - Effect.catchTag("SchemaError", (cause) => - Effect.fail( - new TextGenerationError({ - operation, - detail: "Claude returned invalid structured output.", - cause, - }), - ), - ), - ); - }); + ), + ); + }); // --------------------------------------------------------------------------- // TextGenerationShape methods diff --git a/apps/server/src/git/Layers/CodexTextGeneration.test.ts b/apps/server/src/git/Layers/CodexTextGeneration.test.ts index 21a97eec9c..a07505f025 100644 --- a/apps/server/src/git/Layers/CodexTextGeneration.test.ts +++ b/apps/server/src/git/Layers/CodexTextGeneration.test.ts @@ -5,7 +5,7 @@ import { expect } from "vitest"; import { ServerConfig } from "../../config.ts"; import { CodexTextGenerationLive } from "./CodexTextGeneration.ts"; -import { TextGenerationError } from "../Errors.ts"; +import { TextGenerationError } from "@t3tools/contracts"; import { TextGeneration } from "../Services/TextGeneration.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; diff --git a/apps/server/src/git/Layers/CodexTextGeneration.ts b/apps/server/src/git/Layers/CodexTextGeneration.ts index 8f0556ee34..52ddf55453 100644 --- a/apps/server/src/git/Layers/CodexTextGeneration.ts +++ b/apps/server/src/git/Layers/CodexTextGeneration.ts @@ -8,7 +8,7 @@ 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, @@ -85,44 +85,43 @@ const makeCodexTextGeneration = Effect.gen(function* () { const safeUnlink = (filePath: string): Effect.Effect => fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void)); - const materializeImageAttachments = ( + const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* ( _operation: | "generateCommitMessage" | "generatePrContent" | "generateBranchName" | "generateThreadTitle", attachments: BranchNameGenerationInput["attachments"], - ): Effect.Effect => - Effect.gen(function* () { - if (!attachments || attachments.length === 0) { - return { imagePaths: [] }; + ): Effect.fn.Return { + if (!attachments || attachments.length === 0) { + return { imagePaths: [] }; + } + + const imagePaths: string[] = []; + for (const attachment of attachments) { + if (attachment.type !== "image") { + continue; } - const imagePaths: string[] = []; - for (const attachment of attachments) { - if (attachment.type !== "image") { - continue; - } - - const resolvedPath = resolveAttachmentPath({ - attachmentsDir: serverConfig.attachmentsDir, - attachment, - }); - if (!resolvedPath || !path.isAbsolute(resolvedPath)) { - continue; - } - const fileInfo = yield* fileSystem - .stat(resolvedPath) - .pipe(Effect.catch(() => Effect.succeed(null))); - if (!fileInfo || fileInfo.type !== "File") { - continue; - } - imagePaths.push(resolvedPath); + const resolvedPath = resolveAttachmentPath({ + attachmentsDir: serverConfig.attachmentsDir, + attachment, + }); + if (!resolvedPath || !path.isAbsolute(resolvedPath)) { + continue; } - return { imagePaths }; - }); + const fileInfo = yield* fileSystem + .stat(resolvedPath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!fileInfo || fileInfo.type !== "File") { + continue; + } + imagePaths.push(resolvedPath); + } + return { imagePaths }; + }); - const runCodexJson = ({ + const runCodexJson = Effect.fn("runCodexJson")(function* ({ operation, cwd, prompt, @@ -142,138 +141,137 @@ const makeCodexTextGeneration = Effect.gen(function* () { imagePaths?: ReadonlyArray; cleanupPaths?: ReadonlyArray; modelSelection: CodexModelSelection; - }): Effect.Effect => - Effect.gen(function* () { - const schemaPath = yield* writeTempFile( - operation, - "codex-schema", - JSON.stringify(toJsonSchemaObject(outputSchemaJson)), + }): Effect.fn.Return { + const schemaPath = yield* writeTempFile( + operation, + "codex-schema", + JSON.stringify(toJsonSchemaObject(outputSchemaJson)), + ); + const outputPath = yield* writeTempFile(operation, "codex-output", ""); + + const codexSettings = yield* Effect.map( + serverSettingsService.getSettings, + (settings) => settings.providers.codex, + ).pipe(Effect.catch(() => Effect.undefined)); + + const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () { + const normalizedOptions = normalizeCodexModelOptionsWithCapabilities( + getCodexModelCapabilities(modelSelection.model), + modelSelection.options, ); - const outputPath = yield* writeTempFile(operation, "codex-output", ""); - - const codexSettings = yield* Effect.map( - serverSettingsService.getSettings, - (settings) => settings.providers.codex, - ).pipe(Effect.catch(() => Effect.undefined)); - - const runCodexCommand = Effect.gen(function* () { - const normalizedOptions = normalizeCodexModelOptionsWithCapabilities( - getCodexModelCapabilities(modelSelection.model), - modelSelection.options, - ); - const reasoningEffort = - modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT; - const command = ChildProcess.make( - codexSettings?.binaryPath || "codex", - [ - "exec", - "--ephemeral", - "-s", - "read-only", - "--model", - modelSelection.model, - "--config", - `model_reasoning_effort="${reasoningEffort}"`, - ...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []), - "--output-schema", - schemaPath, - "--output-last-message", - outputPath, - ...imagePaths.flatMap((imagePath) => ["--image", imagePath]), - "-", - ], - { - env: { - ...process.env, - ...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}), - }, - cwd, - shell: process.platform === "win32", - stdin: { - stream: Stream.encodeText(Stream.make(prompt)), - }, - }, - ); - - const child = yield* commandSpawner - .spawn(command) - .pipe( - Effect.mapError((cause) => - normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"), - ), - ); - - const [stdout, stderr, exitCode] = yield* Effect.all( - [ - readStreamAsString(operation, child.stdout), - readStreamAsString(operation, child.stderr), - child.exitCode.pipe( - Effect.mapError((cause) => - normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"), - ), - ), - ], - { concurrency: "unbounded" }, - ); - - if (exitCode !== 0) { - const stderrDetail = stderr.trim(); - const stdoutDetail = stdout.trim(); - const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail; - return yield* new TextGenerationError({ - operation, - detail: - detail.length > 0 - ? `Codex CLI command failed: ${detail}` - : `Codex CLI command failed with code ${exitCode}.`, - }); - } - }); - - const cleanup = Effect.all( - [schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)), + const reasoningEffort = + modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT; + const command = ChildProcess.make( + codexSettings?.binaryPath || "codex", + [ + "exec", + "--ephemeral", + "-s", + "read-only", + "--model", + modelSelection.model, + "--config", + `model_reasoning_effort="${reasoningEffort}"`, + ...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []), + "--output-schema", + schemaPath, + "--output-last-message", + outputPath, + ...imagePaths.flatMap((imagePath) => ["--image", imagePath]), + "-", + ], { - concurrency: "unbounded", + env: { + ...process.env, + ...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}), + }, + cwd, + shell: process.platform === "win32", + stdin: { + stream: Stream.encodeText(Stream.make(prompt)), + }, }, - ).pipe(Effect.asVoid); + ); - return yield* Effect.gen(function* () { - yield* runCodexCommand.pipe( - Effect.scoped, - Effect.timeoutOption(CODEX_TIMEOUT_MS), - Effect.flatMap( - Option.match({ - onNone: () => - Effect.fail( - new TextGenerationError({ operation, detail: "Codex CLI request timed out." }), - ), - onSome: () => Effect.void, + const child = yield* commandSpawner + .spawn(command) + .pipe( + Effect.mapError((cause) => + normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"), + ), + ); + + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + readStreamAsString(operation, child.stdout), + readStreamAsString(operation, child.stderr), + child.exitCode.pipe( + Effect.mapError((cause) => + normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"), + ), + ), + ], + { concurrency: "unbounded" }, + ); + + if (exitCode !== 0) { + const stderrDetail = stderr.trim(); + const stdoutDetail = stdout.trim(); + const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail; + return yield* new TextGenerationError({ + operation, + detail: + detail.length > 0 + ? `Codex CLI command failed: ${detail}` + : `Codex CLI command failed with code ${exitCode}.`, + }); + } + }); + + const cleanup = Effect.all( + [schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)), + { + concurrency: "unbounded", + }, + ).pipe(Effect.asVoid); + + return yield* Effect.gen(function* () { + yield* runCodexCommand().pipe( + Effect.scoped, + Effect.timeoutOption(CODEX_TIMEOUT_MS), + Effect.flatMap( + Option.match({ + onNone: () => + Effect.fail( + new TextGenerationError({ operation, detail: "Codex CLI request timed out." }), + ), + onSome: () => Effect.void, + }), + ), + ); + + return yield* fileSystem.readFileString(outputPath).pipe( + Effect.mapError( + (cause) => + new TextGenerationError({ + operation, + detail: "Failed to read Codex output file.", + cause, + }), + ), + Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))), + Effect.catchTag("SchemaError", (cause) => + Effect.fail( + new TextGenerationError({ + operation, + detail: "Codex returned invalid structured output.", + cause, }), ), - ); - - return yield* fileSystem.readFileString(outputPath).pipe( - Effect.mapError( - (cause) => - new TextGenerationError({ - operation, - detail: "Failed to read Codex output file.", - cause, - }), - ), - Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))), - Effect.catchTag("SchemaError", (cause) => - Effect.fail( - new TextGenerationError({ - operation, - detail: "Codex returned invalid structured output.", - cause, - }), - ), - ), - ); - }).pipe(Effect.ensuring(cleanup)); - }); + ), + ); + }).pipe(Effect.ensuring(cleanup)); + }); const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn( "CodexTextGeneration.generateCommitMessage", diff --git a/apps/server/src/git/Layers/GitCore.test.ts b/apps/server/src/git/Layers/GitCore.test.ts index 135834f891..8ab541e675 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"; @@ -40,6 +40,24 @@ function writeTextFile( }); } +function removePath( + targetPath: string, +): Effect.Effect { + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + yield* fileSystem.remove(targetPath, { recursive: true, force: true }); + }); +} + +function makeDirectory( + dirPath: string, +): Effect.Effect { + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + yield* fileSystem.makeDirectory(dirPath, { recursive: true }); + }); +} + /** Run a raw git command for test setup (not under test). */ function git( cwd: string, @@ -59,6 +77,23 @@ function git( }); } +function configureRemote( + cwd: string, + remoteName: string, + remotePath: string, + fetchNamespace: string, +): Effect.Effect { + return Effect.gen(function* () { + yield* git(cwd, ["config", `remote.${remoteName}.url`, remotePath]); + return yield* git(cwd, [ + "config", + "--replace-all", + `remote.${remoteName}.fetch`, + `+refs/heads/*:refs/remotes/${fetchNamespace}/*`, + ]); + }); +} + function runShellCommand(input: { command: string; cwd: string; @@ -202,7 +237,10 @@ it.layer(TestLayer)("git integration", (it) => { const seenChunks: string[][] = []; const core = yield* makeIsolatedGitCore((input) => { - if (input.args.join(" ") !== "check-ignore --no-index -z --stdin") { + if ( + input.args.join(" ") !== + "-c core.fsmonitor=false -c core.untrackedCache=false check-ignore --no-index -z --stdin" + ) { return Effect.fail( new GitCommandError({ operation: input.operation, @@ -235,6 +273,35 @@ it.layer(TestLayer)("git integration", (it) => { expect(result).toEqual(expectedPaths); }), ); + + it.effect("listWorkspaceFiles disables fsmonitor and untracked cache helpers", () => + Effect.gen(function* () { + const core = yield* makeIsolatedGitCore((input) => { + expect(input.args).toEqual([ + "-c", + "core.fsmonitor=false", + "-c", + "core.untrackedCache=false", + "ls-files", + "--cached", + "--others", + "--exclude-standard", + "-z", + ]); + return Effect.succeed({ + code: 0, + stdout: "src/index.ts\0README.md\0", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + }); + }); + + const result = yield* core.listWorkspaceFiles("/virtual/repo"); + expect(result.paths).toEqual(["src/index.ts", "README.md"]); + expect(result.truncated).toBe(false); + }), + ); }); // ── listGitBranches ── @@ -250,6 +317,21 @@ it.layer(TestLayer)("git integration", (it) => { }), ); + it.effect("returns isRepo: false for deleted directories", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const deletedDir = path.join(tmp, "deleted-repo"); + yield* makeDirectory(deletedDir); + yield* removePath(deletedDir); + + const result = yield* (yield* GitCore).listBranches({ cwd: deletedDir }); + + expect(result.isRepo).toBe(false); + expect(result.hasOriginRemote).toBe(false); + expect(result.branches).toEqual([]); + }), + ); + it.effect("returns the current branch with current: true", () => Effect.gen(function* () { const tmp = yield* makeTmpDir(); @@ -369,6 +451,94 @@ it.layer(TestLayer)("git integration", (it) => { }), ); + it.effect("paginates branch results and returns paging metadata", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(tmp); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-a" }); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-b" }); + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-c" }); + + const firstPage = yield* (yield* GitCore).listBranches({ cwd: tmp, limit: 2 }); + expect(firstPage.totalCount).toBe(4); + expect(firstPage.nextCursor).toBe(2); + expect(firstPage.branches.map((branch) => branch.name)).toEqual([ + initialBranch, + "feature-a", + ]); + + const secondPage = yield* (yield* GitCore).listBranches({ + cwd: tmp, + cursor: firstPage.nextCursor ?? 0, + limit: 2, + }); + expect(secondPage.totalCount).toBe(4); + expect(secondPage.nextCursor).toBeNull(); + expect(secondPage.branches.map((branch) => branch.name)).toEqual([ + "feature-b", + "feature-c", + ]); + }), + ); + + 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(); @@ -456,6 +626,41 @@ it.layer(TestLayer)("git integration", (it) => { expect(remoteBranch?.remoteName).toBe(remoteName); }), ); + + it.effect( + "filters branch queries before pagination and dedupes origin refs with local matches", + () => + Effect.gen(function* () { + const remote = yield* makeTmpDir(); + const tmp = yield* makeTmpDir(); + + yield* git(remote, ["init", "--bare"]); + const { initialBranch } = yield* initRepoWithCommit(tmp); + yield* git(tmp, ["remote", "add", "origin", remote]); + yield* git(tmp, ["push", "-u", "origin", initialBranch]); + + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/demo" }); + yield* git(tmp, ["push", "-u", "origin", "feature/demo"]); + + yield* git(tmp, ["checkout", "-b", "feature/remote-only"]); + yield* git(tmp, ["push", "-u", "origin", "feature/remote-only"]); + yield* git(tmp, ["checkout", initialBranch]); + yield* git(tmp, ["branch", "-D", "feature/remote-only"]); + + const result = yield* (yield* GitCore).listBranches({ + cwd: tmp, + query: "feature/", + limit: 10, + }); + + expect(result.totalCount).toBe(2); + expect(result.nextCursor).toBeNull(); + expect(result.branches.map((branch) => branch.name)).toEqual([ + "feature/demo", + "origin/feature/remote-only", + ]); + }), + ); }); // ── checkoutGitBranch ── @@ -477,8 +682,8 @@ 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 context = yield* Effect.context(); + const runPromise = Effect.runPromiseWith(context); const remote = yield* makeTmpDir(); const source = yield* makeTmpDir(); @@ -529,7 +734,7 @@ it.layer(TestLayer)("git integration", (it) => { }), ); - it.effect("keeps checkout successful when upstream refresh fails", () => + it.effect("statusDetails remains successful when upstream refresh fails after checkout", () => Effect.gen(function* () { const remote = yield* makeTmpDir(); const source = yield* makeTmpDir(); @@ -554,7 +759,7 @@ it.layer(TestLayer)("git integration", (it) => { const realGitCore = yield* GitCore; let refreshFetchAttempts = 0; const core = yield* makeIsolatedGitCore((input) => { - if (input.args[0] === "fetch") { + if (input.args[0] === "--git-dir" && input.args[2] === "fetch") { refreshFetchAttempts += 1; return Effect.fail( new GitCommandError({ @@ -568,16 +773,15 @@ it.layer(TestLayer)("git integration", (it) => { return realGitCore.execute(input); }); yield* core.checkoutBranch({ cwd: source, branch: featureBranch }); - yield* Effect.promise(() => - vi.waitFor(() => { - expect(refreshFetchAttempts).toBe(1); - }), - ); + const status = yield* core.statusDetails(source); + expect(refreshFetchAttempts).toBe(1); + expect(status.branch).toBe(featureBranch); + expect(status.upstreamRef).toBe(`origin/${featureBranch}`); expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch); }), ); - it.effect("refresh fetch is scoped to the checked out branch upstream refspec", () => + it.effect("defers upstream refresh until statusDetails is requested", () => Effect.gen(function* () { const remote = yield* makeTmpDir(); const source = yield* makeTmpDir(); @@ -599,10 +803,10 @@ it.layer(TestLayer)("git integration", (it) => { yield* git(source, ["checkout", defaultBranch]); const realGitCore = yield* GitCore; - let fetchArgs: readonly string[] | null = null; + let refreshFetchAttempts = 0; const core = yield* makeIsolatedGitCore((input) => { - if (input.args[0] === "fetch") { - fetchArgs = [...input.args]; + if (input.args[0] === "--git-dir" && input.args[2] === "fetch") { + refreshFetchAttempts += 1; return Effect.succeed({ code: 0, stdout: "", @@ -614,73 +818,137 @@ it.layer(TestLayer)("git integration", (it) => { return realGitCore.execute(input); }); yield* core.checkoutBranch({ cwd: source, branch: featureBranch }); - yield* Effect.promise(() => - vi.waitFor(() => { - expect(fetchArgs).not.toBeNull(); - }), - ); - - expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch); - expect(fetchArgs).toEqual([ - "fetch", - "--quiet", - "--no-tags", - "origin", - `+refs/heads/${featureBranch}:refs/remotes/origin/${featureBranch}`, - ]); + yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 50))); + expect(refreshFetchAttempts).toBe(0); + const status = yield* core.statusDetails(source); + expect(status.branch).toBe(featureBranch); + expect(refreshFetchAttempts).toBe(1); }), ); - it.effect("returns checkout result before background upstream refresh completes", () => + it.effect("shares upstream refreshes across worktrees that use the same git common dir", () => Effect.gen(function* () { - const remote = yield* makeTmpDir(); - const source = yield* makeTmpDir(); - yield* git(remote, ["init", "--bare"]); + const ok = (stdout = "") => + Effect.succeed({ + code: 0, + stdout, + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + }); - yield* initRepoWithCommit(source); - const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find( - (branch) => branch.current, - )!.name; - yield* git(source, ["remote", "add", "origin", remote]); - yield* git(source, ["push", "-u", "origin", defaultBranch]); - - const featureBranch = "feature/background-refresh"; - yield* git(source, ["checkout", "-b", featureBranch]); - yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n"); - yield* git(source, ["add", "feature.txt"]); - yield* git(source, ["commit", "-m", "feature base"]); - yield* git(source, ["push", "-u", "origin", featureBranch]); - yield* git(source, ["checkout", defaultBranch]); - - const realGitCore = yield* GitCore; - let fetchStarted = false; - let releaseFetch!: () => void; - const waitForReleasePromise = new Promise((resolve) => { - releaseFetch = resolve; - }); + let fetchCount = 0; const core = yield* makeIsolatedGitCore((input) => { - if (input.args[0] === "fetch") { - fetchStarted = true; - return Effect.promise(() => - waitForReleasePromise.then(() => ({ - code: 0, - stdout: "", - stderr: "", - stdoutTruncated: false, - stderrTruncated: false, - })), + if ( + input.args[0] === "rev-parse" && + input.args[1] === "--abbrev-ref" && + input.args[2] === "--symbolic-full-name" && + input.args[3] === "@{upstream}" + ) { + return ok("origin/main\n"); + } + if (input.args[0] === "remote") { + return ok("origin\n"); + } + if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") { + return ok("/repo/.git\n"); + } + if (input.args[0] === "--git-dir" && input.args[2] === "fetch") { + fetchCount += 1; + expect(input.cwd).toBe("/repo"); + return ok(); + } + if (input.operation === "GitCore.statusDetails.status") { + return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n"); + } + if ( + input.operation === "GitCore.statusDetails.unstagedNumstat" || + input.operation === "GitCore.statusDetails.stagedNumstat" + ) { + return ok(); + } + if (input.operation === "GitCore.statusDetails.defaultRef") { + return ok("refs/remotes/origin/main\n"); + } + return Effect.fail( + new GitCommandError({ + operation: input.operation, + command: `git ${input.args.join(" ")}`, + cwd: input.cwd, + detail: "Unexpected git command in shared refresh cache test.", + }), + ); + }); + + yield* core.statusDetails("/repo/worktrees/main"); + yield* core.statusDetails("/repo/worktrees/pr-123"); + expect(fetchCount).toBe(1); + }), + ); + + it.effect("briefly backs off failed upstream refreshes across sibling worktrees", () => + Effect.gen(function* () { + const ok = (stdout = "") => + Effect.succeed({ + code: 0, + stdout, + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + }); + + let fetchCount = 0; + const core = yield* makeIsolatedGitCore((input) => { + if ( + input.args[0] === "rev-parse" && + input.args[1] === "--abbrev-ref" && + input.args[2] === "--symbolic-full-name" && + input.args[3] === "@{upstream}" + ) { + return ok("origin/main\n"); + } + if (input.args[0] === "remote") { + return ok("origin\n"); + } + if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") { + return ok("/repo/.git\n"); + } + if (input.args[0] === "--git-dir" && input.args[2] === "fetch") { + fetchCount += 1; + return Effect.fail( + new GitCommandError({ + operation: input.operation, + command: `git ${input.args.join(" ")}`, + cwd: input.cwd, + detail: "simulated fetch timeout", + }), ); } - return realGitCore.execute(input); + if (input.operation === "GitCore.statusDetails.status") { + return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n"); + } + if ( + input.operation === "GitCore.statusDetails.unstagedNumstat" || + input.operation === "GitCore.statusDetails.stagedNumstat" + ) { + return ok(); + } + if (input.operation === "GitCore.statusDetails.defaultRef") { + return ok("refs/remotes/origin/main\n"); + } + return Effect.fail( + new GitCommandError({ + operation: input.operation, + command: `git ${input.args.join(" ")}`, + cwd: input.cwd, + detail: "Unexpected git command in refresh failure cooldown test.", + }), + ); }); - yield* core.checkoutBranch({ cwd: source, branch: featureBranch }); - yield* Effect.promise(() => - vi.waitFor(() => { - expect(fetchStarted).toBe(true); - }), - ); - expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch); - releaseFetch(); + + yield* core.statusDetails("/repo/worktrees/main"); + yield* core.statusDetails("/repo/worktrees/pr-123"); + expect(fetchCount).toBe(1); }), ); @@ -721,16 +989,21 @@ it.layer(TestLayer)("git integration", (it) => { it.effect("checks out a remote tracking branch when remote name contains slashes", () => Effect.gen(function* () { const remote = yield* makeTmpDir(); + const prefixRemote = yield* makeTmpDir(); const source = yield* makeTmpDir(); + const prefixFetchNamespace = "prefix-my-org"; + const prefixRemoteName = "my-org"; const remoteName = "my-org/upstream"; const featureBranch = "feature"; yield* git(remote, ["init", "--bare"]); + yield* git(prefixRemote, ["init", "--bare"]); yield* initRepoWithCommit(source); const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find( (branch) => branch.current, )!.name; - yield* git(source, ["remote", "add", remoteName, remote]); + yield* configureRemote(source, prefixRemoteName, prefixRemote, prefixFetchNamespace); + yield* configureRemote(source, remoteName, remote, remoteName); yield* git(source, ["push", "-u", remoteName, defaultBranch]); yield* git(source, ["checkout", "-b", featureBranch]); @@ -741,12 +1014,41 @@ it.layer(TestLayer)("git integration", (it) => { yield* git(source, ["checkout", defaultBranch]); yield* git(source, ["branch", "-D", featureBranch]); - yield* (yield* GitCore).checkoutBranch({ + const checkoutResult = yield* (yield* GitCore).checkoutBranch({ cwd: source, branch: `${remoteName}/${featureBranch}`, }); + expect(checkoutResult.branch).toBe("upstream/feature"); expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature"); + const realGitCore = yield* GitCore; + let fetchArgs: readonly string[] | null = null; + const core = yield* makeIsolatedGitCore((input) => { + if (input.args[0] === "--git-dir" && input.args[2] === "fetch") { + fetchArgs = [...input.args]; + return Effect.succeed({ + code: 0, + stdout: "", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + }); + } + return realGitCore.execute(input); + }); + + const status = yield* core.statusDetails(source); + expect(status.branch).toBe("upstream/feature"); + expect(status.upstreamRef).toBe(`${remoteName}/${featureBranch}`); + expect(fetchArgs).toEqual([ + "--git-dir", + path.join(source, ".git"), + "fetch", + "--quiet", + "--no-tags", + remoteName, + `+refs/heads/${featureBranch}:refs/remotes/${remoteName}/${featureBranch}`, + ]); }), ); @@ -1357,6 +1659,37 @@ it.layer(TestLayer)("git integration", (it) => { }), ); + it.effect("returns a non-repo status for deleted directories", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const deletedDir = path.join(tmp, "deleted-repo"); + yield* makeDirectory(deletedDir); + yield* removePath(deletedDir); + const core = yield* GitCore; + + const status = yield* core.statusDetails(deletedDir); + const localStatus = yield* core.statusDetailsLocal(deletedDir); + + expect(status).toEqual({ + isRepo: false, + hasOriginRemote: false, + isDefaultBranch: false, + branch: null, + upstreamRef: null, + hasWorkingTreeChanges: false, + workingTree: { + files: [], + insertions: 0, + deletions: 0, + }, + hasUpstream: false, + aheadCount: 0, + behindCount: 0, + }); + expect(localStatus).toEqual(status); + }), + ); + it.effect("computes ahead count against base branch when no upstream is configured", () => Effect.gen(function* () { const tmp = yield* makeTmpDir(); @@ -1633,6 +1966,47 @@ it.layer(TestLayer)("git integration", (it) => { }), ); + it.effect("pushes to the tracked upstream when the remote name contains slashes", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const remote = yield* makeTmpDir(); + const prefixRemote = yield* makeTmpDir(); + const prefixFetchNamespace = "prefix-my-org"; + const prefixRemoteName = "my-org"; + const remoteName = "my-org/upstream"; + const featureBranch = "feature/slash-remote-push"; + yield* git(remote, ["init", "--bare"]); + yield* git(prefixRemote, ["init", "--bare"]); + + const { initialBranch } = yield* initRepoWithCommit(tmp); + yield* configureRemote(tmp, prefixRemoteName, prefixRemote, prefixFetchNamespace); + yield* configureRemote(tmp, remoteName, remote, remoteName); + yield* git(tmp, ["push", "-u", remoteName, initialBranch]); + + yield* git(tmp, ["checkout", "-b", featureBranch]); + yield* writeTextFile(path.join(tmp, "feature.txt"), "first revision\n"); + yield* git(tmp, ["add", "feature.txt"]); + yield* git(tmp, ["commit", "-m", "feature base"]); + yield* git(tmp, ["push", "-u", remoteName, featureBranch]); + + yield* writeTextFile(path.join(tmp, "feature.txt"), "second revision\n"); + yield* git(tmp, ["add", "feature.txt"]); + yield* git(tmp, ["commit", "-m", "feature update"]); + + const core = yield* GitCore; + const pushed = yield* core.pushCurrentBranch(tmp, null); + expect(pushed.status).toBe("pushed"); + expect(pushed.setUpstream).toBe(false); + expect(pushed.upstreamBranch).toBe(`${remoteName}/${featureBranch}`); + expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe( + `${remoteName}/${featureBranch}`, + ); + expect(yield* git(tmp, ["ls-remote", "--heads", remoteName, featureBranch])).toContain( + featureBranch, + ); + }), + ); + it.effect("includes command context when worktree removal fails", () => Effect.gen(function* () { const tmp = yield* makeTmpDir(); @@ -1898,7 +2272,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 b94278095a..ce267be2ea 100644 --- a/apps/server/src/git/Layers/GitCore.ts +++ b/apps/server/src/git/Layers/GitCore.ts @@ -18,15 +18,24 @@ import { } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; -import { GitCommandError } from "../Errors.ts"; +import { GitCommandError, type GitBranch } from "@t3tools/contracts"; +import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git"; +import { compactTraceAttributes } from "../../observability/Attributes.ts"; +import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../../observability/Metrics.ts"; import { GitCore, type ExecuteGitProgress, type GitCommitOptions, type GitCoreShape, + type GitStatusDetails, type ExecuteGitInput, type ExecuteGitResult, } from "../Services/GitCore.ts"; +import { + parseRemoteNames, + parseRemoteNamesInGitOrder, + parseRemoteRefWithRemoteNames, +} from "../remoteRefs.ts"; import { ServerConfig } from "../../config.ts"; import { decodeJsonResult } from "@t3tools/shared/schemaJson"; import { limitChunkToByteLimit } from "../../process/outputBuffer"; @@ -40,10 +49,30 @@ 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 WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [ + "-c", + "core.fsmonitor=false", + "-c", + "core.untrackedCache=false", +] as const; const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15); const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5); +const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5); const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048; const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const; +const GIT_LIST_BRANCHES_DEFAULT_LIMIT = 100; +const NON_REPOSITORY_STATUS_DETAILS = Object.freeze({ + isRepo: false, + hasOriginRemote: false, + isDefaultBranch: false, + branch: null, + upstreamRef: null, + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + hasUpstream: false, + aheadCount: 0, + behindCount: 0, +}); type TraceTailState = { processedChars: number; @@ -51,7 +80,7 @@ type TraceTailState = { }; class StatusUpstreamRefreshCacheKey extends Data.Class<{ - cwd: string; + gitCommonDir: string; upstreamRef: string; remoteName: string; upstreamBranch: string; @@ -178,12 +207,38 @@ function parseBranchLine(line: string): { name: string; current: boolean } | nul }; } -function parseRemoteNames(stdout: string): ReadonlyArray { - return stdout - .split("\n") - .map((line) => line.trim()) - .filter((line) => line.length > 0) - .toSorted((a, b) => b.length - a.length); +function filterBranchesForListQuery( + branches: ReadonlyArray, + query?: string, +): ReadonlyArray { + if (!query) { + return branches; + } + + const normalizedQuery = query.toLowerCase(); + return branches.filter((branch) => branch.name.toLowerCase().includes(normalizedQuery)); +} + +function paginateBranches(input: { + branches: ReadonlyArray; + cursor?: number | undefined; + limit?: number | undefined; +}): { + branches: ReadonlyArray; + nextCursor: number | null; + totalCount: number; +} { + const cursor = input.cursor ?? 0; + const limit = input.limit ?? GIT_LIST_BRANCHES_DEFAULT_LIMIT; + const totalCount = input.branches.length; + const branches = input.branches.slice(cursor, cursor + limit); + const nextCursor = cursor + branches.length < totalCount ? cursor + branches.length : null; + + return { + branches, + nextCursor, + totalCount, + }; } function sanitizeRemoteName(value: string): string { @@ -218,30 +273,41 @@ function parseRemoteFetchUrls(stdout: string): Map { return remotes; } -function parseRemoteRefWithRemoteNames( - branchName: string, +function parseUpstreamRefWithRemoteNames( + upstreamRef: string, remoteNames: ReadonlyArray, -): { remoteRef: string; remoteName: string; localBranch: string } | null { - const trimmedBranchName = branchName.trim(); - if (trimmedBranchName.length === 0) return null; - - for (const remoteName of remoteNames) { - const remotePrefix = `${remoteName}/`; - if (!trimmedBranchName.startsWith(remotePrefix)) { - continue; - } - const localBranch = trimmedBranchName.slice(remotePrefix.length).trim(); - if (localBranch.length === 0) { - return null; - } - return { - remoteRef: trimmedBranchName, - remoteName, - localBranch, - }; +): { upstreamRef: string; remoteName: string; upstreamBranch: string } | null { + const parsed = parseRemoteRefWithRemoteNames(upstreamRef, remoteNames); + if (!parsed) { + return null; } - return null; + return { + upstreamRef, + remoteName: parsed.remoteName, + upstreamBranch: parsed.branchName, + }; +} + +function parseUpstreamRefByFirstSeparator( + upstreamRef: string, +): { upstreamRef: string; remoteName: string; upstreamBranch: string } | null { + const separatorIndex = upstreamRef.indexOf("/"); + if (separatorIndex <= 0 || separatorIndex === upstreamRef.length - 1) { + return null; + } + + const remoteName = upstreamRef.slice(0, separatorIndex).trim(); + const upstreamBranch = upstreamRef.slice(separatorIndex + 1).trim(); + if (remoteName.length === 0 || upstreamBranch.length === 0) { + return null; + } + + return { + upstreamRef, + remoteName, + upstreamBranch, + }; } function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null { @@ -307,6 +373,16 @@ function quoteGitCommand(args: ReadonlyArray): string { return `git ${args.join(" ")}`; } +function isMissingGitCwdError(error: GitCommandError): boolean { + const normalized = `${error.detail}\n${error.message}`.toLowerCase(); + return ( + normalized.includes("no such file or directory") || + normalized.includes("notfound: filesystem.access") || + normalized.includes("enoent") || + normalized.includes("not a directory") + ); +} + function toGitCommandError( input: Pick, detail: string, @@ -328,6 +404,18 @@ interface Trace2Monitor { readonly flush: Effect.Effect; } +const nowUnixNano = (): bigint => BigInt(Date.now()) * 1_000_000n; + +const addCurrentSpanEvent = (name: string, attributes: Record) => + Effect.currentSpan.pipe( + Effect.tap((span) => + Effect.sync(() => { + span.event(name, nowUnixNano(), compactTraceAttributes(attributes)); + }), + ), + Effect.catch(() => Effect.void), + ); + function trace2ChildKey(record: Record): string | null { const childId = record.child_id; if (typeof childId === "number" || typeof childId === "string") { @@ -400,6 +488,9 @@ const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* ( if (event === "child_start") { hookStartByChildKey.set(childKey, { hookName, startedAtMs: Date.now() }); + yield* addCurrentSpanEvent("git.hook.started", { + hookName, + }); if (progress.onHookStarted) { yield* progress.onHookStarted(hookName); } @@ -408,12 +499,19 @@ const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* ( if (event === "child_exit") { hookStartByChildKey.delete(childKey); + const code = traceRecord.success.code; + const exitCode = typeof code === "number" && Number.isInteger(code) ? code : null; + const durationMs = started ? Math.max(0, Date.now() - started.startedAtMs) : null; + yield* addCurrentSpanEvent("git.hook.finished", { + hookName: started?.hookName ?? hookName, + exitCode, + durationMs, + }); 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, + exitCode, + durationMs, }); } } @@ -562,13 +660,13 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { const path = yield* Path.Path; const { worktreesDir } = yield* ServerConfig; - let execute: GitCoreShape["execute"]; + let executeRaw: GitCoreShape["execute"]; if (options?.executeOverride) { - execute = options.executeOverride; + executeRaw = options.executeOverride; } else { const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - execute = Effect.fnUntraced(function* (input) { + executeRaw = Effect.fnUntraced(function* (input) { const commandInput = { ...input, args: [...input.args], @@ -669,6 +767,25 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { }); } + const execute: GitCoreShape["execute"] = (input) => + executeRaw(input).pipe( + withMetrics({ + counter: gitCommandsTotal, + timer: gitCommandDuration, + attributes: { + operation: input.operation, + }, + }), + Effect.withSpan(input.operation, { + kind: "client", + attributes: { + "git.operation": input.operation, + "git.cwd": input.cwd, + "git.args_count": input.args.length, + }, + }), + ); + const executeGit = ( operation: string, cwd: string, @@ -790,45 +907,27 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { 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 remoteNames = yield* runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe( + Effect.map(parseRemoteNames), + Effect.catch(() => Effect.succeed>([])), + ); + return ( + parseUpstreamRefWithRemoteNames(upstreamRef, remoteNames) ?? + parseUpstreamRefByFirstSeparator(upstreamRef) + ); }); - 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, + gitCommonDir: string, upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string }, ): Effect.Effect => { const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`; + const fetchCwd = + path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir; return executeGit( "GitCore.fetchUpstreamRefForStatus", - cwd, - ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], + fetchCwd, + ["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], { allowNonZeroExit: true, timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT), @@ -836,10 +935,18 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { ).pipe(Effect.asVoid); }; + const resolveGitCommonDir = Effect.fn("resolveGitCommonDir")(function* (cwd: string) { + const gitCommonDir = yield* runGitStdout("GitCore.resolveGitCommonDir", cwd, [ + "rev-parse", + "--git-common-dir", + ]).pipe(Effect.map((stdout) => stdout.trim())); + return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir); + }); + const refreshStatusUpstreamCacheEntry = Effect.fn("refreshStatusUpstreamCacheEntry")(function* ( cacheKey: StatusUpstreamRefreshCacheKey, ) { - yield* fetchUpstreamRefForStatus(cacheKey.cwd, { + yield* fetchUpstreamRefForStatus(cacheKey.gitCommonDir, { upstreamRef: cacheKey.upstreamRef, remoteName: cacheKey.remoteName, upstreamBranch: cacheKey.upstreamBranch, @@ -847,11 +954,13 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { return true as const; }); - const statusUpstreamRefreshCache = yield* Cache.makeWith({ + const statusUpstreamRefreshCache = yield* Cache.makeWith(refreshStatusUpstreamCacheEntry, { 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), + // Keep successful refreshes warm and briefly back off failed refreshes to avoid retry storms. + timeToLive: (exit) => + Exit.isSuccess(exit) + ? STATUS_UPSTREAM_REFRESH_INTERVAL + : STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN, }); const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* ( @@ -859,10 +968,11 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { ) { const upstream = yield* resolveCurrentUpstream(cwd); if (!upstream) return; + const gitCommonDir = yield* resolveGitCommonDir(cwd); yield* Cache.get( statusUpstreamRefreshCache, new StatusUpstreamRefreshCacheKey({ - cwd, + gitCommonDir, upstreamRef: upstream.upstreamRef, remoteName: upstream.remoteName, upstreamBranch: upstream.upstreamBranch, @@ -870,14 +980,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { ); }); - 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, @@ -917,7 +1019,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { const listRemoteNames = (cwd: string): Effect.Effect, GitCommandError> => runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe( - Effect.map((stdout) => parseRemoteNames(stdout).toReversed()), + Effect.map(parseRemoteNamesInGitOrder), ); const resolvePrimaryRemoteName = Effect.fn("resolvePrimaryRemoteName")(function* (cwd: string) { @@ -1101,17 +1203,56 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { return branchLastCommit; }); - const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) { - yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true })); + const readStatusDetailsLocal = Effect.fn("readStatusDetailsLocal")(function* (cwd: string) { + const statusResult = yield* executeGit( + "GitCore.statusDetails.status", + cwd, + ["status", "--porcelain=2", "--branch"], + { + allowNonZeroExit: true, + }, + ).pipe(Effect.catchIf(isMissingGitCwdError, () => Effect.succeed(null))); - 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" }, - ); + if (statusResult === null) { + return NON_REPOSITORY_STATUS_DETAILS; + } + + if (statusResult.code !== 0) { + const stderr = statusResult.stderr.trim(); + return yield* createGitCommandError( + "GitCore.statusDetails.status", + cwd, + ["status", "--porcelain=2", "--branch"], + stderr || "git status failed", + ); + } + + const [unstagedNumstatStdout, stagedNumstatStdout, defaultRefResult, hasOriginRemote] = + yield* Effect.all( + [ + runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]), + runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, [ + "diff", + "--cached", + "--numstat", + ]), + executeGit( + "GitCore.statusDetails.defaultRef", + cwd, + ["symbolic-ref", "refs/remotes/origin/HEAD"], + { + allowNonZeroExit: true, + }, + ), + originRemoteExists(cwd).pipe(Effect.catch(() => Effect.succeed(false))), + ], + { concurrency: "unbounded" }, + ); + const statusStdout = statusResult.stdout; + const defaultBranch = + defaultRefResult.code === 0 + ? defaultRefResult.stdout.trim().replace(/^refs\/remotes\/origin\//, "") + : null; let branch: string | null = null; let upstreamRef: string | null = null; @@ -1179,6 +1320,12 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { files.sort((a, b) => a.path.localeCompare(b.path)); return { + isRepo: true, + hasOriginRemote, + isDefaultBranch: + branch !== null && + (branch === defaultBranch || + (defaultBranch === null && (branch === "main" || branch === "master"))), branch, upstreamRef, hasWorkingTreeChanges, @@ -1193,9 +1340,26 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { }; }); + const statusDetailsLocal: GitCoreShape["statusDetailsLocal"] = Effect.fn("statusDetailsLocal")( + function* (cwd) { + return yield* readStatusDetailsLocal(cwd); + }, + ); + + const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) { + yield* refreshStatusUpstreamIfStale(cwd).pipe( + Effect.catchIf(isMissingGitCwdError, () => Effect.void), + Effect.ignoreCause({ log: true }), + ); + return yield* readStatusDetailsLocal(cwd); + }); + const status: GitCoreShape["status"] = (input) => statusDetails(input.cwd).pipe( Effect.map((details) => ({ + isRepo: details.isRepo, + hasOriginRemote: details.hasOriginRemote, + isDefaultBranch: details.isDefaultBranch, branch: details.branch, hasWorkingTreeChanges: details.hasWorkingTreeChanges, workingTree: details.workingTree, @@ -1344,7 +1508,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { "push", "-u", publishRemoteName, - branch, + `HEAD:refs/heads/${branch}`, ]); return { status: "pushed" as const, @@ -1488,7 +1652,14 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { executeGit( "GitCore.listWorkspaceFiles", cwd, - ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], + [ + ...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, + "ls-files", + "--cached", + "--others", + "--exclude-standard", + "-z", + ], { allowNonZeroExit: true, timeoutMs: 20_000, @@ -1506,7 +1677,14 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { createGitCommandError( "GitCore.listWorkspaceFiles", cwd, - ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], + [ + ...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, + "ls-files", + "--cached", + "--others", + "--exclude-standard", + "-z", + ], result.stderr.trim().length > 0 ? result.stderr.trim() : "git ls-files failed", ), ), @@ -1526,7 +1704,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { const result = yield* executeGit( "GitCore.filterIgnoredPaths", cwd, - ["check-ignore", "--no-index", "-z", "--stdin"], + [...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"], { stdin: `${chunk.join("\0")}\0`, allowNonZeroExit: true, @@ -1540,7 +1718,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { return yield* createGitCommandError( "GitCore.filterIgnoredPaths", cwd, - ["check-ignore", "--no-index", "-z", "--stdin"], + [...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"], result.stderr.trim().length > 0 ? result.stderr.trim() : "git check-ignore failed", ); } @@ -1564,22 +1742,38 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { const localBranchResult = yield* executeGit( "GitCore.listBranches.branchNoColor", input.cwd, - ["branch", "--no-color"], + ["branch", "--no-color", "--no-column"], { timeoutMs: 10_000, allowNonZeroExit: true, }, + ).pipe( + Effect.catchIf(isMissingGitCwdError, () => + Effect.succeed({ + code: 128, + stdout: "", + stderr: "fatal: not a git repository", + stdoutTruncated: false, + stderrTruncated: false, + }), + ), ); if (localBranchResult.code !== 0) { const stderr = localBranchResult.stderr.trim(); if (stderr.toLowerCase().includes("not a git repository")) { - return { branches: [], isRepo: false, hasOriginRemote: false }; + return { + branches: [], + isRepo: false, + hasOriginRemote: false, + nextCursor: null, + totalCount: 0, + }; } return yield* createGitCommandError( "GitCore.listBranches", input.cwd, - ["branch", "--no-color"], + ["branch", "--no-color", "--no-column"], stderr || "git branch failed", ); } @@ -1587,7 +1781,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { const remoteBranchResultEffect = executeGit( "GitCore.listBranches.remoteBranches", input.cwd, - ["branch", "--no-color", "--remotes"], + ["branch", "--no-color", "--no-column", "--remotes"], { timeoutMs: 10_000, allowNonZeroExit: true, @@ -1738,9 +1932,22 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { }) : []; - const branches = [...localBranches, ...remoteBranches]; + const branches = paginateBranches({ + branches: filterBranchesForListQuery( + dedupeRemoteBranchesWithLocalMatches([...localBranches, ...remoteBranches]), + input.query, + ), + cursor: input.cursor, + limit: input.limit, + }); - return { branches, isRepo: true, hasOriginRemote: remoteNames.includes("origin") }; + return { + branches: [...branches.branches], + isRepo: true, + hasOriginRemote: remoteNames.includes("origin"), + nextCursor: branches.nextCursor, + totalCount: branches.totalCount, + }; }); const createWorktree: GitCoreShape["createWorktree"] = Effect.fn("createWorktree")( @@ -1832,7 +2039,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { "GitCore.removeWorktree", input.cwd, args, - `${commandLabel(args)} failed (cwd: ${input.cwd}): ${error instanceof Error ? error.message : String(error)}`, + `${commandLabel(args)} failed (cwd: ${input.cwd}): ${error.message}`, error, ), ), @@ -1859,12 +2066,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { 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( @@ -1938,13 +2139,27 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { 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 branch = yield* runGitStdout("GitCore.checkoutBranch.currentBranch", input.cwd, [ + "branch", + "--show-current", + ]).pipe(Effect.map((stdout) => stdout.trim() || null)); + + return { branch }; }, ); + const createBranch: GitCoreShape["createBranch"] = Effect.fn("createBranch")(function* (input) { + yield* executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], { + timeoutMs: 10_000, + fallbackErrorMessage: "git branch create failed", + }); + if (input.checkout) { + yield* checkoutBranch({ cwd: input.cwd, branch: input.branch }); + } + + return { branch: input.branch }; + }); + const initRepo: GitCoreShape["initRepo"] = (input) => executeGit("GitCore.initRepo", input.cwd, ["init"], { timeoutMs: 10_000, @@ -1955,6 +2170,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { runGitStdout("GitCore.listLocalBranchNames", cwd, [ "branch", "--list", + "--no-column", "--format=%(refname:short)", ]).pipe( Effect.map((stdout) => @@ -1969,6 +2185,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { execute, status, statusDetails, + statusDetailsLocal, prepareCommitContext, commit, pushCurrentBranch, diff --git a/apps/server/src/git/Layers/GitHubCli.test.ts b/apps/server/src/git/Layers/GitHubCli.test.ts index aafc796db3..0ee4b3f09a 100644 --- a/apps/server/src/git/Layers/GitHubCli.test.ts +++ b/apps/server/src/git/Layers/GitHubCli.test.ts @@ -76,6 +76,105 @@ layer("GitHubCliLive", (it) => { }), ); + it.effect("trims pull request fields decoded from gh json", () => + Effect.gen(function* () { + mockedRunProcess.mockResolvedValueOnce({ + stdout: JSON.stringify({ + number: 42, + title: " Add PR thread creation \n", + url: " https://github.com/pingdotgg/codething-mvp/pull/42 ", + baseRefName: " main ", + headRefName: "\tfeature/pr-threads\t", + state: "OPEN", + mergedAt: null, + isCrossRepository: true, + headRepository: { + nameWithOwner: " octocat/codething-mvp ", + }, + headRepositoryOwner: { + login: " octocat ", + }, + }), + stderr: "", + code: 0, + signal: null, + timedOut: false, + }); + + const result = yield* Effect.gen(function* () { + const gh = yield* GitHubCli; + return yield* gh.getPullRequest({ + cwd: "/repo", + reference: "#42", + }); + }); + + assert.deepStrictEqual(result, { + number: 42, + title: "Add PR thread creation", + url: "https://github.com/pingdotgg/codething-mvp/pull/42", + baseRefName: "main", + headRefName: "feature/pr-threads", + state: "open", + isCrossRepository: true, + headRepositoryNameWithOwner: "octocat/codething-mvp", + headRepositoryOwnerLogin: "octocat", + }); + }), + ); + + it.effect("skips invalid entries when parsing pr lists", () => + Effect.gen(function* () { + mockedRunProcess.mockResolvedValueOnce({ + stdout: JSON.stringify([ + { + number: 0, + title: "invalid", + url: "https://github.com/pingdotgg/codething-mvp/pull/0", + baseRefName: "main", + headRefName: "feature/invalid", + }, + { + number: 43, + title: " Valid PR ", + url: " https://github.com/pingdotgg/codething-mvp/pull/43 ", + baseRefName: " main ", + headRefName: " feature/pr-list ", + headRepository: { + nameWithOwner: " ", + }, + headRepositoryOwner: { + login: " ", + }, + }, + ]), + stderr: "", + code: 0, + signal: null, + timedOut: false, + }); + + const result = yield* Effect.gen(function* () { + const gh = yield* GitHubCli; + return yield* gh.listOpenPullRequests({ + cwd: "/repo", + headSelector: "feature/pr-list", + }); + }); + + assert.deepStrictEqual(result, [ + { + number: 43, + title: "Valid PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/43", + baseRefName: "main", + headRefName: "feature/pr-list", + state: "open", + }, + ]); + }), + ); + it.effect("reads repository clone URLs", () => Effect.gen(function* () { mockedRunProcess.mockResolvedValueOnce({ diff --git a/apps/server/src/git/Layers/GitHubCli.ts b/apps/server/src/git/Layers/GitHubCli.ts index 80ce43659e..1a687b0e8d 100644 --- a/apps/server/src/git/Layers/GitHubCli.ts +++ b/apps/server/src/git/Layers/GitHubCli.ts @@ -1,14 +1,18 @@ -import { Effect, Layer, Schema } from "effect"; -import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts"; +import { Effect, Layer, Result, Schema, SchemaIssue } from "effect"; +import { TrimmedNonEmptyString } from "@t3tools/contracts"; import { runProcess } from "../../processRunner"; -import { GitHubCliError } from "../Errors.ts"; +import { GitHubCliError } from "@t3tools/contracts"; import { GitHubCli, type GitHubRepositoryCloneUrls, type GitHubCliShape, - type GitHubPullRequestSummary, } from "../Services/GitHubCli.ts"; +import { + decodeGitHubPullRequestJson, + decodeGitHubPullRequestListJson, + formatGitHubJsonDecodeError, +} from "../githubPullRequests.ts"; const DEFAULT_TIMEOUT_MS = 30_000; @@ -63,76 +67,12 @@ function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown }); } -function normalizePullRequestState(input: { - state?: string | null | undefined; - mergedAt?: string | null | undefined; -}): "open" | "closed" | "merged" { - const mergedAt = input.mergedAt; - const state = input.state; - if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") { - return "merged"; - } - if (state === "CLOSED") { - return "closed"; - } - return "open"; -} - -const RawGitHubPullRequestSchema = Schema.Struct({ - number: PositiveInt, - title: TrimmedNonEmptyString, - url: TrimmedNonEmptyString, - baseRefName: TrimmedNonEmptyString, - headRefName: TrimmedNonEmptyString, - state: Schema.optional(Schema.NullOr(Schema.String)), - mergedAt: Schema.optional(Schema.NullOr(Schema.String)), - isCrossRepository: Schema.optional(Schema.Boolean), - headRepository: Schema.optional( - Schema.NullOr( - Schema.Struct({ - nameWithOwner: Schema.String, - }), - ), - ), - headRepositoryOwner: Schema.optional( - Schema.NullOr( - Schema.Struct({ - login: Schema.String, - }), - ), - ), -}); - const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({ nameWithOwner: TrimmedNonEmptyString, url: TrimmedNonEmptyString, sshUrl: TrimmedNonEmptyString, }); -function normalizePullRequestSummary( - raw: Schema.Schema.Type, -): GitHubPullRequestSummary { - const headRepositoryNameWithOwner = raw.headRepository?.nameWithOwner ?? null; - const headRepositoryOwnerLogin = - raw.headRepositoryOwner?.login ?? - (typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/") - ? (headRepositoryNameWithOwner.split("/")[0] ?? null) - : null); - return { - number: raw.number, - title: raw.title, - url: raw.url, - baseRefName: raw.baseRefName, - headRefName: raw.headRefName, - state: normalizePullRequestState(raw), - ...(typeof raw.isCrossRepository === "boolean" - ? { isCrossRepository: raw.isCrossRepository } - : {}), - ...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}), - ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), - }; -} - function normalizeRepositoryCloneUrls( raw: Schema.Schema.Type, ): GitHubRepositoryCloneUrls { @@ -154,7 +94,7 @@ function decodeGitHubJson( (error) => new GitHubCliError({ operation, - detail: error instanceof Error ? `${invalidDetail}: ${error.message}` : invalidDetail, + detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`, cause: error, }), ), @@ -187,21 +127,31 @@ const makeGitHubCli = Effect.sync(() => { "--limit", String(input.limit ?? 1), "--json", - "number,title,url,baseRefName,headRefName", + "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner", ], }).pipe( Effect.map((result) => result.stdout.trim()), Effect.flatMap((raw) => raw.length === 0 ? Effect.succeed([]) - : decodeGitHubJson( - raw, - Schema.Array(RawGitHubPullRequestSchema), - "listOpenPullRequests", - "GitHub CLI returned invalid PR list JSON.", + : Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe( + Effect.flatMap((decoded) => { + if (!Result.isSuccess(decoded)) { + return Effect.fail( + new GitHubCliError({ + operation: "listOpenPullRequests", + detail: `GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`, + cause: decoded.failure, + }), + ); + } + + return Effect.succeed( + decoded.success.map(({ updatedAt: _updatedAt, ...summary }) => summary), + ); + }), ), ), - Effect.map((pullRequests) => pullRequests.map(normalizePullRequestSummary)), ), getPullRequest: (input) => execute({ @@ -216,14 +166,24 @@ const makeGitHubCli = Effect.sync(() => { }).pipe( Effect.map((result) => result.stdout.trim()), Effect.flatMap((raw) => - decodeGitHubJson( - raw, - RawGitHubPullRequestSchema, - "getPullRequest", - "GitHub CLI returned invalid pull request JSON.", + Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe( + Effect.flatMap((decoded) => { + if (!Result.isSuccess(decoded)) { + return Effect.fail( + new GitHubCliError({ + operation: "getPullRequest", + detail: `GitHub CLI returned invalid pull request JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`, + cause: decoded.failure, + }), + ); + } + + return Effect.succeed( + (({ updatedAt: _updatedAt, ...summary }) => summary)(decoded.success), + ); + }), ), ), - Effect.map(normalizePullRequestSummary), ), getRepositoryCloneUrls: (input) => execute({ diff --git a/apps/server/src/git/Layers/GitManager.test.ts b/apps/server/src/git/Layers/GitManager.test.ts index db82ea4c72..fd991273d1 100644 --- a/apps/server/src/git/Layers/GitManager.test.ts +++ b/apps/server/src/git/Layers/GitManager.test.ts @@ -6,9 +6,14 @@ 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, ModelSelection } from "@t3tools/contracts"; +import type { + GitActionProgressEvent, + GitPreparePullRequestThreadInput, + ModelSelection, + ThreadId, +} 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, @@ -21,10 +26,16 @@ import { GitCore } from "../Services/GitCore.ts"; import { makeGitManager } from "./GitManager.ts"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; +import { + ProjectSetupScriptRunner, + type ProjectSetupScriptRunnerInput, + type ProjectSetupScriptRunnerShape, +} from "../../project/Services/ProjectSetupScriptRunner.ts"; interface FakeGhScenario { prListSequence?: string[]; prListByHeadSelector?: Record; + prListSequenceByHeadSelector?: Record; createdPrUrl?: string; defaultBranch?: string; pullRequest?: { @@ -77,6 +88,72 @@ interface FakeGitTextGeneration { type FakePullRequest = NonNullable; +function normalizeFakePullRequestSummary(raw: unknown): GitHubPullRequestSummary | null { + if (!raw || typeof raw !== "object") { + return null; + } + + const record = raw as Record; + const number = record.number; + const title = record.title; + const url = record.url; + const baseRefName = record.baseRefName; + const headRefName = record.headRefName; + const headRepository = + typeof record.headRepository === "object" && record.headRepository !== null + ? (record.headRepository as Record) + : null; + const headRepositoryOwner = + typeof record.headRepositoryOwner === "object" && record.headRepositoryOwner !== null + ? (record.headRepositoryOwner as Record) + : null; + + if ( + typeof number !== "number" || + typeof title !== "string" || + typeof url !== "string" || + typeof baseRefName !== "string" || + typeof headRefName !== "string" + ) { + return null; + } + + const state = + typeof record.state === "string" + ? record.state === "OPEN" || record.state === "open" + ? "open" + : record.state === "CLOSED" || record.state === "closed" + ? "closed" + : "merged" + : undefined; + const isCrossRepository = + typeof record.isCrossRepository === "boolean" ? record.isCrossRepository : undefined; + const headRepositoryNameWithOwner = + typeof record.headRepositoryNameWithOwner === "string" + ? record.headRepositoryNameWithOwner + : typeof headRepository?.nameWithOwner === "string" + ? headRepository.nameWithOwner + : undefined; + const headRepositoryOwnerLogin = + typeof record.headRepositoryOwnerLogin === "string" + ? record.headRepositoryOwnerLogin + : typeof headRepositoryOwner?.login === "string" + ? headRepositoryOwner.login + : undefined; + + return { + number, + title, + url, + baseRefName, + headRefName, + ...(state ? { state } : {}), + ...(isCrossRepository !== undefined ? { isCrossRepository } : {}), + ...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}), + ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), + }; +} + function runGitSyncForFakeGh(cwd: string, args: readonly string[]): void { const result = spawnSync("git", args, { cwd, @@ -109,6 +186,24 @@ function makeTempDir( }); } +function removePath( + targetPath: string, +): Effect.Effect { + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + yield* fileSystem.remove(targetPath, { recursive: true, force: true }); + }); +} + +function makeDirectory( + dirPath: string, +): Effect.Effect { + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + yield* fileSystem.makeDirectory(dirPath, { recursive: true }); + }); +} + function runGit( cwd: string, args: readonly string[], @@ -159,6 +254,23 @@ function createBareRemote(): Effect.Effect< }); } +function configureRemote( + cwd: string, + remoteName: string, + remotePath: string, + fetchNamespace: string, +): Effect.Effect { + return Effect.gen(function* () { + yield* runGit(cwd, ["config", `remote.${remoteName}.url`, remotePath]); + yield* runGit(cwd, [ + "config", + "--replace-all", + `remote.${remoteName}.fetch`, + `+refs/heads/*:refs/remotes/${fetchNamespace}/*`, + ]); + }); +} + function createTextGeneration(overrides: Partial = {}): TextGenerationShape { const implementation: FakeGitTextGeneration = { generateCommitMessage: (input) => @@ -236,6 +348,12 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): { ghCalls: string[]; } { const prListQueue = [...(scenario.prListSequence ?? [])]; + const prListQueueByHeadSelector = new Map( + Object.entries(scenario.prListSequenceByHeadSelector ?? {}).map(([headSelector, values]) => [ + headSelector, + [...values], + ]), + ); const ghCalls: string[] = []; const execute: GitHubCliShape["execute"] = (input) => { @@ -252,11 +370,15 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): { headSelectorIndex >= 0 && headSelectorIndex < args.length - 1 ? args[headSelectorIndex + 1] : undefined; + const mappedQueue = + typeof headSelector === "string" + ? prListQueueByHeadSelector.get(headSelector)?.shift() + : undefined; const mappedStdout = typeof headSelector === "string" ? scenario.prListByHeadSelector?.[headSelector] : undefined; - const stdout = (mappedStdout ?? prListQueue.shift() ?? "[]") + "\n"; + const stdout = (mappedQueue ?? mappedStdout ?? prListQueue.shift() ?? "[]") + "\n"; return Effect.succeed({ stdout, stderr: "", @@ -410,11 +532,14 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): { "--limit", String(input.limit ?? 1), "--json", - "number,title,url,baseRefName,headRefName", + "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner", ], }).pipe( - Effect.map( - (result) => JSON.parse(result.stdout) as ReadonlyArray, + Effect.map((result) => JSON.parse(result.stdout) as unknown[]), + Effect.map((raw) => + raw + .map((entry) => normalizeFakePullRequestSummary(entry)) + .filter((entry): entry is GitHubPullRequestSummary => entry !== null), ), ), createPullRequest: (input) => @@ -473,7 +598,7 @@ function runStackedAction( manager: GitManagerShape, input: { cwd: string; - action: "commit" | "commit_push" | "commit_push_pr"; + action: "commit" | "push" | "create_pr" | "commit_push" | "commit_push_pr"; actionId?: string; commitMessage?: string; featureBranch?: boolean; @@ -496,7 +621,7 @@ function resolvePullRequest(manager: GitManagerShape, input: { cwd: string; refe function preparePullRequestThread( manager: GitManagerShape, - input: { cwd: string; reference: string; mode: "local" | "worktree" }, + input: GitPreparePullRequestThreadInput, ) { return manager.preparePullRequestThread(input); } @@ -504,6 +629,7 @@ function preparePullRequestThread( function makeManager(input?: { ghScenario?: FakeGhScenario; textGeneration?: Partial; + setupScriptRunner?: ProjectSetupScriptRunnerShape; }) { const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario); const textGeneration = createTextGeneration(input?.textGeneration); @@ -521,6 +647,12 @@ function makeManager(input?: { const managerLayer = Layer.mergeAll( Layer.succeed(GitHubCli, gitHubCli), Layer.succeed(TextGeneration, textGeneration), + Layer.succeed( + ProjectSetupScriptRunner, + input?.setupScriptRunner ?? { + runForThread: () => Effect.succeed({ status: "no-script" as const }), + }, + ), gitCoreLayer, serverSettingsLayer, ).pipe(Layer.provideMerge(NodeServices.layer)); @@ -531,6 +663,8 @@ function makeManager(input?: { ); } +const asThreadId = (threadId: string) => threadId as ThreadId; + const GitManagerTestLayer = GitCoreLive.pipe( Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })), Layer.provideMerge(NodeServices.layer), @@ -563,6 +697,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { }); const status = yield* manager.status({ cwd: repoDir }); + expect(status.isRepo).toBe(true); + expect(status.hasOriginRemote).toBe(true); + expect(status.isDefaultBranch).toBe(false); expect(status.branch).toBe("feature/status-open-pr"); expect(status.pr).toEqual({ number: 13, @@ -575,6 +712,271 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { }), ); + it.effect("status trims PR metadata returned by gh before publishing it", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/status-trimmed-pr"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-trimmed-pr"]); + + const { manager } = yield* makeManager({ + ghScenario: { + prListSequence: [ + JSON.stringify([ + { + number: 14, + title: " Existing PR title \n", + url: " https://github.com/pingdotgg/codething-mvp/pull/14 ", + baseRefName: " main ", + headRefName: "\tfeature/status-trimmed-pr\t", + }, + ]), + ], + }, + }); + + const status = yield* manager.status({ cwd: repoDir }); + + expect(status.pr).toEqual({ + number: 14, + title: "Existing PR title", + url: "https://github.com/pingdotgg/codething-mvp/pull/14", + baseBranch: "main", + headBranch: "feature/status-trimmed-pr", + state: "open", + }); + }), + ); + + it.effect("status ignores invalid gh pr list entries and keeps valid ones", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/status-valid-pr-entry"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-valid-pr-entry"]); + + const { manager } = yield* makeManager({ + ghScenario: { + prListSequence: [ + JSON.stringify([ + { + number: 0, + title: "invalid", + url: "https://github.com/pingdotgg/codething-mvp/pull/0", + baseRefName: "main", + headRefName: "feature/invalid", + }, + { + number: 15, + title: " Valid PR title ", + url: " https://github.com/pingdotgg/codething-mvp/pull/15 ", + baseRefName: " main ", + headRefName: "\tfeature/status-valid-pr-entry\t", + headRepository: { + nameWithOwner: " ", + }, + headRepositoryOwner: { + login: " ", + }, + }, + ]), + ], + }, + }); + + const status = yield* manager.status({ cwd: repoDir }); + + expect(status.pr).toEqual({ + number: 15, + title: "Valid PR title", + url: "https://github.com/pingdotgg/codething-mvp/pull/15", + baseBranch: "main", + headBranch: "feature/status-valid-pr-entry", + state: "open", + }); + }), + ); + + it.effect("status preserves lowercase merged and closed PR states from gh json", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/status-lowercase-state"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-lowercase-state"]); + + const { manager } = yield* makeManager({ + ghScenario: { + prListSequence: [ + JSON.stringify([ + { + number: 16, + title: "Closed PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/16", + baseRefName: "main", + headRefName: "feature/status-lowercase-state", + state: "closed", + updatedAt: "2026-01-01T00:00:00.000Z", + }, + { + number: 17, + title: "Merged PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/17", + baseRefName: "main", + headRefName: "feature/status-lowercase-state", + state: "merged", + updatedAt: "2026-01-02T00:00:00.000Z", + }, + ]), + ], + }, + }); + + const status = yield* manager.status({ cwd: repoDir }); + + expect(status.pr).toEqual({ + number: 17, + title: "Merged PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/17", + baseBranch: "main", + headBranch: "feature/status-lowercase-state", + state: "merged", + }); + }), + ); + + it.effect("status returns an explicit non-repo result for non-git directories", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir("t3code-git-manager-non-repo-"); + const { manager } = yield* makeManager(); + + const status = yield* manager.status({ cwd }); + + expect(status).toEqual({ + isRepo: false, + hasOriginRemote: false, + isDefaultBranch: false, + branch: null, + hasWorkingTreeChanges: false, + workingTree: { + files: [], + insertions: 0, + deletions: 0, + }, + hasUpstream: false, + aheadCount: 0, + behindCount: 0, + pr: null, + }); + }), + ); + + it.effect("status returns an explicit non-repo result for deleted directories", () => + Effect.gen(function* () { + const rootDir = yield* makeTempDir("t3code-git-manager-missing-dir-"); + const cwd = path.join(rootDir, "deleted-repo"); + yield* makeDirectory(cwd); + yield* removePath(cwd); + const { manager } = yield* makeManager(); + + const status = yield* manager.status({ cwd }); + + expect(status).toEqual({ + isRepo: false, + hasOriginRemote: false, + isDefaultBranch: false, + branch: null, + hasWorkingTreeChanges: false, + workingTree: { + files: [], + insertions: 0, + deletions: 0, + }, + hasUpstream: false, + aheadCount: 0, + behindCount: 0, + pr: null, + }); + }), + ); + + it.effect("status briefly caches repeated lookups for the same cwd", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/status-cache"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-cache"]); + + const existingPr = { + number: 113, + title: "Cached PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/113", + baseRefName: "main", + headRefName: "feature/status-cache", + }; + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + prListSequence: [JSON.stringify([existingPr]), JSON.stringify([existingPr])], + }, + }); + + const first = yield* manager.status({ cwd: repoDir }); + const second = yield* manager.status({ cwd: repoDir }); + + expect(first.pr?.number).toBe(113); + expect(second.pr?.number).toBe(113); + expect(ghCalls.filter((call) => call.startsWith("pr list "))).toHaveLength(1); + }), + ); + + it.effect( + "status ignores unrelated fork PRs when the current branch tracks the same repository", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + + const { manager } = yield* makeManager({ + ghScenario: { + prListSequence: [ + JSON.stringify([ + { + number: 1661, + title: "Fork PR from main", + url: "https://github.com/pingdotgg/t3code/pull/1661", + baseRefName: "main", + headRefName: "main", + state: "OPEN", + updatedAt: "2026-04-01T15:00:00Z", + isCrossRepository: true, + headRepository: { + nameWithOwner: "lnieuwenhuis/t3code", + }, + headRepositoryOwner: { + login: "lnieuwenhuis", + }, + }, + ]), + ], + }, + }); + + const status = yield* manager.status({ cwd: repoDir }); + expect(status.branch).toBe("main"); + expect(status.pr).toBeNull(); + }), + ); + it.effect( "status detects cross-repo PRs from the upstream remote URL owner", () => @@ -610,6 +1012,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { headRefName: "statemachine", state: "OPEN", updatedAt: "2026-03-10T07:00:00Z", + isCrossRepository: true, + headRepository: { + nameWithOwner: "jasonLaster/codething-mvp", + }, + headRepositoryOwner: { + login: "jasonLaster", + }, }, ]), ], @@ -627,10 +1036,118 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { state: "open", }); expect(ghCalls).toContain( - "pr list --head jasonLaster:statemachine --state all --limit 20 --json number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt", + "pr list --head jasonLaster:statemachine --state all --limit 20 --json number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner", ); }), - 12_000, + 20_000, + ); + + it.effect( + "status ignores synthetic local branch aliases when the upstream remote name contains slashes", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const originDir = yield* createBareRemote(); + const upstreamDir = yield* createBareRemote(); + yield* configureRemote(repoDir, "origin", originDir, "origin"); + yield* configureRemote(repoDir, "my-org/upstream", upstreamDir, "my-org/upstream"); + + yield* runGit(repoDir, ["checkout", "-b", "effect-atom"]); + yield* runGit(repoDir, ["push", "-u", "origin", "effect-atom"]); + yield* runGit(repoDir, ["push", "-u", "my-org/upstream", "effect-atom"]); + yield* runGit(repoDir, [ + "config", + "remote.origin.url", + "git@github.com:pingdotgg/codething-mvp.git", + ]); + yield* runGit(repoDir, ["config", "remote.origin.pushurl", originDir]); + yield* runGit(repoDir, [ + "config", + "remote.my-org/upstream.url", + "git@github.com:pingdotgg/codething-mvp.git", + ]); + yield* runGit(repoDir, ["config", "remote.my-org/upstream.pushurl", upstreamDir]); + yield* runGit(repoDir, ["checkout", "main"]); + yield* runGit(repoDir, ["branch", "-D", "effect-atom"]); + yield* runGit(repoDir, ["checkout", "--track", "my-org/upstream/effect-atom"]); + + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + prListByHeadSelector: { + "effect-atom": JSON.stringify([ + { + number: 1618, + title: "Correct PR", + url: "https://github.com/pingdotgg/t3code/pull/1618", + baseRefName: "main", + headRefName: "effect-atom", + state: "OPEN", + updatedAt: "2026-03-01T10:00:00Z", + }, + ]), + "upstream/effect-atom": JSON.stringify([ + { + number: 1518, + title: "Wrong PR", + url: "https://github.com/pingdotgg/t3code/pull/1518", + baseRefName: "main", + headRefName: "upstream/effect-atom", + state: "OPEN", + updatedAt: "2026-04-01T10:00:00Z", + }, + ]), + "pingdotgg:effect-atom": JSON.stringify([]), + "my-org/upstream:effect-atom": JSON.stringify([]), + "pingdotgg:upstream/effect-atom": JSON.stringify([ + { + number: 1518, + title: "Wrong PR", + url: "https://github.com/pingdotgg/t3code/pull/1518", + baseRefName: "main", + headRefName: "upstream/effect-atom", + state: "OPEN", + updatedAt: "2026-04-01T10:00:00Z", + }, + ]), + "my-org/upstream:upstream/effect-atom": JSON.stringify([ + { + number: 1518, + title: "Wrong PR", + url: "https://github.com/pingdotgg/t3code/pull/1518", + baseRefName: "main", + headRefName: "upstream/effect-atom", + state: "OPEN", + updatedAt: "2026-04-01T10:00:00Z", + }, + ]), + }, + }, + }); + + const status = yield* manager.status({ cwd: repoDir }); + expect(status.branch).toBe("upstream/effect-atom"); + expect(status.pr).toEqual({ + number: 1618, + title: "Correct PR", + url: "https://github.com/pingdotgg/t3code/pull/1618", + baseBranch: "main", + headBranch: "effect-atom", + state: "open", + }); + expect(ghCalls.some((call) => call.includes("pr list --head upstream/effect-atom "))).toBe( + false, + ); + expect( + ghCalls.some((call) => call.includes("pr list --head pingdotgg:upstream/effect-atom ")), + ).toBe(false); + expect( + ghCalls.some((call) => + call.includes("pr list --head my-org/upstream:upstream/effect-atom "), + ), + ).toBe(false); + }), + 20_000, ); it.effect("status returns merged PR state when latest PR was merged", () => @@ -758,6 +1275,17 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { expect(result.commit.status).toBe("created"); expect(result.push.status).toBe("skipped_not_requested"); expect(result.pr.status).toBe("skipped_not_requested"); + expect(result.toast).toMatchObject({ + description: "Implement stacked git actions", + cta: { + kind: "run_action", + label: "Push", + action: { + kind: "push", + }, + }, + }); + expect(result.toast.title).toMatch(/^Committed [0-9a-f]{7}$/); expect( yield* runGit(repoDir, ["log", "-1", "--pretty=%s"]).pipe( Effect.map((result) => result.stdout.trim()), @@ -867,6 +1395,19 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { expect(result.branch.name).toBe("feature/implement-stacked-git-actions"); expect(result.commit.status).toBe("created"); expect(result.push.status).toBe("pushed"); + expect(result.toast).toMatchObject({ + description: "Implement stacked git actions", + cta: { + kind: "run_action", + label: "Create PR", + action: { + kind: "create_pr", + }, + }, + }); + expect(result.toast.title).toMatch( + /^Pushed [0-9a-f]{7} to origin\/feature\/implement-stacked-git-actions$/, + ); expect( yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "HEAD"]).pipe( Effect.map((result) => result.stdout.trim()), @@ -1063,6 +1604,80 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { }), ); + it.effect("pushes existing clean commits without rerunning commit logic", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/push-only"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + fs.writeFileSync(path.join(repoDir, "push-only.txt"), "push only\n"); + yield* runGit(repoDir, ["add", "push-only.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Push only branch"]); + + const { manager } = yield* makeManager(); + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "push", + }); + + expect(result.commit.status).toBe("skipped_not_requested"); + expect(result.push.status).toBe("pushed"); + expect(result.pr.status).toBe("skipped_not_requested"); + expect( + yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"]).pipe( + Effect.map((output) => output.stdout.trim()), + ), + ).toBe("origin/feature/push-only"); + }), + ); + + it.effect("create_pr pushes a clean branch before creating the PR when needed", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/create-pr-only"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + fs.writeFileSync(path.join(repoDir, "create-pr-only.txt"), "create pr\n"); + yield* runGit(repoDir, ["add", "create-pr-only.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Create PR only branch"]); + + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + prListSequence: [ + "[]", + JSON.stringify([ + { + number: 303, + title: "Create PR only branch", + url: "https://github.com/pingdotgg/codething-mvp/pull/303", + baseRefName: "main", + headRefName: "feature/create-pr-only", + }, + ]), + ], + }, + }); + + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "create_pr", + }); + + expect(result.commit.status).toBe("skipped_not_requested"); + expect(result.push.status).toBe("pushed"); + expect(result.push.setUpstream).toBe(true); + expect(result.pr.status).toBe("created"); + expect(result.pr.number).toBe(303); + expect( + ghCalls.some((call) => + call.includes("pr create --base main --head feature/create-pr-only"), + ), + ).toBe(true); + }), + ); + it.effect("returns existing PR metadata for commit/push/pr action", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); @@ -1095,6 +1710,15 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { expect(result.branch.status).toBe("skipped_not_requested"); expect(result.pr.status).toBe("opened_existing"); expect(result.pr.number).toBe(42); + expect(result.toast).toEqual({ + title: "Opened PR #42", + description: "Existing PR", + cta: { + kind: "open_pr", + label: "View PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/42", + }, + }); expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false); }), ); @@ -1126,6 +1750,14 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { url: "https://github.com/pingdotgg/codething-mvp/pull/142", baseRefName: "main", headRefName: "statemachine", + state: "OPEN", + isCrossRepository: true, + headRepository: { + nameWithOwner: "octocat/codething-mvp", + }, + headRepositoryOwner: { + login: "octocat", + }, }, ]), ], @@ -1149,6 +1781,98 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { 12_000, ); + it.effect( + "returns the correct existing PR when a slash remote checks out to a synthetic local alias", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const originDir = yield* createBareRemote(); + const upstreamDir = yield* createBareRemote(); + yield* configureRemote(repoDir, "origin", originDir, "origin"); + yield* configureRemote(repoDir, "my-org/upstream", upstreamDir, "my-org/upstream"); + + yield* runGit(repoDir, ["checkout", "-b", "effect-atom"]); + yield* runGit(repoDir, ["push", "-u", "origin", "effect-atom"]); + yield* runGit(repoDir, ["push", "-u", "my-org/upstream", "effect-atom"]); + yield* runGit(repoDir, [ + "config", + "remote.origin.url", + "git@github.com:pingdotgg/codething-mvp.git", + ]); + yield* runGit(repoDir, ["config", "remote.origin.pushurl", originDir]); + yield* runGit(repoDir, [ + "config", + "remote.my-org/upstream.url", + "git@github.com:pingdotgg/codething-mvp.git", + ]); + yield* runGit(repoDir, ["config", "remote.my-org/upstream.pushurl", upstreamDir]); + yield* runGit(repoDir, ["checkout", "main"]); + yield* runGit(repoDir, ["branch", "-D", "effect-atom"]); + yield* runGit(repoDir, ["checkout", "--track", "my-org/upstream/effect-atom"]); + fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n"); + yield* runGit(repoDir, ["add", "changes.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Feature commit"]); + + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + prListByHeadSelector: { + "effect-atom": JSON.stringify([ + { + number: 1618, + title: "Correct PR", + url: "https://github.com/pingdotgg/t3code/pull/1618", + baseRefName: "main", + headRefName: "effect-atom", + }, + ]), + "upstream/effect-atom": JSON.stringify([ + { + number: 1518, + title: "Wrong PR", + url: "https://github.com/pingdotgg/t3code/pull/1518", + baseRefName: "main", + headRefName: "upstream/effect-atom", + }, + ]), + "pingdotgg:effect-atom": JSON.stringify([]), + "my-org/upstream:effect-atom": JSON.stringify([]), + "pingdotgg:upstream/effect-atom": JSON.stringify([ + { + number: 1518, + title: "Wrong PR", + url: "https://github.com/pingdotgg/t3code/pull/1518", + baseRefName: "main", + headRefName: "upstream/effect-atom", + }, + ]), + "my-org/upstream:upstream/effect-atom": JSON.stringify([ + { + number: 1518, + title: "Wrong PR", + url: "https://github.com/pingdotgg/t3code/pull/1518", + baseRefName: "main", + headRefName: "upstream/effect-atom", + }, + ]), + }, + }, + }); + + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit_push_pr", + }); + + expect(result.pr.status).toBe("opened_existing"); + expect(result.pr.number).toBe(1618); + expect(ghCalls.some((call) => call.includes("pr list --head upstream/effect-atom "))).toBe( + false, + ); + }), + 20_000, + ); + it.effect( "prefers owner-qualified selectors before bare branch names for cross-repo PRs", () => @@ -1187,6 +1911,14 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { url: "https://github.com/pingdotgg/codething-mvp/pull/142", baseRefName: "main", headRefName: "statemachine", + state: "OPEN", + isCrossRepository: true, + headRepository: { + nameWithOwner: "octocat/codething-mvp", + }, + headRepositoryOwner: { + login: "octocat", + }, }, ]), "fork-seed:statemachine": JSON.stringify([]), @@ -1239,6 +1971,14 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { url: "https://github.com/pingdotgg/codething-mvp/pull/142", baseRefName: "main", headRefName: "statemachine", + state: "OPEN", + isCrossRepository: true, + headRepository: { + nameWithOwner: "octocat/codething-mvp", + }, + headRepositoryOwner: { + login: "octocat", + }, }, ]), "fork-seed:statemachine": JSON.stringify([]), @@ -1256,9 +1996,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { expect(result.pr.status).toBe("opened_existing"); expect(result.pr.number).toBe(142); - const prListCalls = ghCalls.filter((call) => call.startsWith("pr list ")); - expect(prListCalls).toHaveLength(1); - expect(prListCalls[0]).toContain( + const openLookupCalls = ghCalls.filter((call) => call.includes("--state open --limit 1")); + expect(openLookupCalls).toHaveLength(1); + expect(openLookupCalls[0]).toContain( "pr list --head octocat:statemachine --state open --limit 1", ); }), @@ -1302,6 +2042,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { expect(result.branch.status).toBe("skipped_not_requested"); expect(result.pr.status).toBe("created"); expect(result.pr.number).toBe(88); + expect(ghCalls.filter((call) => call.startsWith("pr list "))).toHaveLength(2); expect( ghCalls.some((call) => call.includes("pr create --base main --head feature-create-pr")), ).toBe(true); @@ -1309,6 +2050,78 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { }), ); + it.effect( + "creates a new PR instead of reusing an unrelated fork PR with the same head branch", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/no-fork-match"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n"); + yield* runGit(repoDir, ["add", "changes.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Feature commit"]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/no-fork-match"]); + + const { manager, ghCalls } = yield* makeManager({ + ghScenario: { + prListSequence: [ + JSON.stringify([ + { + number: 1661, + title: "Fork PR with same branch name", + url: "https://github.com/pingdotgg/t3code/pull/1661", + baseRefName: "main", + headRefName: "feature/no-fork-match", + state: "OPEN", + isCrossRepository: true, + headRepository: { + nameWithOwner: "lnieuwenhuis/t3code", + }, + headRepositoryOwner: { + login: "lnieuwenhuis", + }, + }, + ]), + JSON.stringify([ + { + number: 188, + title: "Add stacked git actions", + url: "https://github.com/pingdotgg/codething-mvp/pull/188", + baseRefName: "main", + headRefName: "feature/no-fork-match", + state: "OPEN", + isCrossRepository: false, + }, + ]), + ], + }, + }); + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit_push_pr", + }); + + expect(result.pr.status).toBe("created"); + expect(result.pr.number).toBe(188); + expect(result.toast).toEqual({ + title: "Created PR #188", + description: "Add stacked git actions", + cta: { + kind: "open_pr", + label: "View PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/188", + }, + }); + expect( + ghCalls.some((call) => + call.includes("pr create --base main --head feature/no-fork-match"), + ), + ).toBe(true); + }), + ); + it.effect("creates cross-repo PRs with the fork owner selector and default base branch", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); @@ -1330,23 +2143,30 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { const { manager, ghCalls } = yield* makeManager({ ghScenario: { - prListSequence: [ - JSON.stringify([]), - JSON.stringify([]), - JSON.stringify([]), - JSON.stringify([]), - JSON.stringify([]), - JSON.stringify([]), - JSON.stringify([ - { - number: 188, - title: "Add stacked git actions", - url: "https://github.com/pingdotgg/codething-mvp/pull/188", - baseRefName: "main", - headRefName: "statemachine", - }, - ]), - ], + prListSequenceByHeadSelector: { + "octocat:statemachine": [ + JSON.stringify([]), + JSON.stringify([ + { + number: 188, + title: "Add stacked git actions", + url: "https://github.com/pingdotgg/codething-mvp/pull/188", + baseRefName: "main", + headRefName: "statemachine", + state: "OPEN", + isCrossRepository: true, + headRepository: { + nameWithOwner: "octocat/codething-mvp", + }, + headRepositoryOwner: { + login: "octocat", + }, + }, + ]), + ], + "fork-seed:statemachine": [JSON.stringify([])], + statemachine: [JSON.stringify([])], + }, }, }); @@ -1560,6 +2380,59 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { }), ); + it.effect("launches setup only when creating a new PR worktree", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-worktree-setup"]); + fs.writeFileSync(path.join(repoDir, "setup.txt"), "setup\n"); + yield* runGit(repoDir, ["add", "setup.txt"]); + yield* runGit(repoDir, ["commit", "-m", "PR worktree setup branch"]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-worktree-setup"]); + yield* runGit(repoDir, ["push", "origin", "HEAD:refs/pull/177/head"]); + yield* runGit(repoDir, ["checkout", "main"]); + + const setupCalls: ProjectSetupScriptRunnerInput[] = []; + const { manager } = yield* makeManager({ + ghScenario: { + pullRequest: { + number: 177, + title: "Worktree setup PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/177", + baseRefName: "main", + headRefName: "feature/pr-worktree-setup", + state: "open", + }, + }, + setupScriptRunner: { + runForThread: (setupInput) => + Effect.sync(() => { + setupCalls.push(setupInput); + return { status: "no-script" as const }; + }), + }, + }); + + const result = yield* preparePullRequestThread(manager, { + cwd: repoDir, + reference: "177", + mode: "worktree", + threadId: asThreadId("thread-pr-setup"), + }); + + expect(result.worktreePath).not.toBeNull(); + expect(setupCalls).toHaveLength(1); + expect(setupCalls[0]).toEqual({ + threadId: "thread-pr-setup", + projectCwd: repoDir, + worktreePath: result.worktreePath as string, + }); + }), + ); + it.effect("preserves fork upstream tracking when preparing a worktree PR thread", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); @@ -1744,6 +2617,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { const worktreePath = path.join(repoDir, "..", `pr-existing-${Date.now()}`); yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-existing-worktree"]); + const setupCalls: ProjectSetupScriptRunnerInput[] = []; const { manager } = yield* makeManager({ ghScenario: { pullRequest: { @@ -1755,18 +2629,27 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { state: "open", }, }, + setupScriptRunner: { + runForThread: (setupInput) => + Effect.sync(() => { + setupCalls.push(setupInput); + return { status: "no-script" as const }; + }), + }, }); const result = yield* preparePullRequestThread(manager, { cwd: repoDir, reference: "78", mode: "worktree", + threadId: asThreadId("thread-pr-existing-worktree"), }); expect(result.worktreePath && fs.realpathSync.native(result.worktreePath)).toBe( fs.realpathSync.native(worktreePath), ); expect(result.branch).toBe("feature/pr-existing-worktree"); + expect(setupCalls).toHaveLength(0); }), ); @@ -1946,6 +2829,50 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { }), ); + it.effect("does not fail PR worktree prep when setup terminal startup fails", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-setup-failure"]); + fs.writeFileSync(path.join(repoDir, "setup-failure.txt"), "setup failure\n"); + yield* runGit(repoDir, ["add", "setup-failure.txt"]); + yield* runGit(repoDir, ["commit", "-m", "PR setup failure branch"]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-setup-failure"]); + yield* runGit(repoDir, ["push", "origin", "HEAD:refs/pull/184/head"]); + yield* runGit(repoDir, ["checkout", "main"]); + + const { manager } = yield* makeManager({ + ghScenario: { + pullRequest: { + number: 184, + title: "Setup failure PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/184", + baseRefName: "main", + headRefName: "feature/pr-setup-failure", + state: "open", + }, + }, + setupScriptRunner: { + runForThread: () => Effect.fail(new Error("terminal start failed")), + }, + }); + + const result = yield* preparePullRequestThread(manager, { + cwd: repoDir, + reference: "184", + mode: "worktree", + threadId: asThreadId("thread-pr-setup-failure"), + }); + + expect(result.branch).toBe("feature/pr-setup-failure"); + expect(result.worktreePath).not.toBeNull(); + expect(fs.existsSync(result.worktreePath as string)).toBe(true); + }), + ); + it.effect("rejects worktree prep when the PR head branch is checked out in the main repo", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); @@ -2090,4 +3017,81 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { ); }), ); + + it.effect("create_pr emits only the PR phase when the branch is already pushed", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-only-follow-up"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + fs.writeFileSync(path.join(repoDir, "pr-only.txt"), "pr only\n"); + yield* runGit(repoDir, ["add", "pr-only.txt"]); + yield* runGit(repoDir, ["commit", "-m", "PR only branch"]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-only-follow-up"]); + + const { manager } = yield* makeManager({ + ghScenario: { + prListSequence: [ + JSON.stringify([]), + JSON.stringify([ + { + number: 201, + title: "PR only branch", + url: "https://github.com/pingdotgg/codething-mvp/pull/201", + baseRefName: "main", + headRefName: "feature/pr-only-follow-up", + state: "OPEN", + isCrossRepository: false, + }, + ]), + ], + }, + }); + const events: GitActionProgressEvent[] = []; + + const result = yield* runStackedAction( + manager, + { + cwd: repoDir, + action: "create_pr", + }, + { + actionId: "action-pr-only", + progressReporter: { + publish: (event) => + Effect.sync(() => { + events.push(event); + }), + }, + }, + ); + + expect(result.commit.status).toBe("skipped_not_requested"); + expect(result.push.status).toBe("skipped_not_requested"); + expect(result.pr.status).toBe("created"); + expect( + events.filter( + (event): event is Extract => + event.kind === "phase_started", + ), + ).toEqual([ + expect.objectContaining({ + kind: "phase_started", + phase: "pr", + label: "Preparing PR...", + }), + expect.objectContaining({ + kind: "phase_started", + phase: "pr", + label: "Generating PR content...", + }), + expect.objectContaining({ + kind: "phase_started", + phase: "pr", + label: "Creating GitHub pull request...", + }), + ]); + }), + ); }); diff --git a/apps/server/src/git/Layers/GitManager.ts b/apps/server/src/git/Layers/GitManager.ts index dc082674b7..a84427a194 100644 --- a/apps/server/src/git/Layers/GitManager.ts +++ b/apps/server/src/git/Layers/GitManager.ts @@ -1,36 +1,68 @@ import { randomUUID } from "node:crypto"; import { realpathSync } from "node:fs"; -import { Effect, FileSystem, Layer, Option, Path, Ref } from "effect"; +import { + Cache, + Duration, + Effect, + Exit, + FileSystem, + Layer, + Option, + Path, + Ref, + Result, +} from "effect"; import { GitActionProgressEvent, GitActionProgressPhase, + GitCommandError, GitRunStackedActionResult, + GitStackedAction, + type GitStatusLocalResult, + type GitStatusRemoteResult, ModelSelection, } from "@t3tools/contracts"; import { + detectGitHostingProviderFromRemoteUrl, + mergeGitStatusParts, resolveAutoFeatureBranchName, sanitizeBranchFragment, sanitizeFeatureBranchName, } from "@t3tools/shared/git"; -import { GitManagerError } from "../Errors.ts"; +import { GitManagerError } from "@t3tools/contracts"; import { GitManager, type GitActionProgressReporter, type GitManagerShape, type GitRunStackedActionOptions, } from "../Services/GitManager.ts"; -import { GitCore } from "../Services/GitCore.ts"; -import { GitHubCli } from "../Services/GitHubCli.ts"; +import { GitCore, GitStatusDetails } from "../Services/GitCore.ts"; +import { GitHubCli, type GitHubPullRequestSummary } from "../Services/GitHubCli.ts"; import { TextGeneration } from "../Services/TextGeneration.ts"; +import { ProjectSetupScriptRunner } from "../../project/Services/ProjectSetupScriptRunner.ts"; +import { extractBranchNameFromRemoteRef } from "../remoteRefs.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; -import type { GitManagerServiceError } from "../Errors.ts"; +import type { GitManagerServiceError } from "@t3tools/contracts"; +import { + decodeGitHubPullRequestListJson, + formatGitHubJsonDecodeError, +} from "../githubPullRequests.ts"; const COMMIT_TIMEOUT_MS = 10 * 60_000; const MAX_PROGRESS_TEXT_LENGTH = 500; +const SHORT_SHA_LENGTH = 7; +const TOAST_DESCRIPTION_MAX = 72; +const STATUS_RESULT_CACHE_TTL = Duration.seconds(1); +const STATUS_RESULT_CACHE_CAPACITY = 2_048; type StripProgressContext = T extends any ? Omit : never; type GitActionProgressPayload = StripProgressContext; +type GitActionProgressEmitter = (event: GitActionProgressPayload) => Effect.Effect; + +function isNotGitRepositoryError(error: GitCommandError): boolean { + return error.message.toLowerCase().includes("not a git repository"); +} interface OpenPrInfo { number: number; @@ -40,7 +72,7 @@ interface OpenPrInfo { headRefName: string; } -interface PullRequestInfo extends OpenPrInfo { +interface PullRequestInfo extends OpenPrInfo, PullRequestHeadRemoteInfo { state: "open" | "closed" | "merged"; updatedAt: string | null; } @@ -135,55 +167,113 @@ function parseRepositoryOwnerLogin(nameWithOwner: string | null): string | null return normalizedOwnerLogin.length > 0 ? normalizedOwnerLogin : null; } -function parsePullRequestList(raw: unknown): PullRequestInfo[] { - if (!Array.isArray(raw)) return []; +function normalizeOptionalString(value: string | null | undefined): string | null { + const trimmed = value?.trim() ?? ""; + return trimmed.length > 0 ? trimmed : null; +} - const parsed: PullRequestInfo[] = []; - for (const entry of raw) { - if (!entry || typeof entry !== "object") continue; - const record = entry as Record; - const number = record.number; - const title = record.title; - const url = record.url; - const baseRefName = record.baseRefName; - const headRefName = record.headRefName; - const state = record.state; - const mergedAt = record.mergedAt; - const updatedAt = record.updatedAt; - if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) { - continue; - } - if ( - typeof title !== "string" || - typeof url !== "string" || - typeof baseRefName !== "string" || - typeof headRefName !== "string" - ) { - continue; - } +function normalizeOptionalRepositoryNameWithOwner(value: string | null | undefined): string | null { + const normalized = normalizeOptionalString(value); + return normalized ? normalized.toLowerCase() : null; +} - let normalizedState: "open" | "closed" | "merged"; - if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") { - normalizedState = "merged"; - } else if (state === "OPEN" || state === undefined || state === null) { - normalizedState = "open"; - } else if (state === "CLOSED") { - normalizedState = "closed"; - } else { - continue; - } +function normalizeOptionalOwnerLogin(value: string | null | undefined): string | null { + const normalized = normalizeOptionalString(value); + return normalized ? normalized.toLowerCase() : null; +} - parsed.push({ - number, - title, - url, - baseRefName, - headRefName, - state: normalizedState, - updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null, - }); +function resolvePullRequestHeadRepositoryNameWithOwner( + pr: PullRequestHeadRemoteInfo & { url: string }, +) { + const explicitRepository = normalizeOptionalString(pr.headRepositoryNameWithOwner); + if (explicitRepository) { + return explicitRepository; } - return parsed; + + if (!pr.isCrossRepository) { + return null; + } + + const ownerLogin = normalizeOptionalString(pr.headRepositoryOwnerLogin); + const repositoryName = parseRepositoryNameFromPullRequestUrl(pr.url); + if (!ownerLogin || !repositoryName) { + return null; + } + + return `${ownerLogin}/${repositoryName}`; +} + +function matchesBranchHeadContext( + pr: PullRequestInfo, + headContext: Pick< + BranchHeadContext, + "headBranch" | "headRepositoryNameWithOwner" | "headRepositoryOwnerLogin" | "isCrossRepository" + >, +): boolean { + if (pr.headRefName !== headContext.headBranch) { + return false; + } + + const expectedHeadRepository = normalizeOptionalRepositoryNameWithOwner( + headContext.headRepositoryNameWithOwner, + ); + const expectedHeadOwner = + normalizeOptionalOwnerLogin(headContext.headRepositoryOwnerLogin) ?? + parseRepositoryOwnerLogin(expectedHeadRepository); + const prHeadRepository = normalizeOptionalRepositoryNameWithOwner( + resolvePullRequestHeadRepositoryNameWithOwner(pr), + ); + const prHeadOwner = + normalizeOptionalOwnerLogin(pr.headRepositoryOwnerLogin) ?? + parseRepositoryOwnerLogin(prHeadRepository); + + if (headContext.isCrossRepository) { + if (pr.isCrossRepository === false) { + return false; + } + if ((expectedHeadRepository || expectedHeadOwner) && !prHeadRepository && !prHeadOwner) { + return false; + } + if (expectedHeadRepository && prHeadRepository && expectedHeadRepository !== prHeadRepository) { + return false; + } + if (expectedHeadOwner && prHeadOwner && expectedHeadOwner !== prHeadOwner) { + return false; + } + return true; + } + + if (pr.isCrossRepository === true) { + return false; + } + if (expectedHeadRepository && prHeadRepository && expectedHeadRepository !== prHeadRepository) { + return false; + } + if (expectedHeadOwner && prHeadOwner && expectedHeadOwner !== prHeadOwner) { + return false; + } + return true; +} + +function toPullRequestInfo(summary: GitHubPullRequestSummary): PullRequestInfo { + return { + number: summary.number, + title: summary.title, + url: summary.url, + baseRefName: summary.baseRefName, + headRefName: summary.headRefName, + state: summary.state ?? "open", + updatedAt: null, + ...(summary.isCrossRepository !== undefined + ? { isCrossRepository: summary.isCrossRepository } + : {}), + ...(summary.headRepositoryNameWithOwner !== undefined + ? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner } + : {}), + ...(summary.headRepositoryOwnerLogin !== undefined + ? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin } + : {}), + }; } function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError { @@ -199,6 +289,57 @@ function limitContext(value: string, maxChars: number): string { return `${value.slice(0, maxChars)}\n\n[truncated]`; } +function shortenSha(sha: string | undefined): string | null { + if (!sha) return null; + return sha.slice(0, SHORT_SHA_LENGTH); +} + +function truncateText( + value: string | undefined, + maxLength = TOAST_DESCRIPTION_MAX, +): string | undefined { + if (!value) return undefined; + if (value.length <= maxLength) return value; + if (maxLength <= 3) return "...".slice(0, maxLength); + return `${value.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`; +} + +function withDescription(title: string, description: string | undefined) { + return description ? { title, description } : { title }; +} + +function summarizeGitActionResult( + result: Pick, +): { + title: string; + description?: string; +} { + if (result.pr.status === "created" || result.pr.status === "opened_existing") { + const prNumber = result.pr.number ? ` #${result.pr.number}` : ""; + const title = `${result.pr.status === "created" ? "Created PR" : "Opened PR"}${prNumber}`; + return withDescription(title, truncateText(result.pr.title)); + } + + if (result.push.status === "pushed") { + const shortSha = shortenSha(result.commit.commitSha); + const branch = result.push.upstreamBranch ?? result.push.branch; + const pushedCommitPart = shortSha ? ` ${shortSha}` : ""; + const branchPart = branch ? ` to ${branch}` : ""; + return withDescription( + `Pushed${pushedCommitPart}${branchPart}`, + truncateText(result.commit.subject), + ); + } + + if (result.commit.status === "created") { + const shortSha = shortenSha(result.commit.commitSha); + const title = shortSha ? `Committed ${shortSha}` : "Committed changes"; + return withDescription(title, truncateText(result.commit.subject)); + } + + return { title: "Done" }; +} + function sanitizeCommitMessage(generated: { subject: string; body: string; @@ -236,6 +377,12 @@ interface CommitAndBranchSuggestion { commitMessage: string; } +function isCommitAction( + action: GitStackedAction, +): action is "commit" | "commit_push" | "commit_push_pr" { + return action === "commit" || action === "commit_push" || action === "commit_push_pr"; +} + function formatCommitMessage(subject: string, body: string): string { const trimmedBody = body.trim(); if (trimmedBody.length === 0) { @@ -262,25 +409,6 @@ function parseCustomCommitMessage(raw: string): { subject: string; body: string }; } -function extractBranchFromRef(ref: string): string { - const normalized = ref.trim(); - - if (normalized.startsWith("refs/remotes/")) { - const withoutPrefix = normalized.slice("refs/remotes/".length); - const firstSlash = withoutPrefix.indexOf("/"); - if (firstSlash === -1) { - return withoutPrefix.trim(); - } - return withoutPrefix.slice(firstSlash + 1).trim(); - } - - const firstSlash = normalized.indexOf("/"); - if (firstSlash === -1) { - return normalized; - } - return normalized.slice(firstSlash + 1).trim(); -} - function appendUnique(values: string[], next: string | null | undefined): void { const trimmed = next?.trim() ?? ""; if (trimmed.length === 0 || values.includes(trimmed)) { @@ -365,10 +493,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { const gitCore = yield* GitCore; const gitHubCli = yield* GitHubCli; const textGeneration = yield* TextGeneration; + const projectSetupScriptRunner = yield* ProjectSetupScriptRunner; const serverSettingsService = yield* ServerSettingsService; const createProgressEmitter = ( - input: { cwd: string; action: "commit" | "commit_push" | "commit_push_pr" }, + input: { cwd: string; action: GitStackedAction }, options?: GitRunStackedActionOptions, ) => { const actionId = options?.actionId ?? randomUUID(); @@ -505,10 +634,96 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { const path = yield* Path.Path; const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp"; + const normalizeStatusCacheKey = (cwd: string) => canonicalizeExistingPath(cwd); + const nonRepositoryStatusDetails = { + isRepo: false, + hasOriginRemote: false, + isDefaultBranch: false, + branch: null, + upstreamRef: null, + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + hasUpstream: false, + aheadCount: 0, + behindCount: 0, + } satisfies GitStatusDetails; + const readLocalStatus = Effect.fn("readLocalStatus")(function* (cwd: string) { + const details = yield* gitCore + .statusDetailsLocal(cwd) + .pipe( + Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(nonRepositoryStatusDetails)), + ); + const hostingProvider = details.isRepo + ? yield* resolveHostingProvider(cwd, details.branch) + : null; + + return { + isRepo: details.isRepo, + ...(hostingProvider ? { hostingProvider } : {}), + hasOriginRemote: details.hasOriginRemote, + isDefaultBranch: details.isDefaultBranch, + branch: details.branch, + hasWorkingTreeChanges: details.hasWorkingTreeChanges, + workingTree: details.workingTree, + } satisfies GitStatusLocalResult; + }); + const localStatusResultCache = yield* Cache.makeWith(readLocalStatus, { + capacity: STATUS_RESULT_CACHE_CAPACITY, + timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero), + }); + const invalidateLocalStatusResultCache = (cwd: string) => + Cache.invalidate(localStatusResultCache, normalizeStatusCacheKey(cwd)); + const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (cwd: string) { + const details = yield* gitCore + .statusDetails(cwd) + .pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null))); + if (details === null || !details.isRepo) { + return null; + } + + const pr = + details.branch !== null + ? yield* findLatestPr(cwd, { + branch: details.branch, + upstreamRef: details.upstreamRef, + }).pipe( + Effect.map((latest) => (latest ? toStatusPr(latest) : null)), + Effect.catch(() => Effect.succeed(null)), + ) + : null; + + return { + hasUpstream: details.hasUpstream, + aheadCount: details.aheadCount, + behindCount: details.behindCount, + pr, + } satisfies GitStatusRemoteResult; + }); + const remoteStatusResultCache = yield* Cache.makeWith(readRemoteStatus, { + capacity: STATUS_RESULT_CACHE_CAPACITY, + timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero), + }); + const invalidateRemoteStatusResultCache = (cwd: string) => + Cache.invalidate(remoteStatusResultCache, normalizeStatusCacheKey(cwd)); const readConfigValueNullable = (cwd: string, key: string) => gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null))); + const resolveHostingProvider = Effect.fn("resolveHostingProvider")(function* ( + cwd: string, + branch: string | null, + ) { + const preferredRemoteName = + branch === null + ? "origin" + : ((yield* readConfigValueNullable(cwd, `branch.${branch}.remote`)) ?? "origin"); + const remoteUrl = + (yield* readConfigValueNullable(cwd, `remote.${preferredRemoteName}.url`)) ?? + (yield* readConfigValueNullable(cwd, "remote.origin.url")); + + return remoteUrl ? detectGitHostingProviderFromRemoteUrl(remoteUrl) : null; + }); + const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* ( cwd: string, remoteName: string | null, @@ -534,9 +749,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { ) { const remoteName = yield* readConfigValueNullable(cwd, `branch.${details.branch}.remote`); const headBranchFromUpstream = details.upstreamRef - ? extractBranchFromRef(details.upstreamRef) + ? extractBranchNameFromRemoteRef(details.upstreamRef, { remoteName }) : ""; const headBranch = headBranchFromUpstream.length > 0 ? headBranchFromUpstream : details.branch; + const shouldProbeLocalBranchSelector = + headBranchFromUpstream.length === 0 || headBranch === details.branch; const [remoteRepository, originRepository] = yield* Effect.all( [ @@ -572,7 +789,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null, ); } - appendUnique(headSelectors, details.branch); + if (shouldProbeLocalBranchSelector) { + appendUnique(headSelectors, details.branch); + } appendUnique(headSelectors, headBranch !== details.branch ? headBranch : null); if (!isCrossRepository && shouldProbeRemoteOwnedSelectors) { appendUnique(headSelectors, ownerHeadSelector); @@ -597,16 +816,26 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { const findOpenPr = Effect.fn("findOpenPr")(function* ( cwd: string, - headSelectors: ReadonlyArray, + headContext: Pick< + BranchHeadContext, + | "headBranch" + | "headSelectors" + | "headRepositoryNameWithOwner" + | "headRepositoryOwnerLogin" + | "isCrossRepository" + >, ) { - for (const headSelector of headSelectors) { + for (const headSelector of headContext.headSelectors) { const pullRequests = yield* gitHubCli.listOpenPullRequests({ cwd, headSelector, limit: 1, }); + const normalizedPullRequests = pullRequests.map(toPullRequestInfo); - const [firstPullRequest] = pullRequests; + const firstPullRequest = normalizedPullRequests.find((pullRequest) => + matchesBranchHeadContext(pullRequest, headContext), + ); if (firstPullRequest) { return { number: firstPullRequest.number, @@ -644,7 +873,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { "--limit", "20", "--json", - "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt", + "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner", ], }) .pipe(Effect.map((result) => result.stdout)); @@ -654,13 +883,26 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { continue; } - const parsedJson = yield* Effect.try({ - try: () => JSON.parse(raw) as unknown, - catch: (cause) => - gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause), - }); + const pullRequests = yield* Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe( + Effect.flatMap((decoded) => { + if (!Result.isSuccess(decoded)) { + return Effect.fail( + gitManagerError( + "findLatestPr", + `GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`, + decoded.failure, + ), + ); + } - for (const pr of parsePullRequestList(parsedJson)) { + return Effect.succeed(decoded.success); + }), + ); + + for (const pr of pullRequests) { + if (!matchesBranchHeadContext(pr, headContext)) { + continue; + } parsedByNumber.set(pr.number, pr); } } @@ -678,17 +920,109 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { return parsed[0] ?? null; }); + const buildCompletionToast = Effect.fn("buildCompletionToast")(function* ( + cwd: string, + result: Pick, + ) { + const summary = summarizeGitActionResult(result); + let latestOpenPr: PullRequestInfo | null = null; + let currentBranchIsDefault = false; + let finalBranchContext: { + branch: string; + upstreamRef: string | null; + hasUpstream: boolean; + } | null = null; + + if (result.action !== "commit") { + const finalStatus = yield* gitCore.statusDetails(cwd); + if (finalStatus.branch) { + finalBranchContext = { + branch: finalStatus.branch, + upstreamRef: finalStatus.upstreamRef, + hasUpstream: finalStatus.hasUpstream, + }; + currentBranchIsDefault = finalStatus.isDefaultBranch; + } + } + + const explicitResultPr = + (result.pr.status === "created" || result.pr.status === "opened_existing") && result.pr.url + ? { + url: result.pr.url, + state: "open" as const, + } + : null; + const shouldLookupExistingOpenPr = + (result.action === "commit_push" || result.action === "push") && + result.push.status === "pushed" && + result.branch.status !== "created" && + !currentBranchIsDefault && + explicitResultPr === null && + finalBranchContext?.hasUpstream === true; + + if (shouldLookupExistingOpenPr && finalBranchContext) { + latestOpenPr = yield* resolveBranchHeadContext(cwd, { + branch: finalBranchContext.branch, + upstreamRef: finalBranchContext.upstreamRef, + }).pipe( + Effect.flatMap((headContext) => findOpenPr(cwd, headContext)), + Effect.catch(() => Effect.succeed(null)), + ); + } + + const openPr = latestOpenPr ?? explicitResultPr; + + const cta = + result.action === "commit" && result.commit.status === "created" + ? { + kind: "run_action" as const, + label: "Push", + action: { kind: "push" as const }, + } + : (result.action === "push" || + result.action === "create_pr" || + result.action === "commit_push" || + result.action === "commit_push_pr") && + openPr?.url && + (!currentBranchIsDefault || + result.pr.status === "created" || + result.pr.status === "opened_existing") + ? { + kind: "open_pr" as const, + label: "View PR", + url: openPr.url, + } + : (result.action === "push" || result.action === "commit_push") && + result.push.status === "pushed" && + !currentBranchIsDefault + ? { + kind: "run_action" as const, + label: "Create PR", + action: { kind: "create_pr" as const }, + } + : { + kind: "none" as const, + }; + + return { + ...summary, + cta, + }; + }); + const resolveBaseBranch = Effect.fn("resolveBaseBranch")(function* ( cwd: string, branch: string, upstreamRef: string | null, - headContext: Pick, + headContext: Pick, ) { const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`); if (configured) return configured; if (upstreamRef && !headContext.isCrossRepository) { - const upstreamBranch = extractBranchFromRef(upstreamRef); + const upstreamBranch = extractBranchNameFromRemoteRef(upstreamRef, { + remoteName: headContext.remoteName, + }); if (upstreamBranch.length > 0 && upstreamBranch !== branch) { return upstreamBranch; } @@ -868,6 +1202,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { modelSelection: ModelSelection, cwd: string, fallbackBranch: string | null, + emit: GitActionProgressEmitter, ) { const details = yield* gitCore.statusDetails(cwd); const branch = details.branch ?? fallbackBranch; @@ -889,7 +1224,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { upstreamRef: details.upstreamRef, }); - const existing = yield* findOpenPr(cwd, headContext.headSelectors); + const existing = yield* findOpenPr(cwd, headContext); if (existing) { return { status: "opened_existing" as const, @@ -902,6 +1237,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { } const baseBranch = yield* resolveBaseBranch(cwd, branch, details.upstreamRef, headContext); + yield* emit({ + kind: "phase_started", + phase: "pr", + label: "Generating PR content...", + }); const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch); const generated = yield* textGeneration.generatePrContent({ @@ -922,6 +1262,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { gitManagerError("runPrStep", "Failed to write pull request body temp file.", cause), ), ); + yield* emit({ + kind: "phase_started", + phase: "pr", + label: "Creating GitHub pull request...", + }); yield* gitHubCli .createPullRequest({ cwd, @@ -932,7 +1277,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { }) .pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.catch(() => Effect.void)))); - const created = yield* findOpenPr(cwd, headContext.headSelectors); + const created = yield* findOpenPr(cwd, headContext); if (!created) { return { status: "created" as const, @@ -952,30 +1297,34 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { }; }); - const status: GitManagerShape["status"] = Effect.fn("status")(function* (input) { - const details = yield* gitCore.statusDetails(input.cwd); - - const pr = - details.branch !== null - ? yield* findLatestPr(input.cwd, { - branch: details.branch, - upstreamRef: details.upstreamRef, - }).pipe( - Effect.map((latest) => (latest ? toStatusPr(latest) : null)), - Effect.catch(() => Effect.succeed(null)), - ) - : null; - - return { - branch: details.branch, - hasWorkingTreeChanges: details.hasWorkingTreeChanges, - workingTree: details.workingTree, - hasUpstream: details.hasUpstream, - aheadCount: details.aheadCount, - behindCount: details.behindCount, - pr, - }; + const localStatus: GitManagerShape["localStatus"] = Effect.fn("localStatus")(function* (input) { + return yield* Cache.get(localStatusResultCache, normalizeStatusCacheKey(input.cwd)); }); + const remoteStatus: GitManagerShape["remoteStatus"] = Effect.fn("remoteStatus")( + function* (input) { + return yield* Cache.get(remoteStatusResultCache, normalizeStatusCacheKey(input.cwd)); + }, + ); + const status: GitManagerShape["status"] = Effect.fn("status")(function* (input) { + const [local, remote] = yield* Effect.all([localStatus(input), remoteStatus(input)]); + return mergeGitStatusParts(local, remote); + }); + const invalidateLocalStatus: GitManagerShape["invalidateLocalStatus"] = Effect.fn( + "invalidateLocalStatus", + )(function* (cwd) { + yield* invalidateLocalStatusResultCache(cwd); + }); + const invalidateRemoteStatus: GitManagerShape["invalidateRemoteStatus"] = Effect.fn( + "invalidateRemoteStatus", + )(function* (cwd) { + yield* invalidateRemoteStatusResultCache(cwd); + }); + const invalidateStatus: GitManagerShape["invalidateStatus"] = Effect.fn("invalidateStatus")( + function* (cwd) { + yield* invalidateLocalStatusResultCache(cwd); + yield* invalidateRemoteStatusResultCache(cwd); + }, + ); const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fn("resolvePullRequest")( function* (input) { @@ -993,143 +1342,164 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { 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({ + const maybeRunSetupScript = (worktreePath: string) => { + if (!input.threadId) { + return Effect.void; + } + return projectSetupScriptRunner + .runForThread({ + threadId: input.threadId, + projectCwd: input.cwd, + worktreePath, + }) + .pipe( + Effect.catch((error) => + Effect.logWarning( + `GitManager.preparePullRequestThread: failed to launch worktree setup script for thread ${input.threadId} in ${worktreePath}: ${error.message}`, + ).pipe(Effect.asVoid), + ), + ); + }; + return yield* Effect.gen(function* () { + const normalizedReference = normalizePullRequestReference(input.reference); + const rootWorktreePath = canonicalizeExistingPath(input.cwd); + const pullRequestSummary = yield* gitHubCli.getPullRequest({ cwd: input.cwd, reference: normalizedReference, - force: true, }); - const details = yield* gitCore.statusDetails(input.cwd); - yield* configurePullRequestHeadUpstream( + 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 = 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, - { - ...pullRequest, - ...toPullRequestHeadRemoteInfo(pullRequestSummary), - }, - details.branch ?? pullRequest.headBranch, - ); - return { - pullRequest, - branch: details.branch ?? pullRequest.headBranch, - worktreePath: null, - }; - } - - 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 - ); - }), + pullRequestWithRemoteInfo, + localPullRequestBranch, ); - 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, + 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, - 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.", - ); - } + path: null, + }); + yield* ensureExistingWorktreeUpstream(worktree.worktree.path); + yield* maybeRunSetupScript(worktree.worktree.path); - 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, + branch: worktree.worktree.branch, + worktreePath: worktree.worktree.path, }; - } - 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, - }; + }).pipe(Effect.ensuring(invalidateStatus(input.cwd))); }); const runFeatureBranchStep = Effect.fn("runFeatureBranchStep")(function* ( @@ -1171,27 +1541,53 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fn("runStackedAction")( function* (input, options) { const progress = createProgressEmitter(input, options); - const phases: GitActionProgressPhase[] = [ - ...(input.featureBranch ? (["branch"] as const) : []), - "commit", - ...(input.action !== "commit" ? (["push"] as const) : []), - ...(input.action === "commit_push_pr" ? (["pr"] as const) : []), - ]; const currentPhase = yield* Ref.make>(Option.none()); const runAction = Effect.fn("runStackedAction.runAction")(function* (): Effect.fn.Return< GitRunStackedActionResult, GitManagerServiceError > { + const initialStatus = yield* gitCore.statusDetails(input.cwd); + const wantsCommit = isCommitAction(input.action); + const wantsPush = + input.action === "push" || + input.action === "commit_push" || + input.action === "commit_push_pr" || + (input.action === "create_pr" && + (!initialStatus.hasUpstream || initialStatus.aheadCount > 0)); + const wantsPr = input.action === "create_pr" || input.action === "commit_push_pr"; + + if (input.featureBranch && !wantsCommit) { + return yield* gitManagerError( + "runStackedAction", + "Feature-branch checkout is only supported for commit actions.", + ); + } + if (input.action === "push" && initialStatus.hasWorkingTreeChanges) { + return yield* gitManagerError( + "runStackedAction", + "Commit or stash local changes before pushing.", + ); + } + if (input.action === "create_pr" && initialStatus.hasWorkingTreeChanges) { + return yield* gitManagerError( + "runStackedAction", + "Commit local changes before creating a PR.", + ); + } + + const phases: GitActionProgressPhase[] = [ + ...(input.featureBranch ? (["branch"] as const) : []), + ...(wantsCommit ? (["commit"] as const) : []), + ...(wantsPush ? (["push"] as const) : []), + ...(wantsPr ? (["pr"] as const) : []), + ]; + yield* progress.emit({ kind: "action_started", phases, }); - const wantsPush = input.action !== "commit"; - const wantsPr = input.action === "commit_push_pr"; - - const initialStatus = yield* gitCore.statusDetails(input.cwd); if (!input.featureBranch && wantsPush && !initialStatus.branch) { return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD."); } @@ -1235,19 +1631,25 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { } const currentBranch = branchStep.name ?? initialStatus.branch; + const commitAction = isCommitAction(input.action) ? input.action : null; - yield* Ref.set(currentPhase, Option.some("commit")); - const commit = yield* runCommitStep( - modelSelection, - input.cwd, - input.action, - currentBranch, - commitMessageForStep, - preResolvedCommitSuggestion, - input.filePaths, - options?.progressReporter, - progress.actionId, - ); + const commit = commitAction + ? yield* Ref.set(currentPhase, Option.some("commit")).pipe( + Effect.flatMap(() => + runCommitStep( + modelSelection, + input.cwd, + commitAction, + currentBranch, + commitMessageForStep, + preResolvedCommitSuggestion, + input.filePaths, + options?.progressReporter, + progress.actionId, + ), + ), + ) + : { status: "skipped_not_requested" as const }; const push = wantsPush ? yield* progress @@ -1267,20 +1669,31 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { .emit({ kind: "phase_started", phase: "pr", - label: "Creating PR...", + label: "Preparing PR...", }) .pipe( Effect.tap(() => Ref.set(currentPhase, Option.some("pr"))), - Effect.flatMap(() => runPrStep(modelSelection, input.cwd, currentBranch)), + Effect.flatMap(() => + runPrStep(modelSelection, input.cwd, currentBranch, progress.emit), + ), ) : { status: "skipped_not_requested" as const }; + const toast = yield* buildCompletionToast(input.cwd, { + action: input.action, + branch: branchStep, + commit, + push, + pr, + }); + const result = { action: input.action, branch: branchStep, commit, push, pr, + toast, }; yield* progress.emit({ kind: "action_finished", @@ -1290,6 +1703,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { }); return yield* runAction().pipe( + Effect.ensuring(invalidateStatus(input.cwd)), Effect.tapError((error) => Effect.flatMap(Ref.get(currentPhase), (phase) => progress.emit({ @@ -1304,7 +1718,12 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { ); return { + localStatus, + remoteStatus, status, + invalidateLocalStatus, + invalidateRemoteStatus, + invalidateStatus, resolvePullRequest, preparePullRequestThread, runStackedAction, diff --git a/apps/server/src/git/Layers/GitStatusBroadcaster.test.ts b/apps/server/src/git/Layers/GitStatusBroadcaster.test.ts new file mode 100644 index 0000000000..72a0c24e27 --- /dev/null +++ b/apps/server/src/git/Layers/GitStatusBroadcaster.test.ts @@ -0,0 +1,312 @@ +import { assert, it } from "@effect/vitest"; +import { Deferred, Effect, Exit, Layer, Option, Scope, Stream } from "effect"; +import type { + GitStatusLocalResult, + GitStatusRemoteResult, + GitStatusResult, + GitStatusStreamEvent, +} from "@t3tools/contracts"; +import { describe } from "vitest"; + +import { GitStatusBroadcaster } from "../Services/GitStatusBroadcaster.ts"; +import { GitStatusBroadcasterLive } from "./GitStatusBroadcaster.ts"; +import { type GitManagerShape, GitManager } from "../Services/GitManager.ts"; + +const baseLocalStatus: GitStatusLocalResult = { + isRepo: true, + hostingProvider: { + kind: "github", + name: "GitHub", + baseUrl: "https://github.com", + }, + hasOriginRemote: true, + isDefaultBranch: false, + branch: "feature/status-broadcast", + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, +}; + +const baseRemoteStatus: GitStatusRemoteResult = { + hasUpstream: true, + aheadCount: 0, + behindCount: 0, + pr: null, +}; + +const baseStatus: GitStatusResult = { + ...baseLocalStatus, + ...baseRemoteStatus, +}; + +function makeTestLayer(state: { + currentLocalStatus: GitStatusLocalResult; + currentRemoteStatus: GitStatusRemoteResult | null; + localStatusCalls: number; + remoteStatusCalls: number; + localInvalidationCalls: number; + remoteInvalidationCalls: number; +}) { + const gitManager: GitManagerShape = { + localStatus: () => + Effect.sync(() => { + state.localStatusCalls += 1; + return state.currentLocalStatus; + }), + remoteStatus: () => + Effect.sync(() => { + state.remoteStatusCalls += 1; + return state.currentRemoteStatus; + }), + status: () => Effect.die("status should not be called in this test"), + invalidateLocalStatus: () => + Effect.sync(() => { + state.localInvalidationCalls += 1; + }), + invalidateRemoteStatus: () => + Effect.sync(() => { + state.remoteInvalidationCalls += 1; + }), + invalidateStatus: () => Effect.die("invalidateStatus should not be called in this test"), + resolvePullRequest: () => Effect.die("resolvePullRequest should not be called in this test"), + preparePullRequestThread: () => + Effect.die("preparePullRequestThread should not be called in this test"), + runStackedAction: () => Effect.die("runStackedAction should not be called in this test"), + }; + + return GitStatusBroadcasterLive.pipe(Layer.provide(Layer.succeed(GitManager, gitManager))); +} + +describe("GitStatusBroadcasterLive", () => { + it.effect("reuses the cached git status across repeated reads", () => { + const state = { + currentLocalStatus: baseLocalStatus, + currentRemoteStatus: baseRemoteStatus, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + }; + + return Effect.gen(function* () { + const broadcaster = yield* GitStatusBroadcaster; + + const first = yield* broadcaster.getStatus({ cwd: "/repo" }); + const second = yield* broadcaster.getStatus({ cwd: "/repo" }); + + assert.deepStrictEqual(first, baseStatus); + assert.deepStrictEqual(second, baseStatus); + assert.equal(state.localStatusCalls, 1); + assert.equal(state.remoteStatusCalls, 1); + assert.equal(state.localInvalidationCalls, 0); + assert.equal(state.remoteInvalidationCalls, 0); + }).pipe(Effect.provide(makeTestLayer(state))); + }); + + it.effect("refreshes the cached snapshot after explicit invalidation", () => { + const state = { + currentLocalStatus: baseLocalStatus, + currentRemoteStatus: baseRemoteStatus, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + }; + + return Effect.gen(function* () { + const broadcaster = yield* GitStatusBroadcaster; + const initial = yield* broadcaster.getStatus({ cwd: "/repo" }); + + state.currentLocalStatus = { + ...baseLocalStatus, + branch: "feature/updated-status", + }; + state.currentRemoteStatus = { + ...baseRemoteStatus, + aheadCount: 2, + }; + const refreshed = yield* broadcaster.refreshStatus("/repo"); + const cached = yield* broadcaster.getStatus({ cwd: "/repo" }); + + assert.deepStrictEqual(initial, baseStatus); + assert.deepStrictEqual(refreshed, { + ...state.currentLocalStatus, + ...state.currentRemoteStatus, + }); + assert.deepStrictEqual(cached, { + ...state.currentLocalStatus, + ...state.currentRemoteStatus, + }); + assert.equal(state.localStatusCalls, 2); + assert.equal(state.remoteStatusCalls, 2); + assert.equal(state.localInvalidationCalls, 1); + assert.equal(state.remoteInvalidationCalls, 1); + }).pipe(Effect.provide(makeTestLayer(state))); + }); + + it.effect("refreshes only the cached local snapshot when requested", () => { + const state = { + currentLocalStatus: baseLocalStatus, + currentRemoteStatus: baseRemoteStatus, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + }; + + return Effect.gen(function* () { + const broadcaster = yield* GitStatusBroadcaster; + const initial = yield* broadcaster.getStatus({ cwd: "/repo" }); + + state.currentLocalStatus = { + ...baseLocalStatus, + branch: "feature/local-only-refresh", + hasWorkingTreeChanges: true, + }; + + const refreshedLocal = yield* broadcaster.refreshLocalStatus("/repo"); + const cached = yield* broadcaster.getStatus({ cwd: "/repo" }); + + assert.deepStrictEqual(initial, baseStatus); + assert.deepStrictEqual(refreshedLocal, state.currentLocalStatus); + assert.deepStrictEqual(cached, { + ...state.currentLocalStatus, + ...baseRemoteStatus, + }); + assert.equal(state.localStatusCalls, 2); + assert.equal(state.remoteStatusCalls, 1); + assert.equal(state.localInvalidationCalls, 1); + assert.equal(state.remoteInvalidationCalls, 0); + }).pipe(Effect.provide(makeTestLayer(state))); + }); + + it.effect("streams a local snapshot first and remote updates later", () => { + const state = { + currentLocalStatus: baseLocalStatus, + currentRemoteStatus: baseRemoteStatus, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + }; + + return Effect.gen(function* () { + const broadcaster = yield* GitStatusBroadcaster; + const snapshotDeferred = yield* Deferred.make(); + const remoteUpdatedDeferred = yield* Deferred.make(); + yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) => { + if (event._tag === "snapshot") { + return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore); + } + if (event._tag === "remoteUpdated") { + return Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore); + } + return Effect.void; + }).pipe(Effect.forkScoped); + + const snapshot = yield* Deferred.await(snapshotDeferred); + yield* broadcaster.refreshStatus("/repo"); + const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred); + + assert.deepStrictEqual(snapshot, { + _tag: "snapshot", + local: baseLocalStatus, + remote: null, + } satisfies GitStatusStreamEvent); + assert.deepStrictEqual(remoteUpdated, { + _tag: "remoteUpdated", + remote: baseRemoteStatus, + } satisfies GitStatusStreamEvent); + }).pipe(Effect.provide(makeTestLayer(state))); + }); + + it.effect("stops the remote poller after the last stream subscriber disconnects", () => { + const state = { + currentLocalStatus: baseLocalStatus, + currentRemoteStatus: baseRemoteStatus, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + }; + let remoteInterruptedDeferred: Deferred.Deferred | null = null; + let remoteStartedDeferred: Deferred.Deferred | null = null; + const testLayer = GitStatusBroadcasterLive.pipe( + Layer.provide( + Layer.succeed(GitManager, { + localStatus: () => + Effect.sync(() => { + state.localStatusCalls += 1; + return state.currentLocalStatus; + }), + remoteStatus: () => + Effect.sync(() => { + state.remoteStatusCalls += 1; + }).pipe( + Effect.andThen( + remoteStartedDeferred + ? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore) + : Effect.void, + ), + Effect.andThen(Effect.never as Effect.Effect), + Effect.onInterrupt(() => + remoteInterruptedDeferred + ? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore) + : Effect.void, + ), + ), + status: () => Effect.die("status should not be called in this test"), + invalidateLocalStatus: () => + Effect.sync(() => { + state.localInvalidationCalls += 1; + }), + invalidateRemoteStatus: () => + Effect.sync(() => { + state.remoteInvalidationCalls += 1; + }), + invalidateStatus: () => Effect.die("invalidateStatus should not be called in this test"), + resolvePullRequest: () => + Effect.die("resolvePullRequest should not be called in this test"), + preparePullRequestThread: () => + Effect.die("preparePullRequestThread should not be called in this test"), + runStackedAction: () => Effect.die("runStackedAction should not be called in this test"), + } satisfies GitManagerShape), + ), + ); + + return Effect.gen(function* () { + const remoteInterrupted = yield* Deferred.make(); + const remoteStarted = yield* Deferred.make(); + remoteInterruptedDeferred = remoteInterrupted; + remoteStartedDeferred = remoteStarted; + + const broadcaster = yield* GitStatusBroadcaster; + const firstSnapshot = yield* Deferred.make(); + const secondSnapshot = yield* Deferred.make(); + const firstScope = yield* Scope.make(); + const secondScope = yield* Scope.make(); + yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) => + event._tag === "snapshot" + ? Deferred.succeed(firstSnapshot, event).pipe(Effect.ignore) + : Effect.void, + ).pipe(Effect.forkIn(firstScope)); + yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) => + event._tag === "snapshot" + ? Deferred.succeed(secondSnapshot, event).pipe(Effect.ignore) + : Effect.void, + ).pipe(Effect.forkIn(secondScope)); + + yield* Deferred.await(firstSnapshot); + yield* Deferred.await(secondSnapshot); + yield* Deferred.await(remoteStarted); + + assert.equal(state.remoteStatusCalls, 1); + + yield* Scope.close(firstScope, Exit.void); + assert.equal(Option.isNone(yield* Deferred.poll(remoteInterrupted)), true); + + yield* Scope.close(secondScope, Exit.void).pipe(Effect.forkScoped); + yield* Deferred.await(remoteInterrupted); + assert.equal(Option.isSome(yield* Deferred.poll(remoteInterrupted)), true); + }).pipe(Effect.provide(testLayer)); + }); +}); diff --git a/apps/server/src/git/Layers/GitStatusBroadcaster.ts b/apps/server/src/git/Layers/GitStatusBroadcaster.ts new file mode 100644 index 0000000000..3ad7d095d8 --- /dev/null +++ b/apps/server/src/git/Layers/GitStatusBroadcaster.ts @@ -0,0 +1,311 @@ +import { realpathSync } from "node:fs"; + +import { + Duration, + Effect, + Exit, + Fiber, + Layer, + PubSub, + Ref, + Scope, + Stream, + SynchronizedRef, +} from "effect"; +import type { + GitStatusInput, + GitStatusLocalResult, + GitStatusRemoteResult, + GitStatusStreamEvent, +} from "@t3tools/contracts"; +import { mergeGitStatusParts } from "@t3tools/shared/git"; + +import { + GitStatusBroadcaster, + type GitStatusBroadcasterShape, +} from "../Services/GitStatusBroadcaster.ts"; +import { GitManager } from "../Services/GitManager.ts"; + +const GIT_STATUS_REFRESH_INTERVAL = Duration.seconds(30); + +interface GitStatusChange { + readonly cwd: string; + readonly event: GitStatusStreamEvent; +} + +interface CachedValue { + readonly fingerprint: string; + readonly value: T; +} + +interface CachedGitStatus { + readonly local: CachedValue | null; + readonly remote: CachedValue | null; +} + +interface ActiveRemotePoller { + readonly fiber: Fiber.Fiber; + readonly subscriberCount: number; +} + +function normalizeCwd(cwd: string): string { + try { + return realpathSync.native(cwd); + } catch { + return cwd; + } +} + +function fingerprintStatusPart(status: unknown): string { + return JSON.stringify(status); +} + +export const GitStatusBroadcasterLive = Layer.effect( + GitStatusBroadcaster, + Effect.gen(function* () { + const gitManager = yield* GitManager; + const changesPubSub = yield* Effect.acquireRelease( + PubSub.unbounded(), + (pubsub) => PubSub.shutdown(pubsub), + ); + const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) => + Scope.close(scope, Exit.void), + ); + const cacheRef = yield* Ref.make(new Map()); + const pollersRef = yield* SynchronizedRef.make(new Map()); + + const getCachedStatus = Effect.fn("getCachedStatus")(function* (cwd: string) { + return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null)); + }); + + const updateCachedLocalStatus = Effect.fn("updateCachedLocalStatus")(function* ( + cwd: string, + local: GitStatusLocalResult, + options?: { publish?: boolean }, + ) { + const nextLocal = { + fingerprint: fingerprintStatusPart(local), + value: local, + } satisfies CachedValue; + const shouldPublish = yield* Ref.modify(cacheRef, (cache) => { + const previous = cache.get(cwd) ?? { local: null, remote: null }; + const nextCache = new Map(cache); + nextCache.set(cwd, { + ...previous, + local: nextLocal, + }); + return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const; + }); + + if (options?.publish && shouldPublish) { + yield* PubSub.publish(changesPubSub, { + cwd, + event: { + _tag: "localUpdated", + local, + }, + }); + } + + return local; + }); + + const updateCachedRemoteStatus = Effect.fn("updateCachedRemoteStatus")(function* ( + cwd: string, + remote: GitStatusRemoteResult | null, + options?: { publish?: boolean }, + ) { + const nextRemote = { + fingerprint: fingerprintStatusPart(remote), + value: remote, + } satisfies CachedValue; + const shouldPublish = yield* Ref.modify(cacheRef, (cache) => { + const previous = cache.get(cwd) ?? { local: null, remote: null }; + const nextCache = new Map(cache); + nextCache.set(cwd, { + ...previous, + remote: nextRemote, + }); + return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const; + }); + + if (options?.publish && shouldPublish) { + yield* PubSub.publish(changesPubSub, { + cwd, + event: { + _tag: "remoteUpdated", + remote, + }, + }); + } + + return remote; + }); + + const loadLocalStatus = Effect.fn("loadLocalStatus")(function* (cwd: string) { + const local = yield* gitManager.localStatus({ cwd }); + return yield* updateCachedLocalStatus(cwd, local); + }); + + const loadRemoteStatus = Effect.fn("loadRemoteStatus")(function* (cwd: string) { + const remote = yield* gitManager.remoteStatus({ cwd }); + return yield* updateCachedRemoteStatus(cwd, remote); + }); + + const getOrLoadLocalStatus = Effect.fn("getOrLoadLocalStatus")(function* (cwd: string) { + const cached = yield* getCachedStatus(cwd); + if (cached?.local) { + return cached.local.value; + } + return yield* loadLocalStatus(cwd); + }); + + const getOrLoadRemoteStatus = Effect.fn("getOrLoadRemoteStatus")(function* (cwd: string) { + const cached = yield* getCachedStatus(cwd); + if (cached?.remote) { + return cached.remote.value; + } + return yield* loadRemoteStatus(cwd); + }); + + const getStatus: GitStatusBroadcasterShape["getStatus"] = Effect.fn("getStatus")(function* ( + input: GitStatusInput, + ) { + const normalizedCwd = normalizeCwd(input.cwd); + const [local, remote] = yield* Effect.all([ + getOrLoadLocalStatus(normalizedCwd), + getOrLoadRemoteStatus(normalizedCwd), + ]); + return mergeGitStatusParts(local, remote); + }); + + const refreshLocalStatus: GitStatusBroadcasterShape["refreshLocalStatus"] = Effect.fn( + "refreshLocalStatus", + )(function* (cwd) { + const normalizedCwd = normalizeCwd(cwd); + yield* gitManager.invalidateLocalStatus(normalizedCwd); + const local = yield* gitManager.localStatus({ cwd: normalizedCwd }); + return yield* updateCachedLocalStatus(normalizedCwd, local, { publish: true }); + }); + + const refreshRemoteStatus = Effect.fn("refreshRemoteStatus")(function* (cwd: string) { + yield* gitManager.invalidateRemoteStatus(cwd); + const remote = yield* gitManager.remoteStatus({ cwd }); + return yield* updateCachedRemoteStatus(cwd, remote, { publish: true }); + }); + + const refreshStatus: GitStatusBroadcasterShape["refreshStatus"] = Effect.fn("refreshStatus")( + function* (cwd) { + const normalizedCwd = normalizeCwd(cwd); + const [local, remote] = yield* Effect.all([ + refreshLocalStatus(normalizedCwd), + refreshRemoteStatus(normalizedCwd), + ]); + return mergeGitStatusParts(local, remote); + }, + ); + + const makeRemoteRefreshLoop = (cwd: string) => { + const logRefreshFailure = (error: Error) => + Effect.logWarning("git remote status refresh failed", { + cwd, + detail: error.message, + }); + + return refreshRemoteStatus(cwd).pipe( + Effect.catch(logRefreshFailure), + Effect.andThen( + Effect.forever( + Effect.sleep(GIT_STATUS_REFRESH_INTERVAL).pipe( + Effect.andThen(refreshRemoteStatus(cwd).pipe(Effect.catch(logRefreshFailure))), + ), + ), + ), + ); + }; + + const retainRemotePoller = Effect.fn("retainRemotePoller")(function* (cwd: string) { + yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => { + const existing = activePollers.get(cwd); + if (existing) { + const nextPollers = new Map(activePollers); + nextPollers.set(cwd, { + ...existing, + subscriberCount: existing.subscriberCount + 1, + }); + return Effect.succeed([undefined, nextPollers] as const); + } + + return makeRemoteRefreshLoop(cwd).pipe( + Effect.forkIn(broadcasterScope), + Effect.map((fiber) => { + const nextPollers = new Map(activePollers); + nextPollers.set(cwd, { + fiber, + subscriberCount: 1, + }); + return [undefined, nextPollers] as const; + }), + ); + }); + }); + + const releaseRemotePoller = Effect.fn("releaseRemotePoller")(function* (cwd: string) { + const pollerToInterrupt = yield* SynchronizedRef.modify(pollersRef, (activePollers) => { + const existing = activePollers.get(cwd); + if (!existing) { + return [null, activePollers] as const; + } + + if (existing.subscriberCount > 1) { + const nextPollers = new Map(activePollers); + nextPollers.set(cwd, { + ...existing, + subscriberCount: existing.subscriberCount - 1, + }); + return [null, nextPollers] as const; + } + + const nextPollers = new Map(activePollers); + nextPollers.delete(cwd); + return [existing.fiber, nextPollers] as const; + }); + + if (pollerToInterrupt) { + yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore); + } + }); + + const streamStatus: GitStatusBroadcasterShape["streamStatus"] = (input) => + Stream.unwrap( + Effect.gen(function* () { + const normalizedCwd = normalizeCwd(input.cwd); + const subscription = yield* PubSub.subscribe(changesPubSub); + const initialLocal = yield* getOrLoadLocalStatus(normalizedCwd); + const initialRemote = (yield* getCachedStatus(normalizedCwd))?.remote?.value ?? null; + yield* retainRemotePoller(normalizedCwd); + + const release = releaseRemotePoller(normalizedCwd).pipe(Effect.ignore, Effect.asVoid); + + return Stream.concat( + Stream.make({ + _tag: "snapshot" as const, + local: initialLocal, + remote: initialRemote, + }), + Stream.fromSubscription(subscription).pipe( + Stream.filter((event) => event.cwd === normalizedCwd), + Stream.map((event) => event.event), + ), + ).pipe(Stream.ensuring(release)); + }), + ); + + return { + getStatus, + refreshLocalStatus, + refreshStatus, + streamStatus, + } satisfies GitStatusBroadcasterShape; + }), +); diff --git a/apps/server/src/git/Layers/RoutingTextGeneration.ts b/apps/server/src/git/Layers/RoutingTextGeneration.ts index dee12a3e0e..5372bc1349 100644 --- a/apps/server/src/git/Layers/RoutingTextGeneration.ts +++ b/apps/server/src/git/Layers/RoutingTextGeneration.ts @@ -9,7 +9,7 @@ * * @module RoutingTextGeneration */ -import { Effect, Layer, ServiceMap } from "effect"; +import { Effect, Layer, Context } from "effect"; import { TextGeneration, @@ -23,11 +23,11 @@ import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts"; // Internal service tags so both concrete layers can coexist. // --------------------------------------------------------------------------- -class CodexTextGen extends ServiceMap.Service()( +class CodexTextGen extends Context.Service()( "t3/git/Layers/RoutingTextGeneration/CodexTextGen", ) {} -class ClaudeTextGen extends ServiceMap.Service()( +class ClaudeTextGen extends Context.Service()( "t3/git/Layers/RoutingTextGeneration/ClaudeTextGen", ) {} diff --git a/apps/server/src/git/Prompts.test.ts b/apps/server/src/git/Prompts.test.ts index 7951e78b39..d8d079c0cf 100644 --- a/apps/server/src/git/Prompts.test.ts +++ b/apps/server/src/git/Prompts.test.ts @@ -7,7 +7,7 @@ import { buildThreadTitlePrompt, } from "./Prompts.ts"; import { normalizeCliError, sanitizeThreadTitle } from "./Utils.ts"; -import { TextGenerationError } from "./Errors.ts"; +import { TextGenerationError } from "@t3tools/contracts"; describe("buildCommitMessagePrompt", () => { it("includes staged patch and summary in the prompt", () => { diff --git a/apps/server/src/git/Services/GitCore.ts b/apps/server/src/git/Services/GitCore.ts index 3c30f17121..9f3bc0b9b9 100644 --- a/apps/server/src/git/Services/GitCore.ts +++ b/apps/server/src/git/Services/GitCore.ts @@ -6,11 +6,13 @@ * * @module GitCore */ -import { ServiceMap } from "effect"; -import type { Effect, Scope } from "effect"; +import { Context } from "effect"; +import type { Effect } from "effect"; import type { GitCheckoutInput, + GitCheckoutResult, GitCreateBranchInput, + GitCreateBranchResult, GitCreateWorktreeInput, GitCreateWorktreeResult, GitInitInput, @@ -22,7 +24,7 @@ import type { GitStatusResult, } from "@t3tools/contracts"; -import type { GitCommandError } from "../Errors.ts"; +import type { GitCommandError } from "@t3tools/contracts"; export interface ExecuteGitInput { readonly operation: string; @@ -156,6 +158,11 @@ export interface GitCoreShape { */ readonly statusDetails: (cwd: string) => Effect.Effect; + /** + * Read detailed working tree / branch status without refreshing remote tracking refs. + */ + readonly statusDetailsLocal: (cwd: string) => Effect.Effect; + /** * Build staged change context for commit generation. */ @@ -278,14 +285,16 @@ export interface GitCoreShape { /** * Create a local branch. */ - readonly createBranch: (input: GitCreateBranchInput) => Effect.Effect; + readonly createBranch: ( + input: GitCreateBranchInput, + ) => Effect.Effect; /** * Checkout an existing branch and refresh its upstream metadata in background. */ readonly checkoutBranch: ( input: GitCheckoutInput, - ) => Effect.Effect; + ) => Effect.Effect; /** * Initialize a repository in the provided directory. @@ -301,6 +310,4 @@ export interface GitCoreShape { /** * GitCore - Service tag for low-level Git repository operations. */ -export class GitCore extends ServiceMap.Service()( - "t3/git/Services/GitCore", -) {} +export class GitCore extends Context.Service()("t3/git/Services/GitCore") {} diff --git a/apps/server/src/git/Services/GitHubCli.ts b/apps/server/src/git/Services/GitHubCli.ts index f10339af47..216c24bf7c 100644 --- a/apps/server/src/git/Services/GitHubCli.ts +++ b/apps/server/src/git/Services/GitHubCli.ts @@ -5,11 +5,11 @@ * * @module GitHubCli */ -import { ServiceMap } from "effect"; +import { Context } 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; @@ -98,6 +98,6 @@ export interface GitHubCliShape { /** * GitHubCli - Service tag for GitHub CLI process execution. */ -export class GitHubCli extends ServiceMap.Service()( +export class GitHubCli extends Context.Service()( "t3/git/Services/GitHubCli", ) {} diff --git a/apps/server/src/git/Services/GitManager.ts b/apps/server/src/git/Services/GitManager.ts index 2e83b78c3b..29c762195e 100644 --- a/apps/server/src/git/Services/GitManager.ts +++ b/apps/server/src/git/Services/GitManager.ts @@ -14,12 +14,14 @@ import { GitResolvePullRequestResult, GitRunStackedActionInput, GitRunStackedActionResult, + GitStatusLocalResult, + GitStatusRemoteResult, GitStatusInput, GitStatusResult, } from "@t3tools/contracts"; -import { ServiceMap } from "effect"; +import { Context } 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; @@ -41,6 +43,35 @@ export interface GitManagerShape { input: GitStatusInput, ) => Effect.Effect; + /** + * Read local repository status without remote hosting enrichment. + */ + readonly localStatus: ( + input: GitStatusInput, + ) => Effect.Effect; + + /** + * Read remote tracking / PR status for a repository. + */ + readonly remoteStatus: ( + input: GitStatusInput, + ) => Effect.Effect; + + /** + * Clear any cached local status snapshot for a repository. + */ + readonly invalidateLocalStatus: (cwd: string) => Effect.Effect; + + /** + * Clear any cached remote status snapshot for a repository. + */ + readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect; + + /** + * Clear any cached status snapshot for a repository so the next read is fresh. + */ + readonly invalidateStatus: (cwd: string) => Effect.Effect; + /** * Resolve a pull request by URL/number against the current repository. */ @@ -56,7 +87,7 @@ export interface GitManagerShape { ) => Effect.Effect; /** - * Run a stacked Git action (`commit`, `commit_push`, `commit_push_pr`). + * Run a Git action (`commit`, `push`, `create_pr`, `commit_push`, `commit_push_pr`). * When `featureBranch` is set, creates and checks out a feature branch first. */ readonly runStackedAction: ( @@ -68,6 +99,6 @@ export interface GitManagerShape { /** * GitManager - Service tag for stacked Git workflow orchestration. */ -export class GitManager extends ServiceMap.Service()( +export class GitManager extends Context.Service()( "t3/git/Services/GitManager", ) {} diff --git a/apps/server/src/git/Services/GitStatusBroadcaster.ts b/apps/server/src/git/Services/GitStatusBroadcaster.ts new file mode 100644 index 0000000000..647f840824 --- /dev/null +++ b/apps/server/src/git/Services/GitStatusBroadcaster.ts @@ -0,0 +1,27 @@ +import { Context } from "effect"; +import type { Effect, Stream } from "effect"; +import type { + GitManagerServiceError, + GitStatusInput, + GitStatusLocalResult, + GitStatusResult, + GitStatusStreamEvent, +} from "@t3tools/contracts"; + +export interface GitStatusBroadcasterShape { + readonly getStatus: ( + input: GitStatusInput, + ) => Effect.Effect; + readonly refreshLocalStatus: ( + cwd: string, + ) => Effect.Effect; + readonly refreshStatus: (cwd: string) => Effect.Effect; + readonly streamStatus: ( + input: GitStatusInput, + ) => Stream.Stream; +} + +export class GitStatusBroadcaster extends Context.Service< + GitStatusBroadcaster, + GitStatusBroadcasterShape +>()("t3/git/Services/GitStatusBroadcaster") {} diff --git a/apps/server/src/git/Services/TextGeneration.ts b/apps/server/src/git/Services/TextGeneration.ts index 0df2fff62c..6062d552d9 100644 --- a/apps/server/src/git/Services/TextGeneration.ts +++ b/apps/server/src/git/Services/TextGeneration.ts @@ -6,11 +6,11 @@ * * @module TextGeneration */ -import { ServiceMap } from "effect"; +import { Context } 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"; @@ -118,6 +118,6 @@ export interface TextGenerationShape { /** * TextGeneration - Service tag for commit and PR text generation. */ -export class TextGeneration extends ServiceMap.Service()( +export class TextGeneration extends Context.Service()( "t3/git/Services/TextGeneration", ) {} diff --git a/apps/server/src/git/Utils.ts b/apps/server/src/git/Utils.ts index 8f0321fd52..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"; diff --git a/apps/server/src/git/githubPullRequests.ts b/apps/server/src/git/githubPullRequests.ts new file mode 100644 index 0000000000..d137a46d6f --- /dev/null +++ b/apps/server/src/git/githubPullRequests.ts @@ -0,0 +1,128 @@ +import { Cause, Exit, Result, Schema } from "effect"; +import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts"; +import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson"; + +export interface NormalizedGitHubPullRequestRecord { + readonly number: number; + readonly title: string; + readonly url: string; + readonly baseRefName: string; + readonly headRefName: string; + readonly state: "open" | "closed" | "merged"; + readonly updatedAt: string | null; + readonly isCrossRepository?: boolean; + readonly headRepositoryNameWithOwner?: string | null; + readonly headRepositoryOwnerLogin?: string | null; +} + +const GitHubPullRequestSchema = Schema.Struct({ + number: PositiveInt, + title: TrimmedNonEmptyString, + url: TrimmedNonEmptyString, + baseRefName: TrimmedNonEmptyString, + headRefName: TrimmedNonEmptyString, + state: Schema.optional(Schema.NullOr(Schema.String)), + mergedAt: Schema.optional(Schema.NullOr(Schema.String)), + updatedAt: Schema.optional(Schema.NullOr(Schema.String)), + isCrossRepository: Schema.optional(Schema.Boolean), + headRepository: Schema.optional( + Schema.NullOr( + Schema.Struct({ + nameWithOwner: Schema.String, + }), + ), + ), + headRepositoryOwner: Schema.optional( + Schema.NullOr( + Schema.Struct({ + login: Schema.String, + }), + ), + ), +}); + +function trimOptionalString(value: string | null | undefined): string | null { + const trimmed = value?.trim() ?? ""; + return trimmed.length > 0 ? trimmed : null; +} + +function normalizeGitHubPullRequestState(input: { + state?: string | null | undefined; + mergedAt?: string | null | undefined; +}): "open" | "closed" | "merged" { + const normalizedState = input.state?.trim().toUpperCase(); + if ( + (typeof input.mergedAt === "string" && input.mergedAt.trim().length > 0) || + normalizedState === "MERGED" + ) { + return "merged"; + } + if (normalizedState === "CLOSED") { + return "closed"; + } + return "open"; +} + +function normalizeGitHubPullRequestRecord( + raw: Schema.Schema.Type, +): NormalizedGitHubPullRequestRecord { + const headRepositoryNameWithOwner = trimOptionalString(raw.headRepository?.nameWithOwner); + const headRepositoryOwnerLogin = + trimOptionalString(raw.headRepositoryOwner?.login) ?? + (typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/") + ? (headRepositoryNameWithOwner.split("/")[0] ?? null) + : null); + + return { + number: raw.number, + title: raw.title, + url: raw.url, + baseRefName: raw.baseRefName, + headRefName: raw.headRefName, + state: normalizeGitHubPullRequestState(raw), + updatedAt: + typeof raw.updatedAt === "string" && raw.updatedAt.trim().length > 0 ? raw.updatedAt : null, + ...(typeof raw.isCrossRepository === "boolean" + ? { isCrossRepository: raw.isCrossRepository } + : {}), + ...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}), + ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), + }; +} + +const decodeGitHubPullRequestList = decodeJsonResult(Schema.Array(Schema.Unknown)); +const decodeGitHubPullRequest = decodeJsonResult(GitHubPullRequestSchema); +const decodeGitHubPullRequestEntry = Schema.decodeUnknownExit(GitHubPullRequestSchema); + +export const formatGitHubJsonDecodeError = formatSchemaError; + +export function decodeGitHubPullRequestListJson( + raw: string, +): Result.Result< + ReadonlyArray, + Cause.Cause +> { + const result = decodeGitHubPullRequestList(raw); + if (Result.isSuccess(result)) { + const pullRequests: NormalizedGitHubPullRequestRecord[] = []; + for (const entry of result.success) { + const decodedEntry = decodeGitHubPullRequestEntry(entry); + if (Exit.isFailure(decodedEntry)) { + continue; + } + pullRequests.push(normalizeGitHubPullRequestRecord(decodedEntry.value)); + } + return Result.succeed(pullRequests); + } + return Result.fail(result.failure); +} + +export function decodeGitHubPullRequestJson( + raw: string, +): Result.Result> { + const result = decodeGitHubPullRequest(raw); + if (Result.isSuccess(result)) { + return Result.succeed(normalizeGitHubPullRequestRecord(result.success)); + } + return Result.fail(result.failure); +} diff --git a/apps/server/src/git/remoteRefs.ts b/apps/server/src/git/remoteRefs.ts new file mode 100644 index 0000000000..b5dfc87bd0 --- /dev/null +++ b/apps/server/src/git/remoteRefs.ts @@ -0,0 +1,67 @@ +export function parseRemoteNamesInGitOrder(stdout: string): ReadonlyArray { + return stdout + .split("\n") + .map((line) => line.trim()) + .filter((line) => line.length > 0); +} + +export function parseRemoteNames(stdout: string): ReadonlyArray { + return parseRemoteNamesInGitOrder(stdout).toSorted((a, b) => b.length - a.length); +} + +export function parseRemoteRefWithRemoteNames( + ref: string, + remoteNames: ReadonlyArray, +): { remoteRef: string; remoteName: string; branchName: string } | null { + const trimmedRef = ref.trim(); + if (trimmedRef.length === 0) { + return null; + } + + for (const remoteName of remoteNames) { + const remotePrefix = `${remoteName}/`; + if (!trimmedRef.startsWith(remotePrefix)) { + continue; + } + const branchName = trimmedRef.slice(remotePrefix.length).trim(); + if (branchName.length === 0) { + return null; + } + return { + remoteRef: trimmedRef, + remoteName, + branchName, + }; + } + + return null; +} + +export function extractBranchNameFromRemoteRef( + ref: string, + options?: { + remoteName?: string | null; + remoteNames?: ReadonlyArray; + }, +): string { + const normalized = ref.trim(); + if (normalized.length === 0) { + return ""; + } + + if (normalized.startsWith("refs/remotes/")) { + return extractBranchNameFromRemoteRef(normalized.slice("refs/remotes/".length), options); + } + + const remoteNames = options?.remoteName ? [options.remoteName] : (options?.remoteNames ?? []); + const parsedRemoteRef = parseRemoteRefWithRemoteNames(normalized, remoteNames); + if (parsedRemoteRef) { + return parsedRemoteRef.branchName; + } + + const firstSlash = normalized.indexOf("/"); + if (firstSlash === -1) { + return normalized; + } + return normalized.slice(firstSlash + 1).trim(); +} diff --git a/apps/server/src/http.test.ts b/apps/server/src/http.test.ts new file mode 100644 index 0000000000..de861cc664 --- /dev/null +++ b/apps/server/src/http.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from "vitest"; + +import { isLoopbackHostname, resolveDevRedirectUrl } from "./http.ts"; + +describe("http dev routing", () => { + it("treats localhost and loopback addresses as local", () => { + expect(isLoopbackHostname("127.0.0.1")).toBe(true); + expect(isLoopbackHostname("localhost")).toBe(true); + expect(isLoopbackHostname("::1")).toBe(true); + expect(isLoopbackHostname("[::1]")).toBe(true); + }); + + it("does not treat LAN addresses as local", () => { + expect(isLoopbackHostname("192.168.86.35")).toBe(false); + expect(isLoopbackHostname("10.0.0.24")).toBe(false); + expect(isLoopbackHostname("example.local")).toBe(false); + }); + + it("preserves path and query when redirecting to the dev server", () => { + const devUrl = new URL("http://127.0.0.1:5173/"); + const requestUrl = new URL("http://127.0.0.1:3774/pair?token=test-token"); + + expect(resolveDevRedirectUrl(devUrl, requestUrl)).toBe( + "http://127.0.0.1:5173/pair?token=test-token", + ); + }); +}); diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts new file mode 100644 index 0000000000..ed40389429 --- /dev/null +++ b/apps/server/src/http.ts @@ -0,0 +1,311 @@ +import Mime from "@effect/platform-node/Mime"; +import { Data, Effect, FileSystem, Option, Path } from "effect"; +import { cast } from "effect/Function"; +import { + HttpBody, + HttpClient, + HttpClientResponse, + HttpRouter, + HttpServerResponse, + HttpServerRequest, +} from "effect/unstable/http"; +import { OtlpTracer } from "effect/unstable/observability"; + +import { + ATTACHMENTS_ROUTE_PREFIX, + normalizeAttachmentRelativePath, + resolveAttachmentRelativePath, +} from "./attachmentPaths"; +import { resolveAttachmentPathById } from "./attachmentStore"; +import { resolveStaticDir, ServerConfig } from "./config"; +import { decodeOtlpTraceRecords } from "./observability/TraceRecord.ts"; +import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts"; +import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver"; +import { ServerAuth } from "./auth/Services/ServerAuth.ts"; +import { respondToAuthError } from "./auth/http.ts"; +import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts"; + +const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600"; +const FALLBACK_PROJECT_FAVICON_SVG = ``; +const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces"; +const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]); + +export const browserApiCorsLayer = HttpRouter.cors({ + allowedMethods: ["GET", "POST", "OPTIONS"], + allowedHeaders: ["authorization", "b3", "traceparent", "content-type"], + maxAge: 600, +}); + +export function isLoopbackHostname(hostname: string): boolean { + const normalizedHostname = hostname + .trim() + .toLowerCase() + .replace(/^\[(.*)\]$/, "$1"); + return LOOPBACK_HOSTNAMES.has(normalizedHostname); +} + +export function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string { + const redirectUrl = new URL(devUrl.toString()); + redirectUrl.pathname = requestUrl.pathname; + redirectUrl.search = requestUrl.search; + redirectUrl.hash = requestUrl.hash; + return redirectUrl.toString(); +} + +const requireAuthenticatedRequest = Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const serverAuth = yield* ServerAuth; + yield* serverAuth.authenticateHttpRequest(request); +}); + +export const serverEnvironmentRouteLayer = HttpRouter.add( + "GET", + "/.well-known/t3/environment", + Effect.gen(function* () { + const descriptor = yield* Effect.service(ServerEnvironment).pipe( + Effect.flatMap((serverEnvironment) => serverEnvironment.getDescriptor), + ); + return HttpServerResponse.jsonUnsafe(descriptor, { status: 200 }); + }), +); + +class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{ + readonly cause: unknown; + readonly bodyJson: OtlpTracer.TraceData; +}> {} + +export const otlpTracesProxyRouteLayer = HttpRouter.add( + "POST", + OTLP_TRACES_PROXY_PATH, + Effect.gen(function* () { + yield* requireAuthenticatedRequest; + const request = yield* HttpServerRequest.HttpServerRequest; + const config = yield* ServerConfig; + const otlpTracesUrl = config.otlpTracesUrl; + const browserTraceCollector = yield* BrowserTraceCollector; + const httpClient = yield* HttpClient.HttpClient; + const bodyJson = cast(yield* request.json); + + yield* Effect.try({ + try: () => decodeOtlpTraceRecords(bodyJson), + catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }), + }).pipe( + Effect.flatMap((records) => browserTraceCollector.record(records)), + Effect.catch((cause) => + Effect.logWarning("Failed to decode browser OTLP traces", { + cause, + bodyJson, + }), + ), + ); + + if (otlpTracesUrl === undefined) { + return HttpServerResponse.empty({ status: 204 }); + } + + return yield* httpClient + .post(otlpTracesUrl, { + body: HttpBody.jsonUnsafe(bodyJson), + }) + .pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.as(HttpServerResponse.empty({ status: 204 })), + Effect.tapError((cause) => + Effect.logWarning("Failed to export browser OTLP traces", { + cause, + otlpTracesUrl, + }), + ), + Effect.catch(() => + Effect.succeed(HttpServerResponse.text("Trace export failed.", { status: 502 })), + ), + ); + }).pipe(Effect.catchTag("AuthError", respondToAuthError)), +); + +export const attachmentsRouteLayer = HttpRouter.add( + "GET", + `${ATTACHMENTS_ROUTE_PREFIX}/*`, + Effect.gen(function* () { + yield* requireAuthenticatedRequest; + 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 })), + ), + ); + }).pipe(Effect.catchTag("AuthError", respondToAuthError)), +); + +export const projectFaviconRouteLayer = HttpRouter.add( + "GET", + "/api/project-favicon", + Effect.gen(function* () { + yield* requireAuthenticatedRequest; + 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 })), + ), + ); + }).pipe(Effect.catchTag("AuthError", respondToAuthError)), +); + +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 && isLoopbackHostname(url.value.hostname)) { + return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), { + status: 302, + }); + } + + const staticDir = config.staticDir ?? (config.devUrl ? yield* resolveStaticDir() : undefined); + if (!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(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 542d750c77..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 * as DesktopLauncher from "./process/Layers/DesktopLauncher"; -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(DesktopLauncher.layer), - Layer.provideMerge(NetService.layer), - Layer.provideMerge(NodeServices.layer), - Layer.provideMerge(FetchHttpClient.layer), -); - -Command.run(t3Cli, { version }).pipe(Effect.provide(RuntimeLayer), NodeRuntime.runMain); diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index 9cf0394142..e3f190ff06 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -2,19 +2,19 @@ import { KeybindingCommand, KeybindingRule, KeybindingsConfig } from "@t3tools/c import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { assertFailure } from "@effect/vitest/utils"; -import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect"; +import { Cause, Effect, FileSystem, Layer, Logger, Path, Schema } from "effect"; 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 = () => { @@ -149,6 +149,23 @@ it.layer(NodeServices.layer)("keybindings", (it) => { }), ); + it.effect("formats invalid resolved keybinding rules with the custom message", () => + Effect.sync(() => { + const result = Schema.decodeUnknownExit(ResolvedKeybindingFromConfig)({ + key: "mod+shift+d+o", + command: "terminal.new", + }); + + if (result._tag !== "Failure") { + assert.fail("Expected invalid keybinding decode to fail"); + } + + const detail = Cause.pretty(result.cause); + assert.isTrue(detail.includes("Invalid keybinding rule")); + assert.isFalse(detail.includes("Invalid data")); + }), + ); + it.effect("bootstraps default keybindings when config file is missing", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts index 176e0300ad..19c96bd547 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -9,6 +9,7 @@ import { KeybindingRule, KeybindingsConfig, + KeybindingsConfigError, KeybindingShortcut, KeybindingWhenNode, MAX_KEYBINDINGS_COUNT, @@ -38,7 +39,7 @@ import { SchemaIssue, SchemaTransformation, Ref, - ServiceMap, + Context, Scope, Stream, } from "effect"; @@ -46,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" } @@ -334,7 +322,7 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe( Predicate.isNotNull, () => new SchemaIssue.InvalidValue(Option.some(rule), { - title: "Invalid keybinding rule", + message: "Invalid keybinding rule", }), ), Effect.map((resolved) => resolved), @@ -346,7 +334,7 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe( if (!key) { return yield* Effect.fail( new SchemaIssue.InvalidValue(Option.some(resolved), { - title: "Resolved shortcut cannot be encoded to key string", + message: "Resolved shortcut cannot be encoded to key string", }), ); } @@ -533,7 +521,7 @@ export interface KeybindingsShape { /** * Keybindings - Service tag for keybinding configuration operations. */ -export class Keybindings extends ServiceMap.Service()( +export class Keybindings extends Context.Service()( "t3/keybindings", ) {} 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 8fa75b4ac5..0000000000 --- a/apps/server/src/main.test.ts +++ /dev/null @@ -1,415 +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 { DesktopLauncher, type DesktopLauncherShape } from "./process/Services/DesktopLauncher"; -import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery"; -import { AnalyticsService } from "./telemetry/Services/AnalyticsService"; -import { Server, type ServerShape } from "./wsServer"; -import { ServerSettingsService } from "./serverSettings"; - -const start = vi.fn(() => undefined); -const stop = vi.fn(() => undefined); -const fixPath = vi.fn(() => undefined); -let resolvedConfig: ServerConfigShape | null = null; -const serverStart = Effect.acquireRelease( - Effect.gen(function* () { - resolvedConfig = yield* ServerConfig; - start(); - return {} as unknown as Http.Server; - }), - () => Effect.sync(() => stop()), -); -const findAvailablePort = vi.fn((preferred: number) => Effect.succeed(preferred)); - -// Shared service layer used by this CLI test suite. -const testLayer = Layer.mergeAll( - Layer.succeed(CliConfig, { - cwd: "/tmp/t3-test-workspace", - fixPath: Effect.sync(fixPath), - resolveStaticDir: Effect.undefined, - } satisfies CliConfigShape), - Layer.succeed(NetService, { - canListenOnHost: () => Effect.succeed(true), - isPortAvailableOnLoopback: () => Effect.succeed(true), - reserveLoopbackPort: () => Effect.succeed(0), - findAvailablePort, - }), - Layer.succeed(Server, { - start: serverStart, - stopSignal: Effect.void, - } satisfies ServerShape), - Layer.succeed(DesktopLauncher, { - getAvailableEditors: Effect.succeed([]), - openExternal: () => Effect.void, - openBrowser: (_target: string) => Effect.void, - openInEditor: () => Effect.void, - } satisfies DesktopLauncherShape), - ServerSettingsService.layerTest(), - AnalyticsService.layerTest, - FetchHttpClient.layer, - NodeServices.layer, -); - -const runCli = ( - args: ReadonlyArray, - env: Record = { T3CODE_NO_BROWSER: "true" }, -) => { - return Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe( - Effect.provide( - ConfigProvider.layer( - ConfigProvider.fromEnv({ - env: { - ...env, - }, - }), - ), - ), - ); -}; - -beforeEach(() => { - vi.clearAllMocks(); - resolvedConfig = null; - start.mockImplementation(() => undefined); - stop.mockImplementation(() => undefined); - fixPath.mockImplementation(() => undefined); - findAvailablePort.mockImplementation((preferred: number) => Effect.succeed(preferred)); -}); - -it.layer(testLayer)("server CLI command", (it) => { - it.effect("parses all CLI flags and wires scoped start/stop", () => - Effect.gen(function* () { - yield* runCli([ - "--mode", - "desktop", - "--port", - "4010", - "--host", - "0.0.0.0", - "--home-dir", - "/tmp/t3-cli-home", - "--dev-url", - "http://127.0.0.1:5173", - "--no-browser", - "--auth-token", - "auth-secret", - ]); - - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.mode, "desktop"); - assert.equal(resolvedConfig?.port, 4010); - assert.equal(resolvedConfig?.host, "0.0.0.0"); - assert.equal(resolvedConfig?.baseDir, "/tmp/t3-cli-home"); - assert.equal(resolvedConfig?.stateDir, "/tmp/t3-cli-home/dev"); - assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/"); - assert.equal(resolvedConfig?.noBrowser, true); - assert.equal(resolvedConfig?.authToken, "auth-secret"); - assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, false); - assert.equal(resolvedConfig?.logWebSocketEvents, true); - assert.equal(stop.mock.calls.length, 1); - }), - ); - - it.effect("supports --token as an alias for --auth-token", () => - Effect.gen(function* () { - yield* runCli(["--token", "token-secret"]); - - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.authToken, "token-secret"); - }), - ); - - it.effect("uses env fallbacks when flags are not provided", () => - Effect.gen(function* () { - yield* runCli([], { - T3CODE_MODE: "desktop", - T3CODE_PORT: "4999", - T3CODE_HOST: "100.88.10.4", - T3CODE_HOME: "/tmp/t3-env-home", - VITE_DEV_SERVER_URL: "http://localhost:5173", - T3CODE_NO_BROWSER: "true", - T3CODE_AUTH_TOKEN: "env-token", - }); - - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.mode, "desktop"); - assert.equal(resolvedConfig?.port, 4999); - assert.equal(resolvedConfig?.host, "100.88.10.4"); - assert.equal(resolvedConfig?.baseDir, "/tmp/t3-env-home"); - assert.equal(resolvedConfig?.stateDir, "/tmp/t3-env-home/dev"); - assert.equal(resolvedConfig?.devUrl?.toString(), "http://localhost:5173/"); - assert.equal(resolvedConfig?.noBrowser, true); - assert.equal(resolvedConfig?.authToken, "env-token"); - assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, false); - assert.equal(resolvedConfig?.logWebSocketEvents, true); - assert.equal(findAvailablePort.mock.calls.length, 0); - }), - ); - - const openBootstrapFd = Effect.fn(function* (payload: Record) { - const fs = yield* FileSystem.FileSystem; - const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" }); - yield* fs.writeFileString(filePath, `${JSON.stringify(payload)}\n`); - const { fd } = yield* fs.open(filePath, { flag: "r" }); - return fd; - }); - - it.effect("recognizes bootstrap fd from environment config", () => - Effect.gen(function* () { - const fd = yield* openBootstrapFd({ authToken: "bootstrap-token" }); - - yield* runCli([], { - T3CODE_MODE: "web", - T3CODE_BOOTSTRAP_FD: String(fd), - T3CODE_AUTH_TOKEN: "env-token", - T3CODE_NO_BROWSER: "true", - }); - - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.mode, "web"); - assert.equal(resolvedConfig?.authToken, "env-token"); - }), - ); - - it.effect("uses bootstrap envelope values as fallbacks when CLI and env are absent", () => - Effect.gen(function* () { - const fd = yield* openBootstrapFd({ - mode: "desktop", - port: 4888, - host: "127.0.0.2", - t3Home: "/tmp/t3-bootstrap-home", - devUrl: "http://127.0.0.1:5173", - noBrowser: true, - authToken: "bootstrap-token", - autoBootstrapProjectFromCwd: false, - logWebSocketEvents: true, - }); - - yield* runCli([], { - T3CODE_BOOTSTRAP_FD: String(fd), - }); - - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.mode, "desktop"); - assert.equal(resolvedConfig?.port, 4888); - assert.equal(resolvedConfig?.host, "127.0.0.2"); - assert.equal(resolvedConfig?.baseDir, "/tmp/t3-bootstrap-home"); - assert.equal(resolvedConfig?.stateDir, "/tmp/t3-bootstrap-home/dev"); - assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/"); - assert.equal(resolvedConfig?.noBrowser, true); - assert.equal(resolvedConfig?.authToken, "bootstrap-token"); - assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, false); - assert.equal(resolvedConfig?.logWebSocketEvents, true); - }), - ); - - it.effect("applies CLI then env precedence over bootstrap envelope values", () => - Effect.gen(function* () { - const fd = yield* openBootstrapFd({ - mode: "desktop", - port: 4888, - host: "127.0.0.2", - t3Home: "/tmp/t3-bootstrap-home", - devUrl: "http://127.0.0.1:5173", - noBrowser: false, - authToken: "bootstrap-token", - autoBootstrapProjectFromCwd: false, - logWebSocketEvents: false, - }); - - yield* runCli(["--port", "4999", "--host", "0.0.0.0", "--auth-token", "cli-token"], { - T3CODE_MODE: "web", - T3CODE_BOOTSTRAP_FD: String(fd), - T3CODE_HOME: "/tmp/t3-env-home", - T3CODE_NO_BROWSER: "true", - T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true", - T3CODE_LOG_WS_EVENTS: "true", - }); - - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.mode, "web"); - assert.equal(resolvedConfig?.port, 4999); - assert.equal(resolvedConfig?.host, "0.0.0.0"); - assert.equal(resolvedConfig?.baseDir, "/tmp/t3-env-home"); - assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/"); - assert.equal(resolvedConfig?.noBrowser, true); - assert.equal(resolvedConfig?.authToken, "cli-token"); - assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, true); - assert.equal(resolvedConfig?.logWebSocketEvents, true); - }), - ); - - it.effect("prefers --mode over T3CODE_MODE", () => - Effect.gen(function* () { - findAvailablePort.mockImplementation((_preferred: number) => Effect.succeed(4666)); - yield* runCli(["--mode", "web"], { - T3CODE_MODE: "desktop", - T3CODE_NO_BROWSER: "true", - }); - - assert.deepStrictEqual(findAvailablePort.mock.calls, [[3773]]); - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.mode, "web"); - assert.equal(resolvedConfig?.port, 4666); - assert.equal(resolvedConfig?.host, undefined); - }), - ); - - it.effect("prefers --no-browser over T3CODE_NO_BROWSER", () => - Effect.gen(function* () { - yield* runCli(["--no-browser"], { - T3CODE_NO_BROWSER: "false", - }); - - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.noBrowser, true); - }), - ); - - it.effect("uses dynamic port discovery in web mode when port is omitted", () => - Effect.gen(function* () { - findAvailablePort.mockImplementation((_preferred: number) => Effect.succeed(5444)); - yield* runCli([]); - - assert.deepStrictEqual(findAvailablePort.mock.calls, [[3773]]); - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.port, 5444); - assert.equal(resolvedConfig?.mode, "web"); - }), - ); - - it.effect("uses fixed localhost defaults in desktop mode", () => - Effect.gen(function* () { - yield* runCli([], { - T3CODE_MODE: "desktop", - T3CODE_NO_BROWSER: "true", - }); - - assert.equal(findAvailablePort.mock.calls.length, 0); - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.port, 3773); - assert.equal(resolvedConfig?.host, "127.0.0.1"); - assert.equal(resolvedConfig?.mode, "desktop"); - }), - ); - - it.effect("allows overriding desktop host with --host", () => - Effect.gen(function* () { - yield* runCli(["--host", "0.0.0.0"], { - T3CODE_MODE: "desktop", - T3CODE_NO_BROWSER: "true", - }); - - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.mode, "desktop"); - assert.equal(resolvedConfig?.host, "0.0.0.0"); - }), - ); - - it.effect("supports CLI and env for bootstrap/log websocket toggles", () => - Effect.gen(function* () { - yield* runCli(["--auto-bootstrap-project-from-cwd"], { - T3CODE_MODE: "desktop", - T3CODE_LOG_WS_EVENTS: "false", - T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false", - T3CODE_NO_BROWSER: "true", - }); - - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, true); - assert.equal(resolvedConfig?.logWebSocketEvents, false); - }), - ); - - it.effect("hydrates PATH before server startup", () => - Effect.gen(function* () { - yield* runCli([]); - - assert.equal(fixPath.mock.calls.length, 1); - assert.equal(start.mock.calls.length, 1); - const fixPathOrder = fixPath.mock.invocationCallOrder[0]; - const startOrder = start.mock.invocationCallOrder[0]; - if (typeof fixPathOrder !== "number" || typeof startOrder !== "number") { - assert.fail("Expected fixPath and start to be called"); - } - assert.isTrue(fixPathOrder < startOrder); - }), - ); - - it.effect("records a startup heartbeat with thread/project counts", () => - Effect.gen(function* () { - const recordTelemetry = vi.fn( - (_event: string, _properties?: Readonly>) => Effect.void, - ); - const getSnapshot = vi.fn(() => - Effect.succeed({ - snapshotSequence: 2, - projects: [{} as OrchestrationReadModel["projects"][number]], - threads: [ - {} as OrchestrationReadModel["threads"][number], - {} as OrchestrationReadModel["threads"][number], - ], - updatedAt: new Date(1).toISOString(), - } satisfies OrchestrationReadModel), - ); - - yield* recordStartupHeartbeat.pipe( - Effect.provideService(ProjectionSnapshotQuery, { - getSnapshot, - }), - Effect.provideService(AnalyticsService, { - record: recordTelemetry, - flush: Effect.void, - }), - ); - - assert.deepEqual(recordTelemetry.mock.calls[0], [ - "server.boot.heartbeat", - { - threadCount: 2, - projectCount: 1, - }, - ]); - }), - ); - - it.effect("does not start server for invalid --mode values", () => - Effect.gen(function* () { - yield* runCli(["--mode", "invalid"]).pipe(Effect.catch(() => Effect.void)); - - assert.equal(start.mock.calls.length, 0); - assert.equal(stop.mock.calls.length, 0); - }), - ); - - it.effect("does not start server for invalid --dev-url values", () => - Effect.gen(function* () { - yield* runCli(["--dev-url", "not-a-url"]).pipe(Effect.catch(() => Effect.void)); - - assert.equal(start.mock.calls.length, 0); - assert.equal(stop.mock.calls.length, 0); - }), - ); - - it.effect("does not start server for out-of-range --port values", () => - Effect.gen(function* () { - yield* runCli(["--port", "70000"]).pipe(Effect.catch(() => Effect.void)); - - // effect/unstable/cli renders help/errors for parse failures and returns success. - assert.equal(start.mock.calls.length, 0); - assert.equal(stop.mock.calls.length, 0); - }), - ); -}); diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts deleted file mode 100644 index 8e7b4c8cb7..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 { DesktopLauncher } from "./process/Services/DesktopLauncher"; -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 desktopLauncher = yield* DesktopLauncher; - - 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* desktopLauncher.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/observability/Attributes.test.ts b/apps/server/src/observability/Attributes.test.ts new file mode 100644 index 0000000000..4b495598ea --- /dev/null +++ b/apps/server/src/observability/Attributes.test.ts @@ -0,0 +1,46 @@ +import { assert, describe, it } from "@effect/vitest"; + +import { compactTraceAttributes, normalizeModelMetricLabel } from "./Attributes.ts"; + +describe("Attributes", () => { + it("normalizes circular arrays, maps, and sets without recursing forever", () => { + const array: Array = ["alpha"]; + array.push(array); + + const map = new Map(); + map.set("self", map); + + const set = new Set(); + set.add(set); + + assert.deepStrictEqual( + compactTraceAttributes({ + array, + map, + set, + }), + { + array: ["alpha", "[Circular]"], + map: { self: "[Circular]" }, + set: ["[Circular]"], + }, + ); + }); + + it("normalizes invalid dates without throwing", () => { + assert.deepStrictEqual( + compactTraceAttributes({ + invalidDate: new Date("not-a-real-date"), + }), + { + invalidDate: "Invalid Date", + }, + ); + }); + + it("groups GPT-family models under a shared metric label", () => { + assert.strictEqual(normalizeModelMetricLabel("gpt-4o"), "gpt"); + assert.strictEqual(normalizeModelMetricLabel("gpt-5.4"), "gpt"); + assert.strictEqual(normalizeModelMetricLabel("claude-sonnet-4"), "claude"); + }); +}); diff --git a/apps/server/src/observability/Attributes.ts b/apps/server/src/observability/Attributes.ts new file mode 100644 index 0000000000..2251fcfea6 --- /dev/null +++ b/apps/server/src/observability/Attributes.ts @@ -0,0 +1,128 @@ +import { Cause, Exit } from "effect"; + +export type MetricAttributeValue = string; +export type MetricAttributes = Readonly>; +export type TraceAttributes = Readonly>; +export type ObservabilityOutcome = "success" | "failure" | "interrupt"; + +function isPlainObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function markSeen(value: object, seen: WeakSet): boolean { + if (seen.has(value)) { + return true; + } + seen.add(value); + return false; +} + +function normalizeJsonValue(value: unknown, seen: WeakSet = new WeakSet()): unknown { + if ( + value === null || + value === undefined || + typeof value === "string" || + typeof value === "number" || + typeof value === "boolean" + ) { + return value ?? null; + } + if (typeof value === "bigint") { + return value.toString(); + } + if (value instanceof Date) { + return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString(); + } + if (value instanceof Error) { + return { + name: value.name, + message: value.message, + ...(value.stack ? { stack: value.stack } : {}), + }; + } + if (Array.isArray(value)) { + if (markSeen(value, seen)) { + return "[Circular]"; + } + return value.map((entry) => normalizeJsonValue(entry, seen)); + } + if (value instanceof Map) { + if (markSeen(value, seen)) { + return "[Circular]"; + } + return Object.fromEntries( + Array.from(value.entries(), ([key, entryValue]) => [ + String(key), + normalizeJsonValue(entryValue, seen), + ]), + ); + } + if (value instanceof Set) { + if (markSeen(value, seen)) { + return "[Circular]"; + } + return Array.from(value.values(), (entry) => normalizeJsonValue(entry, seen)); + } + if (!isPlainObject(value)) { + return String(value); + } + if (markSeen(value, seen)) { + return "[Circular]"; + } + return Object.fromEntries( + Object.entries(value).map(([key, entryValue]) => [key, normalizeJsonValue(entryValue, seen)]), + ); +} + +export function compactTraceAttributes( + attributes: Readonly>, +): TraceAttributes { + return Object.fromEntries( + Object.entries(attributes) + .filter(([, value]) => value !== undefined) + .map(([key, value]) => [key, normalizeJsonValue(value)]), + ); +} + +export function compactMetricAttributes( + attributes: Readonly>, +): MetricAttributes { + return Object.fromEntries( + Object.entries(attributes).flatMap(([key, value]) => { + if (value === undefined || value === null) { + return []; + } + if (typeof value === "string") { + return [[key, value]]; + } + if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") { + return [[key, String(value)]]; + } + return []; + }), + ); +} + +export function outcomeFromExit(exit: Exit.Exit): ObservabilityOutcome { + if (Exit.isSuccess(exit)) { + return "success"; + } + return Cause.hasInterruptsOnly(exit.cause) ? "interrupt" : "failure"; +} + +export function normalizeModelMetricLabel(model: string | null | undefined): string | undefined { + const normalized = model?.trim().toLowerCase(); + if (!normalized) { + return undefined; + } + if (normalized.includes("gpt")) { + return "gpt"; + } + if (normalized.includes("claude")) { + return "claude"; + } + if (normalized.includes("gemini")) { + return "gemini"; + } + return "other"; +} diff --git a/apps/server/src/observability/Layers/Observability.ts b/apps/server/src/observability/Layers/Observability.ts new file mode 100644 index 0000000000..7c6a28005f --- /dev/null +++ b/apps/server/src/observability/Layers/Observability.ts @@ -0,0 +1,84 @@ +import { Effect, Layer, References, Tracer } from "effect"; +import { OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/unstable/observability"; + +import { ServerConfig } from "../../config.ts"; +import { ServerLoggerLive } from "../../serverLogger.ts"; +import { makeLocalFileTracer } from "../LocalFileTracer.ts"; +import { BrowserTraceCollector } from "../Services/BrowserTraceCollector.ts"; +import { makeTraceSink } from "../TraceSink.ts"; + +const otlpSerializationLayer = OtlpSerialization.layerJson; + +export const ObservabilityLive = Layer.unwrap( + Effect.gen(function* () { + const config = yield* ServerConfig; + + const traceReferencesLayer = Layer.mergeAll( + Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel), + Layer.succeed(References.TracerTimingEnabled, config.traceTimingEnabled), + ); + + const tracerLayer = Layer.unwrap( + Effect.gen(function* () { + const sink = yield* makeTraceSink({ + filePath: config.serverTracePath, + maxBytes: config.traceMaxBytes, + maxFiles: config.traceMaxFiles, + batchWindowMs: config.traceBatchWindowMs, + }); + const delegate = + config.otlpTracesUrl === undefined + ? undefined + : yield* OtlpTracer.make({ + url: config.otlpTracesUrl, + exportInterval: `${config.otlpExportIntervalMs} millis`, + resource: { + serviceName: config.otlpServiceName, + attributes: { + "service.runtime": "t3-server", + "service.mode": config.mode, + }, + }, + }); + + const tracer = yield* makeLocalFileTracer({ + filePath: config.serverTracePath, + maxBytes: config.traceMaxBytes, + maxFiles: config.traceMaxFiles, + batchWindowMs: config.traceBatchWindowMs, + sink, + ...(delegate ? { delegate } : {}), + }); + + return Layer.mergeAll( + Layer.succeed(Tracer.Tracer, tracer), + Layer.succeed(BrowserTraceCollector, { + record: (records) => + Effect.sync(() => { + for (const record of records) { + sink.push(record); + } + }), + }), + ); + }), + ).pipe(Layer.provideMerge(otlpSerializationLayer)); + + const metricsLayer = + config.otlpMetricsUrl === undefined + ? Layer.empty + : OtlpMetrics.layer({ + url: config.otlpMetricsUrl, + exportInterval: `${config.otlpExportIntervalMs} millis`, + resource: { + serviceName: config.otlpServiceName, + attributes: { + "service.runtime": "t3-server", + "service.mode": config.mode, + }, + }, + }).pipe(Layer.provideMerge(otlpSerializationLayer)); + + return Layer.mergeAll(ServerLoggerLive, traceReferencesLayer, tracerLayer, metricsLayer); + }), +); diff --git a/apps/server/src/observability/LocalFileTracer.test.ts b/apps/server/src/observability/LocalFileTracer.test.ts new file mode 100644 index 0000000000..19efffaf10 --- /dev/null +++ b/apps/server/src/observability/LocalFileTracer.test.ts @@ -0,0 +1,117 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { assert, describe, it } from "@effect/vitest"; +import { Effect, Layer, Logger, References, Tracer } from "effect"; + +import type { EffectTraceRecord } from "./TraceRecord.ts"; +import { makeLocalFileTracer } from "./LocalFileTracer.ts"; + +const makeTestLayer = (tracePath: string) => + Layer.mergeAll( + Layer.effect( + Tracer.Tracer, + makeLocalFileTracer({ + filePath: tracePath, + maxBytes: 1024 * 1024, + maxFiles: 2, + batchWindowMs: 10_000, + }), + ), + Logger.layer([Logger.tracerLogger], { mergeWithExisting: false }), + Layer.succeed(References.MinimumLogLevel, "Info"), + ); + +const readTraceRecords = (tracePath: string): Array => + fs + .readFileSync(tracePath, "utf8") + .trim() + .split("\n") + .filter((line) => line.length > 0) + .map((line) => JSON.parse(line) as EffectTraceRecord); + +describe("LocalFileTracer", () => { + it.effect("writes nested spans to disk and captures log messages as span events", () => + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-local-tracer-")); + const tracePath = path.join(tempDir, "server.trace.ndjson"); + + try { + yield* Effect.scoped( + Effect.gen(function* () { + const program = Effect.gen(function* () { + yield* Effect.annotateCurrentSpan({ + "demo.parent": true, + }); + yield* Effect.logInfo("parent event"); + yield* Effect.gen(function* () { + yield* Effect.annotateCurrentSpan({ + "demo.child": true, + }); + yield* Effect.logInfo("child event"); + }).pipe(Effect.withSpan("child-span")); + }).pipe(Effect.withSpan("parent-span")); + + yield* program.pipe(Effect.provide(makeTestLayer(tracePath))); + }), + ); + + const records = readTraceRecords(tracePath); + assert.equal(records.length, 2); + + const parent = records.find((record) => record.name === "parent-span"); + const child = records.find((record) => record.name === "child-span"); + + assert.notEqual(parent, undefined); + assert.notEqual(child, undefined); + if (!parent || !child) { + return; + } + + assert.equal(child.parentSpanId, parent.spanId); + assert.equal(parent.attributes["demo.parent"], true); + assert.equal(child.attributes["demo.child"], true); + assert.equal( + parent.events.some((event) => event.name === "parent event"), + true, + ); + assert.equal( + child.events.some((event) => event.name === "child event"), + true, + ); + assert.equal( + child.events.some((event) => event.attributes["effect.logLevel"] === "INFO"), + true, + ); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ); + + it.effect("serializes interrupted spans with an interrupted exit status", () => + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-local-tracer-")); + const tracePath = path.join(tempDir, "server.trace.ndjson"); + + try { + yield* Effect.scoped( + Effect.exit( + Effect.interrupt.pipe( + Effect.withSpan("interrupt-span"), + Effect.provide(makeTestLayer(tracePath)), + ), + ), + ); + + const records = readTraceRecords(tracePath); + assert.equal(records.length, 1); + assert.equal(records[0]?.name, "interrupt-span"); + assert.equal(records[0]?.exit._tag, "Interrupted"); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ); +}); diff --git a/apps/server/src/observability/LocalFileTracer.ts b/apps/server/src/observability/LocalFileTracer.ts new file mode 100644 index 0000000000..cde5a176e8 --- /dev/null +++ b/apps/server/src/observability/LocalFileTracer.ts @@ -0,0 +1,107 @@ +import type * as Exit from "effect/Exit"; +import { Effect, Option, Tracer } from "effect"; + +import { EffectTraceRecord, spanToTraceRecord } from "./TraceRecord.ts"; +import { makeTraceSink, type TraceSink } from "./TraceSink.ts"; + +export interface LocalFileTracerOptions { + readonly filePath: string; + readonly maxBytes: number; + readonly maxFiles: number; + readonly batchWindowMs: number; + readonly delegate?: Tracer.Tracer; + readonly sink?: TraceSink; +} + +class LocalFileSpan implements Tracer.Span { + readonly _tag = "Span"; + readonly name: string; + readonly spanId: string; + readonly traceId: string; + readonly parent: Option.Option; + readonly annotations: Tracer.Span["annotations"]; + readonly links: Array; + readonly sampled: boolean; + readonly kind: Tracer.SpanKind; + + status: Tracer.SpanStatus; + attributes: Map; + events: Array<[name: string, startTime: bigint, attributes: Record]>; + + constructor( + options: Parameters[0], + private readonly delegate: Tracer.Span, + private readonly push: (record: EffectTraceRecord) => void, + ) { + this.name = delegate.name; + this.spanId = delegate.spanId; + this.traceId = delegate.traceId; + this.parent = options.parent; + this.annotations = options.annotations; + this.links = [...options.links]; + this.sampled = delegate.sampled; + this.kind = delegate.kind; + this.status = { + _tag: "Started", + startTime: options.startTime, + }; + this.attributes = new Map(); + this.events = []; + } + + end(endTime: bigint, exit: Exit.Exit): void { + this.status = { + _tag: "Ended", + startTime: this.status.startTime, + endTime, + exit, + }; + this.delegate.end(endTime, exit); + + if (this.sampled) { + this.push(spanToTraceRecord(this)); + } + } + + attribute(key: string, value: unknown): void { + this.attributes.set(key, value); + this.delegate.attribute(key, value); + } + + event(name: string, startTime: bigint, attributes?: Record): void { + const nextAttributes = attributes ?? {}; + this.events.push([name, startTime, nextAttributes]); + this.delegate.event(name, startTime, nextAttributes); + } + + addLinks(links: ReadonlyArray): void { + this.links.push(...links); + this.delegate.addLinks(links); + } +} + +export const makeLocalFileTracer = Effect.fn("makeLocalFileTracer")(function* ( + options: LocalFileTracerOptions, +) { + const sink = + options.sink ?? + (yield* makeTraceSink({ + filePath: options.filePath, + maxBytes: options.maxBytes, + maxFiles: options.maxFiles, + batchWindowMs: options.batchWindowMs, + })); + + const delegate = + options.delegate ?? + Tracer.make({ + span: (spanOptions) => new Tracer.NativeSpan(spanOptions), + }); + + return Tracer.make({ + span(spanOptions) { + return new LocalFileSpan(spanOptions, delegate.span(spanOptions), sink.push); + }, + ...(delegate.context ? { context: delegate.context } : {}), + }); +}); diff --git a/apps/server/src/observability/Metrics.test.ts b/apps/server/src/observability/Metrics.test.ts new file mode 100644 index 0000000000..4604f43b63 --- /dev/null +++ b/apps/server/src/observability/Metrics.test.ts @@ -0,0 +1,111 @@ +import { assert, describe, it } from "@effect/vitest"; +import { Effect, Metric } from "effect"; + +import { withMetrics } from "./Metrics.ts"; + +const hasMetricSnapshot = ( + snapshots: ReadonlyArray, + id: string, + attributes: Readonly>, +) => + snapshots.some( + (snapshot) => + snapshot.id === id && + Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value), + ); + +describe("withMetrics", () => { + it.effect("supports pipe-style usage", () => + Effect.gen(function* () { + const counter = Metric.counter("with_metrics_pipe_total"); + const timer = Metric.timer("with_metrics_pipe_duration"); + + const result = yield* Effect.succeed("ok").pipe( + withMetrics({ + counter, + timer, + attributes: { + operation: "pipe", + }, + }), + ); + + assert.equal(result, "ok"); + + const snapshots = yield* Metric.snapshot; + assert.equal( + hasMetricSnapshot(snapshots, "with_metrics_pipe_total", { + operation: "pipe", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "with_metrics_pipe_duration", { + operation: "pipe", + }), + true, + ); + }), + ); + + it.effect("supports direct invocation", () => + Effect.gen(function* () { + const counter = Metric.counter("with_metrics_direct_total"); + + yield* withMetrics(Effect.fail("boom"), { + counter, + attributes: { + operation: "direct", + }, + }).pipe(Effect.exit); + + const snapshots = yield* Metric.snapshot; + assert.equal( + hasMetricSnapshot(snapshots, "with_metrics_direct_total", { + operation: "direct", + outcome: "failure", + }), + true, + ); + }), + ); + + it.effect("evaluates attributes lazily after the wrapped effect runs", () => + Effect.gen(function* () { + const counter = Metric.counter("with_metrics_lazy_total"); + const timer = Metric.timer("with_metrics_lazy_duration"); + let provider = "unknown"; + + yield* Effect.sync(() => { + provider = "codex"; + }).pipe( + withMetrics({ + counter, + timer, + attributes: () => ({ + provider, + operation: "lazy", + }), + }), + ); + + const snapshots = yield* Metric.snapshot; + assert.equal( + hasMetricSnapshot(snapshots, "with_metrics_lazy_total", { + provider: "codex", + operation: "lazy", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "with_metrics_lazy_duration", { + provider: "codex", + operation: "lazy", + }), + true, + ); + }), + ); +}); diff --git a/apps/server/src/observability/Metrics.ts b/apps/server/src/observability/Metrics.ts new file mode 100644 index 0000000000..3e527c7cb4 --- /dev/null +++ b/apps/server/src/observability/Metrics.ts @@ -0,0 +1,160 @@ +import { Duration, Effect, Exit, Metric } from "effect"; +import { dual } from "effect/Function"; + +import { + compactMetricAttributes, + normalizeModelMetricLabel, + outcomeFromExit, +} from "./Attributes.ts"; + +export const rpcRequestsTotal = Metric.counter("t3_rpc_requests_total", { + description: "Total RPC requests handled by the websocket RPC server.", +}); + +export const rpcRequestDuration = Metric.timer("t3_rpc_request_duration", { + description: "RPC request handling duration.", +}); + +export const orchestrationCommandsTotal = Metric.counter("t3_orchestration_commands_total", { + description: "Total orchestration commands dispatched.", +}); + +export const orchestrationCommandDuration = Metric.timer("t3_orchestration_command_duration", { + description: "Orchestration command dispatch duration.", +}); + +export const orchestrationCommandAckDuration = Metric.timer( + "t3_orchestration_command_ack_duration", + { + description: + "Time from orchestration command dispatch to the first committed domain event emitted for that command.", + }, +); + +export const orchestrationEventsProcessedTotal = Metric.counter( + "t3_orchestration_events_processed_total", + { + description: "Total orchestration intent events processed by runtime reactors.", + }, +); + +export const providerSessionsTotal = Metric.counter("t3_provider_sessions_total", { + description: "Total provider session lifecycle operations.", +}); + +export const providerTurnsTotal = Metric.counter("t3_provider_turns_total", { + description: "Total provider turn lifecycle operations.", +}); + +export const providerTurnDuration = Metric.timer("t3_provider_turn_duration", { + description: "Provider turn request duration.", +}); + +export const providerRuntimeEventsTotal = Metric.counter("t3_provider_runtime_events_total", { + description: "Total canonical provider runtime events processed.", +}); + +export const gitCommandsTotal = Metric.counter("t3_git_commands_total", { + description: "Total git commands executed by the server runtime.", +}); + +export const gitCommandDuration = Metric.timer("t3_git_command_duration", { + description: "Git command execution duration.", +}); + +export const terminalSessionsTotal = Metric.counter("t3_terminal_sessions_total", { + description: "Total terminal sessions started.", +}); + +export const terminalRestartsTotal = Metric.counter("t3_terminal_restarts_total", { + description: "Total terminal restart requests handled.", +}); + +export const metricAttributes = ( + attributes: Readonly>, +): ReadonlyArray<[string, string]> => Object.entries(compactMetricAttributes(attributes)); + +export const increment = ( + metric: Metric.Metric, + attributes: Readonly>, + amount = 1, +) => Metric.update(Metric.withAttributes(metric, metricAttributes(attributes)), amount); + +export interface WithMetricsOptions { + readonly counter?: Metric.Metric; + readonly timer?: Metric.Metric; + readonly attributes?: + | Readonly> + | (() => Readonly>); + readonly outcomeAttributes?: ( + outcome: ReturnType, + ) => Readonly>; +} + +const withMetricsImpl = ( + effect: Effect.Effect, + options: WithMetricsOptions, +): Effect.Effect => + Effect.gen(function* () { + const startedAt = Date.now(); + const exit = yield* Effect.exit(effect); + const duration = Duration.millis(Math.max(0, Date.now() - startedAt)); + const baseAttributes = + typeof options.attributes === "function" ? options.attributes() : (options.attributes ?? {}); + + if (options.timer) { + yield* Metric.update( + Metric.withAttributes(options.timer, metricAttributes(baseAttributes)), + duration, + ); + } + + if (options.counter) { + const outcome = outcomeFromExit(exit); + yield* Metric.update( + Metric.withAttributes( + options.counter, + metricAttributes({ + ...baseAttributes, + outcome, + ...(options.outcomeAttributes ? options.outcomeAttributes(outcome) : {}), + }), + ), + 1, + ); + } + + if (Exit.isSuccess(exit)) { + return exit.value; + } + return yield* Effect.failCause(exit.cause); + }); + +export const withMetrics: { + ( + options: WithMetricsOptions, + ): (effect: Effect.Effect) => Effect.Effect; + (effect: Effect.Effect, options: WithMetricsOptions): Effect.Effect; +} = dual(2, withMetricsImpl); + +export const providerMetricAttributes = ( + provider: string, + extra?: Readonly>, +) => + compactMetricAttributes({ + provider, + ...extra, + }); + +export const providerTurnMetricAttributes = (input: { + readonly provider: string; + readonly model: string | null | undefined; + readonly extra?: Readonly>; +}) => { + const modelFamily = normalizeModelMetricLabel(input.model); + return compactMetricAttributes({ + provider: input.provider, + ...(modelFamily ? { modelFamily } : {}), + ...input.extra, + }); +}; diff --git a/apps/server/src/observability/RpcInstrumentation.test.ts b/apps/server/src/observability/RpcInstrumentation.test.ts new file mode 100644 index 0000000000..d29b05f3c2 --- /dev/null +++ b/apps/server/src/observability/RpcInstrumentation.test.ts @@ -0,0 +1,161 @@ +import { assert, describe, it } from "@effect/vitest"; +import { Effect, Exit, Metric, Stream } from "effect"; + +import { + observeRpcEffect, + observeRpcStream, + observeRpcStreamEffect, +} from "./RpcInstrumentation.ts"; + +const hasMetricSnapshot = ( + snapshots: ReadonlyArray, + id: string, + attributes: Readonly>, +) => + snapshots.some( + (snapshot) => + snapshot.id === id && + Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value), + ); + +describe("RpcInstrumentation", () => { + it.effect("records success metrics for unary RPC handlers", () => + Effect.gen(function* () { + yield* observeRpcEffect("rpc.instrumentation.success", Effect.succeed("ok"), { + "rpc.aggregate": "test", + }).pipe(Effect.withSpan("rpc.instrumentation.success.span")); + + const snapshots = yield* Metric.snapshot; + + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_requests_total", { + method: "rpc.instrumentation.success", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_request_duration", { + method: "rpc.instrumentation.success", + }), + true, + ); + }), + ); + + it.effect("records failure outcomes for unary RPC handlers", () => + Effect.gen(function* () { + yield* Effect.exit( + observeRpcEffect("rpc.instrumentation.failure", Effect.fail("boom"), { + "rpc.aggregate": "test", + }).pipe(Effect.withSpan("rpc.instrumentation.failure.span")), + ); + + const snapshots = yield* Metric.snapshot; + + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_requests_total", { + method: "rpc.instrumentation.failure", + outcome: "failure", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_request_duration", { + method: "rpc.instrumentation.failure", + }), + true, + ); + }), + ); + + it.effect("records subscription activation metrics for stream RPC handlers", () => + Effect.gen(function* () { + const events = yield* Stream.runCollect( + observeRpcStreamEffect( + "rpc.instrumentation.stream", + Effect.succeed(Stream.make("a", "b")), + { "rpc.aggregate": "test" }, + ).pipe(Stream.withSpan("rpc.instrumentation.stream.span")), + ); + + assert.deepStrictEqual(Array.from(events), ["a", "b"]); + + const snapshots = yield* Metric.snapshot; + + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_requests_total", { + method: "rpc.instrumentation.stream", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_request_duration", { + method: "rpc.instrumentation.stream", + }), + true, + ); + }), + ); + + it.effect("records failure outcomes for direct stream RPC handlers during consumption", () => + Effect.gen(function* () { + const exit = yield* Stream.runCollect( + observeRpcStream( + "rpc.instrumentation.stream.failure", + Stream.make("a").pipe(Stream.concat(Stream.fail("boom"))), + { "rpc.aggregate": "test" }, + ).pipe(Stream.withSpan("rpc.instrumentation.stream.failure.span")), + ).pipe(Effect.exit); + + assert.equal(Exit.isFailure(exit), true); + + const snapshots = yield* Metric.snapshot; + + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_requests_total", { + method: "rpc.instrumentation.stream.failure", + outcome: "failure", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_request_duration", { + method: "rpc.instrumentation.stream.failure", + }), + true, + ); + }), + ); + + it.effect("records failure outcomes when a stream RPC effect produces a failing stream", () => + Effect.gen(function* () { + const exit = yield* Stream.runCollect( + observeRpcStreamEffect( + "rpc.instrumentation.stream.effect.failure", + Effect.succeed(Stream.fail("boom")), + { "rpc.aggregate": "test" }, + ).pipe(Stream.withSpan("rpc.instrumentation.stream.effect.failure.span")), + ).pipe(Effect.exit); + + assert.equal(Exit.isFailure(exit), true); + + const snapshots = yield* Metric.snapshot; + + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_requests_total", { + method: "rpc.instrumentation.stream.effect.failure", + outcome: "failure", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_request_duration", { + method: "rpc.instrumentation.stream.effect.failure", + }), + true, + ); + }), + ); +}); diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts new file mode 100644 index 0000000000..a3ac29aa02 --- /dev/null +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -0,0 +1,89 @@ +import { Duration, Effect, Exit, Metric, Stream } from "effect"; + +import { outcomeFromExit } from "./Attributes.ts"; +import { metricAttributes, rpcRequestDuration, rpcRequestsTotal, withMetrics } from "./Metrics.ts"; + +const annotateRpcSpan = ( + method: string, + traceAttributes?: Readonly>, +): Effect.Effect => + Effect.annotateCurrentSpan({ + "rpc.method": method, + ...traceAttributes, + }); + +const recordRpcStreamMetrics = ( + method: string, + startedAt: number, + exit: Exit.Exit, +): Effect.Effect => + Effect.gen(function* () { + yield* Metric.update( + Metric.withAttributes(rpcRequestDuration, metricAttributes({ method })), + Duration.millis(Math.max(0, Date.now() - startedAt)), + ); + yield* Metric.update( + Metric.withAttributes( + rpcRequestsTotal, + metricAttributes({ + method, + outcome: outcomeFromExit(exit), + }), + ), + 1, + ); + }); + +export const observeRpcEffect = ( + method: string, + effect: Effect.Effect, + traceAttributes?: Readonly>, +): Effect.Effect => + Effect.gen(function* () { + yield* annotateRpcSpan(method, traceAttributes); + + return yield* effect.pipe( + withMetrics({ + counter: rpcRequestsTotal, + timer: rpcRequestDuration, + attributes: { + method, + }, + }), + ); + }); + +export const observeRpcStream = ( + method: string, + stream: Stream.Stream, + traceAttributes?: Readonly>, +): Stream.Stream => + Stream.unwrap( + Effect.gen(function* () { + yield* annotateRpcSpan(method, traceAttributes); + const startedAt = Date.now(); + return stream.pipe(Stream.onExit((exit) => recordRpcStreamMetrics(method, startedAt, exit))); + }), + ); + +export const observeRpcStreamEffect = ( + method: string, + effect: Effect.Effect, EffectError, EffectContext>, + traceAttributes?: Readonly>, +): Stream.Stream => + Stream.unwrap( + Effect.gen(function* () { + yield* annotateRpcSpan(method, traceAttributes); + const startedAt = Date.now(); + const exit = yield* Effect.exit(effect); + + if (Exit.isFailure(exit)) { + yield* recordRpcStreamMetrics(method, startedAt, exit); + return yield* Effect.failCause(exit.cause); + } + + return exit.value.pipe( + Stream.onExit((streamExit) => recordRpcStreamMetrics(method, startedAt, streamExit)), + ); + }), + ); diff --git a/apps/server/src/observability/Services/BrowserTraceCollector.ts b/apps/server/src/observability/Services/BrowserTraceCollector.ts new file mode 100644 index 0000000000..e27a53c9c3 --- /dev/null +++ b/apps/server/src/observability/Services/BrowserTraceCollector.ts @@ -0,0 +1,13 @@ +import { Context } from "effect"; +import type { Effect } from "effect"; + +import type { TraceRecord } from "../TraceRecord.ts"; + +export interface BrowserTraceCollectorShape { + readonly record: (records: ReadonlyArray) => Effect.Effect; +} + +export class BrowserTraceCollector extends Context.Service< + BrowserTraceCollector, + BrowserTraceCollectorShape +>()("t3/observability/Services/BrowserTraceCollector") {} diff --git a/apps/server/src/observability/TraceRecord.ts b/apps/server/src/observability/TraceRecord.ts new file mode 100644 index 0000000000..a9a598288b --- /dev/null +++ b/apps/server/src/observability/TraceRecord.ts @@ -0,0 +1,287 @@ +import { Cause, Exit, Option, Tracer } from "effect"; + +import { compactTraceAttributes } from "./Attributes.ts"; +import { OtlpResource, OtlpTracer } from "effect/unstable/observability"; + +interface TraceRecordEvent { + readonly name: string; + readonly timeUnixNano: string; + readonly attributes: Readonly>; +} + +interface TraceRecordLink { + readonly traceId: string; + readonly spanId: string; + readonly attributes: Readonly>; +} + +interface BaseTraceRecord { + readonly name: string; + readonly kind: string; + readonly traceId: string; + readonly spanId: string; + readonly parentSpanId?: string; + readonly sampled: boolean; + readonly startTimeUnixNano: string; + readonly endTimeUnixNano: string; + readonly durationMs: number; + readonly attributes: Readonly>; + readonly events: ReadonlyArray; + readonly links: ReadonlyArray; +} + +export interface EffectTraceRecord extends BaseTraceRecord { + readonly type: "effect-span"; + readonly exit: + | { + readonly _tag: "Success"; + } + | { + readonly _tag: "Interrupted"; + readonly cause: string; + } + | { + readonly _tag: "Failure"; + readonly cause: string; + }; +} + +interface OtlpTraceRecord extends BaseTraceRecord { + readonly type: "otlp-span"; + readonly resourceAttributes: Readonly>; + readonly scope: Readonly<{ + readonly name?: string; + readonly version?: string; + readonly attributes: Readonly>; + }>; + readonly status?: + | { + readonly code?: string; + readonly message?: string; + } + | undefined; +} + +export type TraceRecord = EffectTraceRecord | OtlpTraceRecord; + +type OtlpSpan = OtlpTracer.ScopeSpan["spans"][number]; +type OtlpSpanEvent = OtlpSpan["events"][number]; +type OtlpSpanLink = OtlpSpan["links"][number]; +type OtlpSpanStatus = OtlpSpan["status"]; + +interface SerializableSpan { + readonly name: string; + readonly traceId: string; + readonly spanId: string; + readonly parent: Option.Option; + readonly status: Tracer.SpanStatus; + readonly sampled: boolean; + readonly kind: Tracer.SpanKind; + readonly attributes: ReadonlyMap; + readonly links: ReadonlyArray; + readonly events: ReadonlyArray< + readonly [name: string, startTime: bigint, attributes: Record] + >; +} + +function formatTraceExit(exit: Exit.Exit): EffectTraceRecord["exit"] { + if (Exit.isSuccess(exit)) { + return { _tag: "Success" }; + } + if (Cause.hasInterruptsOnly(exit.cause)) { + return { + _tag: "Interrupted", + cause: Cause.pretty(exit.cause), + }; + } + return { + _tag: "Failure", + cause: Cause.pretty(exit.cause), + }; +} + +export function spanToTraceRecord(span: SerializableSpan): EffectTraceRecord { + const status = span.status as Extract; + const parentSpanId = Option.getOrUndefined(span.parent)?.spanId; + + return { + type: "effect-span", + name: span.name, + traceId: span.traceId, + spanId: span.spanId, + ...(parentSpanId ? { parentSpanId } : {}), + sampled: span.sampled, + kind: span.kind, + startTimeUnixNano: String(status.startTime), + endTimeUnixNano: String(status.endTime), + durationMs: Number(status.endTime - status.startTime) / 1_000_000, + attributes: compactTraceAttributes(Object.fromEntries(span.attributes)), + events: span.events.map(([name, startTime, attributes]) => ({ + name, + timeUnixNano: String(startTime), + attributes: compactTraceAttributes(attributes), + })), + links: span.links.map((link) => ({ + traceId: link.span.traceId, + spanId: link.span.spanId, + attributes: compactTraceAttributes(link.attributes), + })), + exit: formatTraceExit(status.exit), + }; +} + +const SPAN_KIND_MAP: Record = { + 1: "internal", + 2: "server", + 3: "client", + 4: "producer", + 5: "consumer", +}; + +export function decodeOtlpTraceRecords( + payload: OtlpTracer.TraceData, +): ReadonlyArray { + const records: Array = []; + + for (const resourceSpan of payload.resourceSpans) { + const resourceAttributes = decodeAttributes(resourceSpan.resource?.attributes ?? []); + + for (const scopeSpan of resourceSpan.scopeSpans) { + for (const span of scopeSpan.spans) { + records.push( + otlpSpanToTraceRecord({ + resourceAttributes, + scopeAttributes: decodeAttributes( + "attributes" in scopeSpan.scope && Array.isArray(scopeSpan.scope.attributes) + ? scopeSpan.scope.attributes + : [], + ), + scopeName: scopeSpan.scope.name, + scopeVersion: + "version" in scopeSpan.scope && typeof scopeSpan.scope.version === "string" + ? scopeSpan.scope.version + : undefined, + span, + }), + ); + } + } + } + + return records; +} + +function otlpSpanToTraceRecord(input: { + readonly resourceAttributes: Readonly>; + readonly scopeAttributes: Readonly>; + readonly scopeName: string | undefined; + readonly scopeVersion: string | undefined; + readonly span: OtlpSpan; +}): OtlpTraceRecord { + return { + type: "otlp-span", + name: input.span.name, + traceId: input.span.traceId, + spanId: input.span.spanId, + ...(input.span.parentSpanId ? { parentSpanId: input.span.parentSpanId } : {}), + sampled: true, + kind: normalizeSpanKind(input.span.kind), + startTimeUnixNano: input.span.startTimeUnixNano, + endTimeUnixNano: input.span.endTimeUnixNano, + durationMs: + Number(parseBigInt(input.span.endTimeUnixNano) - parseBigInt(input.span.startTimeUnixNano)) / + 1_000_000, + attributes: decodeAttributes(input.span.attributes), + resourceAttributes: input.resourceAttributes, + scope: { + ...(input.scopeName ? { name: input.scopeName } : {}), + ...(input.scopeVersion ? { version: input.scopeVersion } : {}), + attributes: input.scopeAttributes, + }, + events: decodeEvents(input.span.events), + links: decodeLinks(input.span.links), + status: decodeStatus(input.span.status), + }; +} + +function decodeStatus(input: OtlpSpanStatus): OtlpTraceRecord["status"] { + const code = String(input.code); + const message = input.message; + + return { + code, + ...(message ? { message } : {}), + }; +} + +function decodeEvents(input: ReadonlyArray): ReadonlyArray { + return input.map((current) => ({ + name: current.name, + timeUnixNano: current.timeUnixNano, + attributes: decodeAttributes(current.attributes), + })); +} + +function decodeLinks(input: ReadonlyArray): ReadonlyArray { + return input.flatMap((current) => { + const traceId = current.traceId; + const spanId = current.spanId; + return { + traceId, + spanId, + attributes: decodeAttributes(current.attributes), + }; + }); +} + +function decodeAttributes( + input: ReadonlyArray, +): Readonly> { + const entries: Record = {}; + + for (const attribute of input) { + entries[attribute.key] = decodeValue(attribute.value); + } + + return compactTraceAttributes(entries); +} + +function decodeValue(input: OtlpResource.AnyValue | null | undefined): unknown { + if (input == null) { + return null; + } + if ("stringValue" in input) { + return input.stringValue; + } + if ("boolValue" in input) { + return input.boolValue; + } + if ("intValue" in input) { + return input.intValue; + } + if ("doubleValue" in input) { + return input.doubleValue; + } + if ("bytesValue" in input) { + return input.bytesValue; + } + if (input.arrayValue) { + return input.arrayValue.values.map((entry) => decodeValue(entry)); + } + if (input.kvlistValue) { + return decodeAttributes(input.kvlistValue.values); + } + return null; +} + +function normalizeSpanKind(input: number): OtlpTraceRecord["kind"] { + return SPAN_KIND_MAP[input] || "internal"; +} + +function parseBigInt(input: string): bigint { + try { + return BigInt(input); + } catch { + return 0n; + } +} diff --git a/apps/server/src/observability/TraceSink.test.ts b/apps/server/src/observability/TraceSink.test.ts new file mode 100644 index 0000000000..f4db90516b --- /dev/null +++ b/apps/server/src/observability/TraceSink.test.ts @@ -0,0 +1,152 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { assert, describe, it } from "@effect/vitest"; +import { Effect } from "effect"; + +import type { TraceRecord } from "./TraceRecord.ts"; +import { makeTraceSink } from "./TraceSink.ts"; + +const makeRecord = (name: string, suffix = ""): TraceRecord => ({ + type: "effect-span", + name, + traceId: `trace-${name}-${suffix}`, + spanId: `span-${name}-${suffix}`, + sampled: true, + kind: "internal", + startTimeUnixNano: "1", + endTimeUnixNano: "2", + durationMs: 1, + attributes: { + payload: suffix, + }, + events: [], + links: [], + exit: { + _tag: "Success", + }, +}); + +describe("TraceSink", () => { + it.effect("flushes buffered records on close", () => + Effect.scoped( + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-")); + const tracePath = path.join(tempDir, "server.trace.ndjson"); + + try { + const sink = yield* makeTraceSink({ + filePath: tracePath, + maxBytes: 1024, + maxFiles: 2, + batchWindowMs: 10_000, + }); + + sink.push(makeRecord("alpha")); + sink.push(makeRecord("beta")); + yield* sink.close(); + + const lines = fs + .readFileSync(tracePath, "utf8") + .trim() + .split("\n") + .map((line) => JSON.parse(line) as TraceRecord); + + assert.equal(lines.length, 2); + assert.equal(lines[0]?.name, "alpha"); + assert.equal(lines[1]?.name, "beta"); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ), + ); + + it.effect("rotates the trace file when the configured max size is exceeded", () => + Effect.scoped( + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-")); + const tracePath = path.join(tempDir, "server.trace.ndjson"); + + try { + const sink = yield* makeTraceSink({ + filePath: tracePath, + maxBytes: 180, + maxFiles: 2, + batchWindowMs: 10_000, + }); + + for (let index = 0; index < 8; index += 1) { + sink.push(makeRecord("rotate", `${index}-${"x".repeat(48)}`)); + yield* sink.flush; + } + yield* sink.close(); + + const matchingFiles = fs + .readdirSync(tempDir) + .filter( + (entry) => + entry === "server.trace.ndjson" || entry.startsWith("server.trace.ndjson."), + ) + .toSorted(); + + assert.equal( + matchingFiles.some((entry) => entry === "server.trace.ndjson.1"), + true, + ); + assert.equal( + matchingFiles.some((entry) => entry === "server.trace.ndjson.3"), + false, + ); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ), + ); + + it.effect("drops only the invalid record when serialization fails", () => + Effect.scoped( + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-")); + const tracePath = path.join(tempDir, "server.trace.ndjson"); + + try { + const sink = yield* makeTraceSink({ + filePath: tracePath, + maxBytes: 1024, + maxFiles: 2, + batchWindowMs: 10_000, + }); + + const circular: Array = []; + circular.push(circular); + + sink.push(makeRecord("alpha")); + sink.push({ + ...makeRecord("invalid"), + attributes: { + circular, + }, + } as TraceRecord); + sink.push(makeRecord("beta")); + yield* sink.close(); + + const lines = fs + .readFileSync(tracePath, "utf8") + .trim() + .split("\n") + .map((line) => JSON.parse(line) as TraceRecord); + + assert.deepStrictEqual( + lines.map((line) => line.name), + ["alpha", "beta"], + ); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ), + ); +}); diff --git a/apps/server/src/observability/TraceSink.ts b/apps/server/src/observability/TraceSink.ts new file mode 100644 index 0000000000..1bd00b4734 --- /dev/null +++ b/apps/server/src/observability/TraceSink.ts @@ -0,0 +1,68 @@ +import { RotatingFileSink } from "@t3tools/shared/logging"; +import { Effect } from "effect"; + +import type { TraceRecord } from "./TraceRecord.ts"; + +const FLUSH_BUFFER_THRESHOLD = 32; + +export interface TraceSinkOptions { + readonly filePath: string; + readonly maxBytes: number; + readonly maxFiles: number; + readonly batchWindowMs: number; +} + +export interface TraceSink { + readonly filePath: string; + push: (record: TraceRecord) => void; + flush: Effect.Effect; + close: () => Effect.Effect; +} + +export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: TraceSinkOptions) { + const sink = new RotatingFileSink({ + filePath: options.filePath, + maxBytes: options.maxBytes, + maxFiles: options.maxFiles, + }); + + let buffer: Array = []; + + const flushUnsafe = () => { + if (buffer.length === 0) { + return; + } + + const chunk = buffer.join(""); + buffer = []; + + try { + sink.write(chunk); + } catch { + buffer.unshift(chunk); + } + }; + + const flush = Effect.sync(flushUnsafe).pipe(Effect.withTracerEnabled(false)); + + yield* Effect.addFinalizer(() => flush.pipe(Effect.ignore)); + yield* Effect.forkScoped( + Effect.sleep(`${options.batchWindowMs} millis`).pipe(Effect.andThen(flush), Effect.forever), + ); + + return { + filePath: options.filePath, + push(record) { + try { + buffer.push(`${JSON.stringify(record)}\n`); + if (buffer.length >= FLUSH_BUFFER_THRESHOLD) { + flushUnsafe(); + } + } catch { + return; + } + }, + flush, + close: () => flush, + } satisfies TraceSink; +}); diff --git a/apps/server/src/open.test.ts b/apps/server/src/open.test.ts new file mode 100644 index 0000000000..6711e9da81 --- /dev/null +++ b/apps/server/src/open.test.ts @@ -0,0 +1,406 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { assertSuccess } from "@effect/vitest/utils"; +import { FileSystem, Path, Effect } from "effect"; + +import { + isCommandAvailable, + launchDetached, + resolveAvailableEditors, + resolveEditorLaunch, +} from "./open"; + +it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { + it.effect("returns commands for command-based editors", () => + Effect.gen(function* () { + const antigravityLaunch = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "antigravity" }, + "darwin", + { PATH: "" }, + ); + assert.deepEqual(antigravityLaunch, { + command: "agy", + args: ["/tmp/workspace"], + }); + + const cursorLaunch = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "cursor" }, + "darwin", + { PATH: "" }, + ); + assert.deepEqual(cursorLaunch, { + command: "cursor", + args: ["/tmp/workspace"], + }); + + const traeLaunch = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "trae" }, + "darwin", + ); + assert.deepEqual(traeLaunch, { + command: "trae", + args: ["/tmp/workspace"], + }); + + const vscodeLaunch = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "vscode" }, + "darwin", + { PATH: "" }, + ); + assert.deepEqual(vscodeLaunch, { + command: "code", + 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", + { PATH: "" }, + ); + assert.deepEqual(zedLaunch, { + command: "zed", + args: ["/tmp/workspace"], + }); + + const ideaLaunch = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "idea" }, + "darwin", + ); + assert.deepEqual(ideaLaunch, { + command: "idea", + args: ["/tmp/workspace"], + }); + }), + ); + + it.effect("applies launch-style-specific navigation arguments", () => + Effect.gen(function* () { + const lineOnly = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" }, + "darwin", + { PATH: "" }, + ); + assert.deepEqual(lineOnly, { + command: "cursor", + args: ["--goto", "/tmp/workspace/AGENTS.md:48"], + }); + + const lineAndColumn = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" }, + "darwin", + { PATH: "" }, + ); + assert.deepEqual(lineAndColumn, { + command: "cursor", + args: ["--goto", "/tmp/workspace/src/open.ts:71:5"], + }); + + const traeLineAndColumn = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "trae" }, + "darwin", + ); + assert.deepEqual(traeLineAndColumn, { + command: "trae", + args: ["--goto", "/tmp/workspace/src/open.ts:71:5"], + }); + + const vscodeLineAndColumn = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" }, + "darwin", + { PATH: "" }, + ); + assert.deepEqual(vscodeLineAndColumn, { + command: "code", + 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", + { PATH: "" }, + ); + assert.deepEqual(zedLineAndColumn, { + command: "zed", + args: ["/tmp/workspace/src/open.ts:71:5"], + }); + + const zedLineOnly = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/AGENTS.md:48", editor: "zed" }, + "darwin", + { PATH: "" }, + ); + assert.deepEqual(zedLineOnly, { + command: "zed", + args: ["/tmp/workspace/AGENTS.md:48"], + }); + + const ideaLineOnly = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/AGENTS.md:48", editor: "idea" }, + "darwin", + ); + assert.deepEqual(ideaLineOnly, { + command: "idea", + args: ["--line", "48", "/tmp/workspace/AGENTS.md"], + }); + + const ideaLineAndColumn = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "idea" }, + "darwin", + ); + assert.deepEqual(ideaLineAndColumn, { + command: "idea", + args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"], + }); + }), + ); + + it.effect("falls back to zeditor when zed is not installed", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" }); + yield* fs.writeFileString(path.join(dir, "zeditor"), "#!/bin/sh\nexit 0\n"); + yield* fs.chmod(path.join(dir, "zeditor"), 0o755); + + const result = yield* resolveEditorLaunch({ cwd: "/tmp/workspace", editor: "zed" }, "linux", { + PATH: dir, + }); + + assert.deepEqual(result, { + command: "zeditor", + args: ["/tmp/workspace"], + }); + }), + ); + + it.effect("falls back to the primary command when no alias is installed", () => + Effect.gen(function* () { + const result = yield* resolveEditorLaunch({ cwd: "/tmp/workspace", editor: "zed" }, "linux", { + PATH: "", + }); + assert.deepEqual(result, { + command: "zed", + args: ["/tmp/workspace"], + }); + }), + ); + + it.effect("maps file-manager editor to OS open commands", () => + Effect.gen(function* () { + const launch1 = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "file-manager" }, + "darwin", + { PATH: "" }, + ); + assert.deepEqual(launch1, { + command: "open", + args: ["/tmp/workspace"], + }); + + const launch2 = yield* resolveEditorLaunch( + { cwd: "C:\\workspace", editor: "file-manager" }, + "win32", + { PATH: "" }, + ); + assert.deepEqual(launch2, { + command: "explorer", + args: ["C:\\workspace"], + }); + + const launch3 = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "file-manager" }, + "linux", + { PATH: "" }, + ); + assert.deepEqual(launch3, { + command: "xdg-open", + args: ["/tmp/workspace"], + }); + }), + ); + + it.effect("uses explorer with a VS Code protocol target on Windows", () => + Effect.gen(function* () { + const launch = yield* resolveEditorLaunch( + { cwd: "C:\\work\\100% real\\file.ts:12:4", editor: "vscode" }, + "win32", + { PATH: "" }, + ); + assert.deepEqual(launch, { + command: "explorer", + args: ["vscode://file/C:/work/100%25%20real/file.ts:12:4"], + }); + }), + ); +}); + +it.layer(NodeServices.layer)("launchDetached", (it) => { + it.effect("resolves when command can be spawned", () => + Effect.gen(function* () { + const result = yield* launchDetached({ + command: process.execPath, + args: ["-e", "process.exit(0)"], + }).pipe(Effect.result); + assertSuccess(result, undefined); + }), + ); + + it.effect("rejects when command does not exist", () => + Effect.gen(function* () { + const result = yield* launchDetached({ + command: `t3code-no-such-command-${Date.now()}`, + args: [], + }).pipe(Effect.result); + assert.equal(result._tag, "Failure"); + }), + ); +}); + +it.layer(NodeServices.layer)("isCommandAvailable", (it) => { + it.effect("resolves win32 commands with PATHEXT", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" }); + yield* fs.writeFileString(path.join(dir, "code.CMD"), "@echo off\r\n"); + const env = { + PATH: dir, + PATHEXT: ".COM;.EXE;.BAT;.CMD", + } satisfies NodeJS.ProcessEnv; + assert.equal(isCommandAvailable("code", { platform: "win32", env }), true); + }), + ); + + it("returns false when a command is not on PATH", () => { + const env = { + PATH: "", + PATHEXT: ".COM;.EXE;.BAT;.CMD", + } satisfies NodeJS.ProcessEnv; + assert.equal(isCommandAvailable("definitely-not-installed", { platform: "win32", env }), false); + }); + + it.effect("does not treat bare files without executable extension as available on win32", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" }); + yield* fs.writeFileString(path.join(dir, "npm"), "echo nope\r\n"); + const env = { + PATH: dir, + PATHEXT: ".COM;.EXE;.BAT;.CMD", + } satisfies NodeJS.ProcessEnv; + assert.equal(isCommandAvailable("npm", { platform: "win32", env }), false); + }), + ); + + it.effect("appends PATHEXT for commands with non-executable extensions on win32", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" }); + yield* fs.writeFileString(path.join(dir, "my.tool.CMD"), "@echo off\r\n"); + const env = { + PATH: dir, + PATHEXT: ".COM;.EXE;.BAT;.CMD", + } satisfies NodeJS.ProcessEnv; + assert.equal(isCommandAvailable("my.tool", { platform: "win32", env }), true); + }), + ); + + it.effect("uses platform-specific PATH delimiter for platform overrides", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const firstDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" }); + const secondDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" }); + yield* fs.writeFileString(path.join(firstDir, "code.CMD"), "@echo off\r\n"); + yield* fs.writeFileString(path.join(secondDir, "code.CMD"), "MZ"); + const env = { + PATH: `${firstDir};${secondDir}`, + PATHEXT: ".COM;.EXE;.BAT;.CMD", + } satisfies NodeJS.ProcessEnv; + assert.equal(isCommandAvailable("code", { platform: "win32", env }), true); + }), + ); +}); + +it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => { + it.effect("returns installed editors for command launches", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" }); + + yield* fs.writeFileString(path.join(dir, "trae.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, ["trae", "vscode-insiders", "vscodium", "file-manager"]); + }), + ); + + it.effect("includes zed when only the zeditor command is installed", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" }); + + yield* fs.writeFileString(path.join(dir, "zeditor"), "#!/bin/sh\nexit 0\n"); + yield* fs.writeFileString(path.join(dir, "xdg-open"), "#!/bin/sh\nexit 0\n"); + yield* fs.chmod(path.join(dir, "zeditor"), 0o755); + yield* fs.chmod(path.join(dir, "xdg-open"), 0o755); + + const editors = resolveAvailableEditors("linux", { + PATH: dir, + }); + assert.deepEqual(editors, ["zed", "file-manager"]); + }), + ); + + it("omits file-manager when the platform opener is unavailable", () => { + const editors = resolveAvailableEditors("linux", { + PATH: "", + }); + assert.deepEqual(editors, []); + }); +}); diff --git a/apps/server/src/open.ts b/apps/server/src/open.ts new file mode 100644 index 0000000000..945974d03a --- /dev/null +++ b/apps/server/src/open.ts @@ -0,0 +1,386 @@ +/** + * Open - Browser/editor launch service interface. + * + * Owns process launch helpers for opening URLs in a browser and workspace + * paths in a configured editor. + * + * @module Open + */ +import { spawn } from "node:child_process"; +import { accessSync, constants, statSync } from "node:fs"; +import { extname, join } from "node:path"; +import { pathToFileURL } from "node:url"; + +import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts"; +import { Context, Effect, Layer } from "effect"; + +// ============================== +// Definitions +// ============================== + +export { OpenError }; + +export interface OpenInEditorInput { + readonly cwd: string; + readonly editor: EditorId; +} + +interface EditorLaunch { + readonly command: string; + readonly args: ReadonlyArray; +} + +interface CommandAvailabilityOptions { + readonly platform?: NodeJS.Platform; + readonly env?: NodeJS.ProcessEnv; +} + +const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/; +const WINDOWS_EDITOR_URI_SCHEMES: Partial> = { + vscode: "vscode", + "vscode-insiders": "vscode-insiders", + vscodium: "vscodium", +}; + +function parseTargetPathAndPosition(target: string): { + path: string; + line: string | undefined; + column: string | undefined; +} | null { + const match = TARGET_WITH_POSITION_PATTERN.exec(target); + if (!match?.[1] || !match[2]) { + return null; + } + + return { + path: match[1], + line: match[2], + column: match[3], + }; +} + +function splitTargetPathAndSuffix(target: string): { + path: string; + suffix: string; +} { + const parsedTarget = parseTargetPathAndPosition(target); + if (!parsedTarget) { + return { path: target, suffix: "" }; + } + + return { + path: parsedTarget.path, + suffix: parsedTarget.column + ? `:${parsedTarget.line}:${parsedTarget.column}` + : `:${parsedTarget.line}`, + }; +} + +function makeWindowsEditorProtocolTarget(editor: EditorId, target: string): string | undefined { + const scheme = WINDOWS_EDITOR_URI_SCHEMES[editor]; + if (!scheme) return undefined; + + const { path, suffix } = splitTargetPathAndSuffix(target); + const fileUrl = pathToFileURL(path).href; + const fileTarget = fileUrl.startsWith("file:///") + ? fileUrl.slice("file:///".length) + : fileUrl.replace(/^file:\/\//, ""); + + return `${scheme}://file/${fileTarget}${suffix}`; +} + +function resolveCommandEditorArgs( + editor: (typeof EDITORS)[number], + target: string, +): ReadonlyArray { + const parsedTarget = parseTargetPathAndPosition(target); + + switch (editor.launchStyle) { + case "direct-path": + return [target]; + case "goto": + return parsedTarget ? ["--goto", target] : [target]; + case "line-column": { + if (!parsedTarget) { + return [target]; + } + + const { path, line, column } = parsedTarget; + return [...(line ? ["--line", line] : []), ...(column ? ["--column", column] : []), path]; + } + } +} + +function resolveAvailableCommand( + commands: ReadonlyArray, + options: CommandAvailabilityOptions = {}, +): string | null { + for (const command of commands) { + if (isCommandAvailable(command, options)) { + return command; + } + } + return null; +} + +function fileManagerCommandForPlatform(platform: NodeJS.Platform): string { + switch (platform) { + case "darwin": + return "open"; + case "win32": + return "explorer"; + default: + return "xdg-open"; + } +} + +function stripWrappingQuotes(value: string): string { + return value.replace(/^"+|"+$/g, ""); +} + +function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string { + return env.PATH ?? env.Path ?? env.path ?? ""; +} + +function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray { + const rawValue = env.PATHEXT; + const fallback = [".COM", ".EXE", ".BAT", ".CMD"]; + if (!rawValue) return fallback; + + const parsed = rawValue + .split(";") + .map((entry) => entry.trim()) + .filter((entry) => entry.length > 0) + .map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`)); + return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback; +} + +function resolveCommandCandidates( + command: string, + platform: NodeJS.Platform, + windowsPathExtensions: ReadonlyArray, +): ReadonlyArray { + if (platform !== "win32") return [command]; + const extension = extname(command); + const normalizedExtension = extension.toUpperCase(); + + if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) { + const commandWithoutExtension = command.slice(0, -extension.length); + return Array.from( + new Set([ + command, + `${commandWithoutExtension}${normalizedExtension}`, + `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`, + ]), + ); + } + + const candidates: string[] = []; + for (const extension of windowsPathExtensions) { + candidates.push(`${command}${extension}`); + candidates.push(`${command}${extension.toLowerCase()}`); + } + return Array.from(new Set(candidates)); +} + +function isExecutableFile( + filePath: string, + platform: NodeJS.Platform, + windowsPathExtensions: ReadonlyArray, +): boolean { + try { + const stat = statSync(filePath); + if (!stat.isFile()) return false; + if (platform === "win32") { + const extension = extname(filePath); + if (extension.length === 0) return false; + return windowsPathExtensions.includes(extension.toUpperCase()); + } + accessSync(filePath, constants.X_OK); + return true; + } catch { + return false; + } +} + +function resolvePathDelimiter(platform: NodeJS.Platform): string { + return platform === "win32" ? ";" : ":"; +} + +export function isCommandAvailable( + command: string, + options: CommandAvailabilityOptions = {}, +): boolean { + const platform = options.platform ?? process.platform; + const env = options.env ?? process.env; + const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : []; + const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions); + + if (command.includes("/") || command.includes("\\")) { + return commandCandidates.some((candidate) => + isExecutableFile(candidate, platform, windowsPathExtensions), + ); + } + + const pathValue = resolvePathEnvironmentVariable(env); + if (pathValue.length === 0) return false; + const pathEntries = pathValue + .split(resolvePathDelimiter(platform)) + .map((entry) => stripWrappingQuotes(entry.trim())) + .filter((entry) => entry.length > 0); + + for (const pathEntry of pathEntries) { + for (const candidate of commandCandidates) { + if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) { + return true; + } + } + } + return false; +} + +export function resolveAvailableEditors( + platform: NodeJS.Platform = process.platform, + env: NodeJS.ProcessEnv = process.env, +): ReadonlyArray { + const available: EditorId[] = []; + + for (const editor of EDITORS) { + if (editor.commands === null) { + const command = fileManagerCommandForPlatform(platform); + if (isCommandAvailable(command, { platform, env })) { + available.push(editor.id); + } + continue; + } + + const command = resolveAvailableCommand(editor.commands, { platform, env }); + if (command !== null) { + available.push(editor.id); + } + } + + return available; +} + +/** + * OpenShape - Service API for browser and editor launch actions. + */ +export interface OpenShape { + /** + * Open a URL target in the default browser. + */ + readonly openBrowser: (target: string) => Effect.Effect; + + /** + * Open a workspace path in a selected editor integration. + * + * Launches the editor as a detached process so server startup is not blocked. + */ + readonly openInEditor: (input: OpenInEditorInput) => Effect.Effect; +} + +/** + * Open - Service tag for browser/editor launch operations. + */ +export class Open extends Context.Service()("t3/open") {} + +// ============================== +// Implementations +// ============================== + +export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* ( + input: OpenInEditorInput, + platform: NodeJS.Platform = process.platform, + env: NodeJS.ProcessEnv = process.env, +): Effect.fn.Return { + yield* Effect.annotateCurrentSpan({ + "open.editor": input.editor, + "open.cwd": input.cwd, + "open.platform": platform, + }); + const editorDef = EDITORS.find((editor) => editor.id === input.editor); + if (!editorDef) { + return yield* new OpenError({ message: `Unknown editor: ${input.editor}` }); + } + + if (platform === "win32") { + const protocolTarget = makeWindowsEditorProtocolTarget(input.editor, input.cwd); + if (protocolTarget) { + return { + command: fileManagerCommandForPlatform(platform), + args: [protocolTarget], + }; + } + } + + if (editorDef.commands) { + const command = + resolveAvailableCommand(editorDef.commands, { platform, env }) ?? editorDef.commands[0]; + return { + command, + args: resolveCommandEditorArgs(editorDef, input.cwd), + }; + } + + if (editorDef.id !== "file-manager") { + return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` }); + } + + return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] }; +}); + +export const launchDetached = (launch: EditorLaunch) => + Effect.gen(function* () { + if (!isCommandAvailable(launch.command)) { + return yield* new OpenError({ message: `Editor command not found: ${launch.command}` }); + } + + yield* Effect.callback((resume) => { + let child; + try { + child = spawn(launch.command, [...launch.args], { + detached: true, + stdio: "ignore", + shell: + process.platform === "win32" && + launch.command.toLowerCase() !== "explorer" && + !launch.command.toLowerCase().endsWith("\\explorer.exe") && + !launch.command.toLowerCase().endsWith("/explorer.exe"), + ...(process.platform === "win32" ? { windowsHide: true } : {}), + }); + } catch (error) { + return resume( + Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })), + ); + } + + const handleSpawn = () => { + child.unref(); + resume(Effect.void); + }; + + child.once("spawn", handleSpawn); + child.once("error", (cause) => + resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))), + ); + }); + }); + +const make = Effect.gen(function* () { + const open = yield* Effect.tryPromise({ + try: () => import("open"), + catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }), + }); + + return { + openBrowser: (target) => + Effect.tryPromise({ + try: () => open.default(target), + catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }), + }), + openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached), + } satisfies OpenShape; +}); + +export const OpenLive = Layer.effect(Open, make); diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts index 7c201af375..12e11450dd 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts @@ -20,9 +20,12 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts"; import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts"; import { GitCoreLive } from "../../git/Layers/GitCore.ts"; +import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts"; +import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts"; import { CheckpointReactorLive } from "./CheckpointReactor.ts"; import { OrchestrationEngineLive } from "./OrchestrationEngine.ts"; import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts"; +import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts"; import { RuntimeReceiptBusLive } from "./RuntimeReceiptBus.ts"; import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts"; import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts"; @@ -39,9 +42,10 @@ import { 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); +const asProjectId = (value: string): ProjectId => ProjectId.make(value); +const asTurnId = (value: string): TurnId => TurnId.make(value); type LegacyProviderRuntimeEvent = { readonly type: string; @@ -77,7 +81,7 @@ function createProviderServiceHarness( provider: providerName, status: "ready", runtimeMode: "full-access", - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), cwd: sessionCwd, createdAt: now, updatedAt: now, @@ -94,7 +98,9 @@ function createProviderServiceHarness( listSessions, getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }), rollbackConversation, - streamEvents: Stream.fromPubSub(runtimeEventPubSub), + get streamEvents() { + return Stream.fromPubSub(runtimeEventPubSub); + }, }; const emit = (event: LegacyProviderRuntimeEvent): void => { @@ -115,7 +121,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<{ @@ -124,7 +130,7 @@ async function waitForThread( activities: ReadonlyArray<{ kind: string }>; }> => { const readModel = await Effect.runPromise(engine.getReadModel()); - const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); if (thread && predicate(thread)) { return thread; } @@ -140,7 +146,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 () => { @@ -191,7 +197,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)) { @@ -238,6 +244,7 @@ describe("CheckpointReactor", () => { readonly threadWorktreePath?: string | null; readonly providerSessionCwd?: string; readonly providerName?: ProviderKind; + readonly gitStatusRefreshCalls?: Array; }) { const cwd = createGitRepository(); tempDirs.push(cwd); @@ -248,22 +255,44 @@ describe("CheckpointReactor", () => { options?.providerName ?? "codex", ); const orchestrationLayer = OrchestrationEngineLive.pipe( + Layer.provide(OrchestrationProjectionSnapshotQueryLive), Layer.provide(OrchestrationProjectionPipelineLive), Layer.provide(OrchestrationEventStoreLive), Layer.provide(OrchestrationCommandReceiptRepositoryLive), + Layer.provide(RepositoryIdentityResolverLive), Layer.provide(SqlitePersistenceMemory), ); const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), { prefix: "t3-checkpoint-reactor-test-", }); + const gitStatusBroadcasterLayer = Layer.succeed(GitStatusBroadcaster, { + getStatus: () => Effect.die("getStatus should not be called in this test"), + refreshLocalStatus: (cwd: string) => + Effect.sync(() => { + options?.gitStatusRefreshCalls?.push(cwd); + }).pipe( + Effect.as({ + isRepo: true, + hasOriginRemote: false, + isDefaultBranch: true, + branch: "main", + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + }), + ), + refreshStatus: () => Effect.die("refreshStatus should not be called in this test"), + streamStatus: () => Stream.empty, + }); const layer = CheckpointReactorLive.pipe( Layer.provideMerge(orchestrationLayer), Layer.provideMerge(RuntimeReceiptBusLive), Layer.provideMerge(Layer.succeed(ProviderService, provider.service)), + Layer.provideMerge(gitStatusBroadcasterLayer), Layer.provideMerge(CheckpointStoreLive), - Layer.provideMerge(WorkspaceEntriesLive), + Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))), + Layer.provideMerge(WorkspacePathsLive), Layer.provideMerge(GitCoreLive), Layer.provideMerge(ServerConfigLayer), Layer.provideMerge(NodeServices.layer), @@ -281,7 +310,7 @@ describe("CheckpointReactor", () => { await Effect.runPromise( engine.dispatch({ type: "project.create", - commandId: CommandId.makeUnsafe("cmd-project-create"), + commandId: CommandId.make("cmd-project-create"), projectId: asProjectId("project-1"), title: "Test Project", workspaceRoot: options?.projectWorkspaceRoot ?? cwd, @@ -295,8 +324,8 @@ describe("CheckpointReactor", () => { await Effect.runPromise( engine.dispatch({ type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-thread-create"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-thread-create"), + threadId: ThreadId.make("thread-1"), projectId: asProjectId("project-1"), title: "Thread", modelSelection: { @@ -315,21 +344,21 @@ describe("CheckpointReactor", () => { await runtime.runPromise( checkpointStore.captureCheckpoint({ cwd, - checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0), + checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0), }), ); fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8"); await runtime.runPromise( checkpointStore.captureCheckpoint({ cwd, - checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1), + checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1), }), ); fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8"); await runtime.runPromise( checkpointStore.captureCheckpoint({ cwd, - checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2), + checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2), }), ); } @@ -349,10 +378,10 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set-capture"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-session-set-capture"), + threadId: ThreadId.make("thread-1"), session: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), status: "ready", providerName: "codex", runtimeMode: "approval-required", @@ -366,26 +395,26 @@ describe("CheckpointReactor", () => { harness.provider.emit({ type: "turn.started", - eventId: EventId.makeUnsafe("evt-turn-started-1"), + eventId: EventId.make("evt-turn-started-1"), provider: "codex", createdAt: new Date().toISOString(), - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-1"), }); await waitForGitRefExists( harness.cwd, - checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0), + checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0), ); fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8"); harness.provider.emit({ type: "turn.completed", - eventId: EventId.makeUnsafe("evt-turn-completed-1"), + eventId: EventId.make("evt-turn-completed-1"), provider: "codex", createdAt: new Date().toISOString(), - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-1"), payload: { state: "completed" }, }); @@ -397,27 +426,49 @@ describe("CheckpointReactor", () => { ); expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1); expect( - gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0)), + gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0)), ).toBe(true); expect( - gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)), + gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1)), ).toBe(true); expect( gitShowFileAtRef( harness.cwd, - checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0), + checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0), "README.md", ), ).toBe("v1\n"); expect( gitShowFileAtRef( harness.cwd, - checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1), + checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1), "README.md", ), ).toBe("v2\n"); }); + it("refreshes local git status state on turn completion using the session cwd", async () => { + const gitStatusRefreshCalls: string[] = []; + const harness = await createHarness({ + seedFilesystemCheckpoints: false, + gitStatusRefreshCalls, + }); + + harness.provider.emit({ + type: "turn.completed", + eventId: EventId.make("evt-turn-completed-refresh-local-status"), + provider: "codex", + createdAt: new Date().toISOString(), + threadId: ThreadId.make("thread-1"), + turnId: asTurnId("turn-refresh-local-status"), + payload: { state: "completed" }, + }); + + await harness.drain(); + + expect(gitStatusRefreshCalls).toEqual([harness.cwd]); + }); + it("ignores auxiliary thread turn completion while primary turn is active", async () => { const harness = await createHarness({ seedFilesystemCheckpoints: false }); const createdAt = new Date().toISOString(); @@ -425,10 +476,10 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set-primary-running"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-session-set-primary-running"), + threadId: ThreadId.make("thread-1"), session: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), status: "running", providerName: "codex", runtimeMode: "approval-required", @@ -442,45 +493,43 @@ describe("CheckpointReactor", () => { harness.provider.emit({ type: "turn.started", - eventId: EventId.makeUnsafe("evt-turn-started-main"), + eventId: EventId.make("evt-turn-started-main"), provider: "codex", createdAt: new Date().toISOString(), - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-main"), }); await waitForGitRefExists( harness.cwd, - checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0), + checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0), ); fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8"); harness.provider.emit({ type: "turn.completed", - eventId: EventId.makeUnsafe("evt-turn-completed-aux"), + eventId: EventId.make("evt-turn-completed-aux"), provider: "codex", createdAt: new Date().toISOString(), - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-aux"), payload: { state: "completed" }, }); await harness.drain(); const midReadModel = await Effect.runPromise(harness.engine.getReadModel()); - const midThread = midReadModel.threads.find( - (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), - ); + const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); expect(midThread?.checkpoints).toHaveLength(0); harness.provider.emit({ type: "turn.completed", - eventId: EventId.makeUnsafe("evt-turn-completed-main"), + eventId: EventId.make("evt-turn-completed-main"), provider: "codex", createdAt: new Date().toISOString(), - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-main"), payload: { state: "completed" }, }); @@ -502,10 +551,10 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set-capture-claude"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-session-set-capture-claude"), + threadId: ThreadId.make("thread-1"), session: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), status: "ready", providerName: "claudeAgent", runtimeMode: "approval-required", @@ -519,24 +568,24 @@ describe("CheckpointReactor", () => { harness.provider.emit({ type: "turn.started", - eventId: EventId.makeUnsafe("evt-turn-started-claude-1"), + eventId: EventId.make("evt-turn-started-claude-1"), provider: "claudeAgent", createdAt: new Date().toISOString(), - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-claude-1"), }); await waitForGitRefExists( harness.cwd, - checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0), + checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0), ); fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8"); harness.provider.emit({ type: "turn.completed", - eventId: EventId.makeUnsafe("evt-turn-completed-claude-1"), + eventId: EventId.make("evt-turn-completed-claude-1"), provider: "claudeAgent", createdAt: new Date().toISOString(), - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-claude-1"), payload: { state: "completed" }, }); @@ -549,7 +598,7 @@ describe("CheckpointReactor", () => { expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1); expect( - gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)), + gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1)), ).toBe(true); }); @@ -560,10 +609,10 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set-missing-baseline-diff"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-session-set-missing-baseline-diff"), + threadId: ThreadId.make("thread-1"), session: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), status: "ready", providerName: "codex", runtimeMode: "approval-required", @@ -577,11 +626,11 @@ describe("CheckpointReactor", () => { harness.provider.emit({ type: "turn.completed", - eventId: EventId.makeUnsafe("evt-turn-completed-missing-baseline"), + eventId: EventId.make("evt-turn-completed-missing-baseline"), provider: "codex", createdAt: new Date().toISOString(), - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-missing-baseline"), payload: { state: "completed" }, }); @@ -610,10 +659,10 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-for-baseline"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-for-baseline"), + threadId: ThreadId.make("thread-1"), message: { - messageId: MessageId.makeUnsafe("message-user-1"), + messageId: MessageId.make("message-user-1"), role: "user", text: "start turn", attachments: [], @@ -626,12 +675,12 @@ describe("CheckpointReactor", () => { await waitForGitRefExists( harness.cwd, - checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0), + checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0), ); expect( gitShowFileAtRef( harness.cwd, - checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0), + checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0), "README.md", ), ).toBe("v1\n"); @@ -648,10 +697,10 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set-missing-provider-cwd"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-session-set-missing-provider-cwd"), + threadId: ThreadId.make("thread-1"), session: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), status: "running", providerName: "codex", runtimeMode: "approval-required", @@ -666,23 +715,23 @@ describe("CheckpointReactor", () => { fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8"); harness.provider.emit({ type: "turn.completed", - eventId: EventId.makeUnsafe("evt-turn-completed-missing-provider-cwd"), + eventId: EventId.make("evt-turn-completed-missing-provider-cwd"), provider: "codex", createdAt: new Date().toISOString(), - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-missing-cwd"), payload: { state: "completed" }, }); await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed"); expect( - gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)), + gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1)), ).toBe(true); expect( gitShowFileAtRef( harness.cwd, - checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1), + checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1), "README.md", ), ).toBe("v2\n"); @@ -695,10 +744,10 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set-checkpoint-captured"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-session-set-checkpoint-captured"), + threadId: ThreadId.make("thread-1"), session: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), status: "ready", providerName: "codex", runtimeMode: "approval-required", @@ -712,11 +761,11 @@ describe("CheckpointReactor", () => { harness.provider.emit({ type: "checkpoint.captured", - eventId: EventId.makeUnsafe("evt-checkpoint-captured-3"), + eventId: EventId.make("evt-checkpoint-captured-3"), provider: "codex", createdAt: new Date().toISOString(), - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-3"), turnCount: 3, status: "completed", @@ -724,7 +773,7 @@ describe("CheckpointReactor", () => { await harness.drain(); const readModel = await Effect.runPromise(harness.engine.getReadModel()); - const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); expect(thread?.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe( false, ); @@ -745,10 +794,10 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set-non-repo-runtime"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-session-set-non-repo-runtime"), + threadId: ThreadId.make("thread-1"), session: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), status: "ready", providerName: "codex", runtimeMode: "approval-required", @@ -762,31 +811,31 @@ describe("CheckpointReactor", () => { harness.provider.emit({ type: "turn.completed", - eventId: EventId.makeUnsafe("evt-runtime-capture-failure"), + eventId: EventId.make("evt-runtime-capture-failure"), provider: "codex", createdAt: new Date().toISOString(), - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-runtime-failure"), payload: { state: "completed" }, }); harness.provider.emit({ type: "turn.started", - eventId: EventId.makeUnsafe("evt-turn-started-after-runtime-failure"), + eventId: EventId.make("evt-turn-started-after-runtime-failure"), provider: "codex", createdAt: new Date().toISOString(), - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-after-runtime-failure"), }); await waitForGitRefExists( harness.cwd, - checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0), + checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0), ); expect( - gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0)), + gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0)), ).toBe(true); }); @@ -797,10 +846,10 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-session-set"), + threadId: ThreadId.make("thread-1"), session: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), status: "ready", providerName: "codex", runtimeMode: "approval-required", @@ -815,11 +864,11 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.diff.complete", - commandId: CommandId.makeUnsafe("cmd-diff-1"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-diff-1"), + threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-1"), completedAt: createdAt, - checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1), + checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1), status: "ready", files: [], checkpointTurnCount: 1, @@ -829,11 +878,11 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.diff.complete", - commandId: CommandId.makeUnsafe("cmd-diff-2"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-diff-2"), + threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-2"), completedAt: createdAt, - checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2), + checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2), status: "ready", files: [], checkpointTurnCount: 2, @@ -844,8 +893,8 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.checkpoint.revert", - commandId: CommandId.makeUnsafe("cmd-revert-request"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-revert-request"), + threadId: ThreadId.make("thread-1"), turnCount: 1, createdAt, }), @@ -859,12 +908,12 @@ describe("CheckpointReactor", () => { expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1); expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1); expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({ - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), numTurns: 1, }); expect(fs.readFileSync(path.join(harness.cwd, "README.md"), "utf8")).toBe("v2\n"); expect( - gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2)), + gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2)), ).toBe(false); }); @@ -875,10 +924,10 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set-claude"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-session-set-claude"), + threadId: ThreadId.make("thread-1"), session: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), status: "ready", providerName: "claudeAgent", runtimeMode: "approval-required", @@ -893,11 +942,11 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.diff.complete", - commandId: CommandId.makeUnsafe("cmd-diff-claude-1"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-diff-claude-1"), + threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-claude-1"), completedAt: createdAt, - checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1), + checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1), status: "ready", files: [], checkpointTurnCount: 1, @@ -907,11 +956,11 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.diff.complete", - commandId: CommandId.makeUnsafe("cmd-diff-claude-2"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-diff-claude-2"), + threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-claude-2"), completedAt: createdAt, - checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2), + checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2), status: "ready", files: [], checkpointTurnCount: 2, @@ -922,8 +971,8 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.checkpoint.revert", - commandId: CommandId.makeUnsafe("cmd-revert-request-claude"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-revert-request-claude"), + threadId: ThreadId.make("thread-1"), turnCount: 1, createdAt, }), @@ -932,7 +981,7 @@ describe("CheckpointReactor", () => { await waitForEvent(harness.engine, (event) => event.type === "thread.reverted"); expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1); expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({ - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), numTurns: 1, }); }); @@ -944,10 +993,10 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set-inline-revert"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-session-set-inline-revert"), + threadId: ThreadId.make("thread-1"), session: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), status: "ready", providerName: "codex", runtimeMode: "approval-required", @@ -962,11 +1011,11 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.diff.complete", - commandId: CommandId.makeUnsafe("cmd-inline-revert-diff-1"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-inline-revert-diff-1"), + threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-1"), completedAt: createdAt, - checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1), + checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1), status: "ready", files: [], checkpointTurnCount: 1, @@ -976,11 +1025,11 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.diff.complete", - commandId: CommandId.makeUnsafe("cmd-inline-revert-diff-2"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-inline-revert-diff-2"), + threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-2"), completedAt: createdAt, - checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2), + checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2), status: "ready", files: [], checkpointTurnCount: 2, @@ -991,8 +1040,8 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.checkpoint.revert", - commandId: CommandId.makeUnsafe("cmd-sequenced-revert-request-1"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-sequenced-revert-request-1"), + threadId: ThreadId.make("thread-1"), turnCount: 1, createdAt, }), @@ -1000,33 +1049,22 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.checkpoint.revert", - commandId: CommandId.makeUnsafe("cmd-sequenced-revert-request-0"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-sequenced-revert-request-0"), + threadId: ThreadId.make("thread-1"), turnCount: 0, createdAt, }), ); - 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({ - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), numTurns: 1, }); expect(harness.provider.rollbackConversation.mock.calls[1]?.[0]).toEqual({ - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), numTurns: 1, }); }); @@ -1038,8 +1076,8 @@ describe("CheckpointReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.checkpoint.revert", - commandId: CommandId.makeUnsafe("cmd-revert-no-session"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-revert-no-session"), + threadId: ThreadId.make("thread-1"), turnCount: 1, createdAt, }), diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.ts index 28609cecb3..0b1b203ba2 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts @@ -24,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 { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts"; import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts"; type ReactorInput = @@ -37,7 +38,7 @@ type ReactorInput = }; function toTurnId(value: string | undefined): TurnId | null { - return value === undefined ? null : TurnId.makeUnsafe(String(value)); + return value === undefined ? null : TurnId.make(String(value)); } function sameId(left: string | null | undefined, right: string | null | undefined): boolean { @@ -61,7 +62,7 @@ function checkpointStatusFromRuntime(status: string | undefined): "ready" | "mis } const serverCommandId = (tag: string): CommandId => - CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`); + CommandId.make(`server:${tag}:${crypto.randomUUID()}`); const make = Effect.gen(function* () { const orchestrationEngine = yield* OrchestrationEngineService; @@ -69,6 +70,7 @@ const make = Effect.gen(function* () { const checkpointStore = yield* CheckpointStore; const receiptBus = yield* RuntimeReceiptBus; const workspaceEntries = yield* WorkspaceEntries; + const gitStatusBroadcaster = yield* GitStatusBroadcaster; const appendRevertFailureActivity = (input: { readonly threadId: ThreadId; @@ -81,7 +83,7 @@ const make = Effect.gen(function* () { commandId: serverCommandId("checkpoint-revert-failure"), threadId: input.threadId, activity: { - id: EventId.makeUnsafe(crypto.randomUUID()), + id: EventId.make(crypto.randomUUID()), tone: "error", kind: "checkpoint.revert.failed", summary: "Checkpoint revert failed", @@ -106,7 +108,7 @@ const make = Effect.gen(function* () { commandId: serverCommandId("checkpoint-capture-failure"), threadId: input.threadId, activity: { - id: EventId.makeUnsafe(crypto.randomUUID()), + id: EventId.make(crypto.randomUUID()), tone: "error", kind: "checkpoint.capture.failed", summary: "Checkpoint capture failed", @@ -119,7 +121,7 @@ const make = Effect.gen(function* () { createdAt: input.createdAt, }); - const resolveSessionRuntimeForThread = Effect.fnUntraced(function* ( + const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* ( threadId: ThreadId, ): Effect.fn.Return> { const readModel = yield* orchestrationEngine.getReadModel(); @@ -153,7 +155,7 @@ const make = Effect.gen(function* () { // active provider session CWD and falling back to the thread/project config. // Returns undefined when no CWD can be determined or the workspace is not // a git repository. - const resolveCheckpointCwd = Effect.fnUntraced(function* (input: { + const resolveCheckpointCwd = Effect.fn("resolveCheckpointCwd")(function* (input: { readonly threadId: ThreadId; readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null }; readonly projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>; @@ -188,7 +190,7 @@ const make = Effect.gen(function* () { // Shared tail for both capture paths: creates the git checkpoint ref, diffs // it against the previous turn, then dispatches the domain events to update // the orchestration read model. - const captureAndDispatchCheckpoint = Effect.fnUntraced(function* (input: { + const captureAndDispatchCheckpoint = Effect.fn("captureAndDispatchCheckpoint")(function* (input: { readonly threadId: ThreadId; readonly turnId: TurnId; readonly thread: { @@ -268,7 +270,7 @@ const make = Effect.gen(function* () { input.thread.messages .toReversed() .find((entry) => entry.role === "assistant" && entry.turnId === input.turnId)?.id ?? - MessageId.makeUnsafe(`assistant:${input.turnId}`); + MessageId.make(`assistant:${input.turnId}`); yield* orchestrationEngine.dispatch({ type: "thread.turn.diff.complete", @@ -305,7 +307,7 @@ const make = Effect.gen(function* () { commandId: serverCommandId("checkpoint-captured-activity"), threadId: input.threadId, activity: { - id: EventId.makeUnsafe(crypto.randomUUID()), + id: EventId.make(crypto.randomUUID()), tone: "info", kind: "checkpoint.captured", summary: "Checkpoint captured", @@ -321,70 +323,70 @@ const make = Effect.gen(function* () { }); // Captures a real git checkpoint when a turn completes via a runtime event. - const captureCheckpointFromTurnCompletion = Effect.fnUntraced(function* ( - event: Extract, - ) { - const turnId = toTurnId(event.turnId); - if (!turnId) { - return; - } + const captureCheckpointFromTurnCompletion = Effect.fn("captureCheckpointFromTurnCompletion")( + function* (event: Extract) { + const turnId = toTurnId(event.turnId); + if (!turnId) { + return; + } - const readModel = yield* orchestrationEngine.getReadModel(); - const thread = readModel.threads.find((entry) => entry.id === event.threadId); - if (!thread) { - return; - } + const readModel = yield* orchestrationEngine.getReadModel(); + const thread = readModel.threads.find((entry) => entry.id === event.threadId); + if (!thread) { + return; + } - // When a primary turn is active, only that turn may produce completion checkpoints. - if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) { - return; - } + // When a primary turn is active, only that turn may produce completion checkpoints. + if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) { + return; + } - // Only skip if a real (non-placeholder) checkpoint already exists for this turn. - // ProviderRuntimeIngestion may insert placeholder entries with status "missing" - // before this reactor runs; those must not prevent real git capture. - if ( - thread.checkpoints.some( - (checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing", - ) - ) { - return; - } + // Only skip if a real (non-placeholder) checkpoint already exists for this turn. + // ProviderRuntimeIngestion may insert placeholder entries with status "missing" + // before this reactor runs; those must not prevent real git capture. + if ( + thread.checkpoints.some( + (checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing", + ) + ) { + return; + } - const checkpointCwd = yield* resolveCheckpointCwd({ - threadId: thread.id, - thread, - projects: readModel.projects, - preferSessionRuntime: true, - }); - if (!checkpointCwd) { - return; - } + const checkpointCwd = yield* resolveCheckpointCwd({ + threadId: thread.id, + thread, + projects: readModel.projects, + preferSessionRuntime: true, + }); + if (!checkpointCwd) { + return; + } - // If a placeholder checkpoint exists for this turn, reuse its turn count - // instead of incrementing past it. - const existingPlaceholder = thread.checkpoints.find( - (checkpoint) => checkpoint.turnId === turnId && checkpoint.status === "missing", - ); - const currentTurnCount = thread.checkpoints.reduce( - (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount), - 0, - ); - const nextTurnCount = existingPlaceholder - ? existingPlaceholder.checkpointTurnCount - : currentTurnCount + 1; + // If a placeholder checkpoint exists for this turn, reuse its turn count + // instead of incrementing past it. + const existingPlaceholder = thread.checkpoints.find( + (checkpoint) => checkpoint.turnId === turnId && checkpoint.status === "missing", + ); + const currentTurnCount = thread.checkpoints.reduce( + (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount), + 0, + ); + const nextTurnCount = existingPlaceholder + ? existingPlaceholder.checkpointTurnCount + : currentTurnCount + 1; - yield* captureAndDispatchCheckpoint({ - threadId: thread.id, - turnId, - thread, - cwd: checkpointCwd, - turnCount: nextTurnCount, - status: checkpointStatusFromRuntime(event.payload.state), - assistantMessageId: undefined, - createdAt: event.createdAt, - }); - }); + yield* captureAndDispatchCheckpoint({ + threadId: thread.id, + turnId, + thread, + cwd: checkpointCwd, + turnCount: nextTurnCount, + status: checkpointStatusFromRuntime(event.payload.state), + assistantMessageId: undefined, + createdAt: event.createdAt, + }); + }, + ); // Captures a real git checkpoint when a placeholder checkpoint (status "missing") // is detected via a domain event. This replaces the placeholder with a real @@ -394,7 +396,7 @@ const make = Effect.gen(function* () { // events from the Codex runtime. This handler fires when the corresponding // domain event arrives, allowing the reactor to capture the actual filesystem // state into a git ref and dispatch a replacement checkpoint. - const captureCheckpointFromPlaceholder = Effect.fnUntraced(function* ( + const captureCheckpointFromPlaceholder = Effect.fn("captureCheckpointFromPlaceholder")(function* ( event: Extract, ) { const { threadId, turnId, checkpointTurnCount, status } = event.payload; @@ -448,57 +450,79 @@ const make = Effect.gen(function* () { }); }); - const ensurePreTurnBaselineFromTurnStart = Effect.fnUntraced(function* ( - event: Extract, - ) { - const turnId = toTurnId(event.turnId); - if (!turnId) { + const ensurePreTurnBaselineFromTurnStart = Effect.fn("ensurePreTurnBaselineFromTurnStart")( + function* (event: Extract) { + const turnId = toTurnId(event.turnId); + if (!turnId) { + return; + } + + const readModel = yield* orchestrationEngine.getReadModel(); + const thread = readModel.threads.find((entry) => entry.id === event.threadId); + if (!thread) { + return; + } + + const checkpointCwd = yield* resolveCheckpointCwd({ + threadId: thread.id, + thread, + projects: readModel.projects, + preferSessionRuntime: false, + }); + if (!checkpointCwd) { + return; + } + + const currentTurnCount = thread.checkpoints.reduce( + (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount), + 0, + ); + const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount); + const baselineExists = yield* checkpointStore.hasCheckpointRef({ + cwd: checkpointCwd, + checkpointRef: baselineCheckpointRef, + }); + if (baselineExists) { + return; + } + + yield* checkpointStore.captureCheckpoint({ + cwd: checkpointCwd, + checkpointRef: baselineCheckpointRef, + }); + yield* receiptBus.publish({ + type: "checkpoint.baseline.captured", + threadId: thread.id, + checkpointTurnCount: currentTurnCount, + checkpointRef: baselineCheckpointRef, + createdAt: event.createdAt, + }); + }, + ); + + const refreshLocalGitStatusFromTurnCompletion = Effect.fn( + "refreshLocalGitStatusFromTurnCompletion", + )(function* (event: Extract) { + const sessionRuntime = yield* resolveSessionRuntimeForThread(event.threadId); + if (Option.isNone(sessionRuntime)) { return; } - const readModel = yield* orchestrationEngine.getReadModel(); - const thread = readModel.threads.find((entry) => entry.id === event.threadId); - if (!thread) { - return; - } - - const checkpointCwd = yield* resolveCheckpointCwd({ - threadId: thread.id, - thread, - projects: readModel.projects, - preferSessionRuntime: false, - }); - if (!checkpointCwd) { - return; - } - - const currentTurnCount = thread.checkpoints.reduce( - (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount), - 0, + yield* gitStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe( + Effect.catch((error) => + Effect.logWarning("failed to refresh local git status after turn completion", { + threadId: event.threadId, + turnId: event.turnId ?? null, + cwd: sessionRuntime.value.cwd, + detail: error.message, + }), + ), ); - const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount); - const baselineExists = yield* checkpointStore.hasCheckpointRef({ - cwd: checkpointCwd, - checkpointRef: baselineCheckpointRef, - }); - if (baselineExists) { - return; - } - - yield* checkpointStore.captureCheckpoint({ - cwd: checkpointCwd, - checkpointRef: baselineCheckpointRef, - }); - yield* receiptBus.publish({ - type: "checkpoint.baseline.captured", - threadId: thread.id, - checkpointTurnCount: currentTurnCount, - checkpointRef: baselineCheckpointRef, - createdAt: event.createdAt, - }); }); - const ensurePreTurnBaselineFromDomainTurnStart = Effect.fnUntraced(function* ( + const ensurePreTurnBaselineFromDomainTurnStart = Effect.fn( + "ensurePreTurnBaselineFromDomainTurnStart", + )(function* ( event: Extract< OrchestrationEvent, { type: "thread.turn-start-requested" | "thread.message-sent" } @@ -557,7 +581,7 @@ const make = Effect.gen(function* () { }); }); - const handleRevertRequested = Effect.fnUntraced(function* ( + const handleRevertRequested = Effect.fn("handleRevertRequested")(function* ( event: Extract, ) { const now = new Date().toISOString(); @@ -685,7 +709,7 @@ const make = Effect.gen(function* () { ); }); - const processDomainEvent = Effect.fnUntraced(function* (event: OrchestrationEvent) { + const processDomainEvent = Effect.fn("processDomainEvent")(function* (event: OrchestrationEvent) { if (event.type === "thread.turn-start-requested" || event.type === "thread.message-sent") { yield* ensurePreTurnBaselineFromDomainTurnStart(event); return; @@ -724,7 +748,9 @@ const make = Effect.gen(function* () { } }); - const processRuntimeEvent = Effect.fnUntraced(function* (event: ProviderRuntimeEvent) { + const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* ( + event: ProviderRuntimeEvent, + ) { if (event.type === "turn.started") { yield* ensurePreTurnBaselineFromTurnStart(event); return; @@ -732,6 +758,7 @@ const make = Effect.gen(function* () { if (event.type === "turn.completed") { const turnId = toTurnId(event.turnId); + yield* refreshLocalGitStatusFromTurnCompletion(event); yield* captureCheckpointFromTurnCompletion(event).pipe( Effect.catch((error) => appendCaptureFailureActivity({ diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts index 6aa889991e..eaf66f3971 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts @@ -8,7 +8,7 @@ import { TurnId, type OrchestrationEvent, } from "@t3tools/contracts"; -import { Effect, Layer, ManagedRuntime, Queue, Stream } from "effect"; +import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect"; import { describe, expect, it } from "vitest"; import { PersistenceSqlError } from "../../persistence/Errors.ts"; @@ -19,29 +19,34 @@ import { OrchestrationEventStore, type OrchestrationEventStoreShape, } from "../../persistence/Services/OrchestrationEventStore.ts"; +import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts"; import { OrchestrationEngineLive } from "./OrchestrationEngine.ts"; import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts"; +import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts"; import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; import { OrchestrationProjectionPipeline, type OrchestrationProjectionPipelineShape, } from "../Services/ProjectionPipeline.ts"; +import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"; import { ServerConfig } from "../../config.ts"; import * as NodeServices from "@effect/platform-node/NodeServices"; -const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value); -const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value); -const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value); -const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value); +const asProjectId = (value: string): ProjectId => ProjectId.make(value); +const asMessageId = (value: string): MessageId => MessageId.make(value); +const asTurnId = (value: string): TurnId => TurnId.make(value); +const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(value); async function createOrchestrationSystem() { const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), { prefix: "t3-orchestration-engine-test-", }); const orchestrationLayer = OrchestrationEngineLive.pipe( + Layer.provide(OrchestrationProjectionSnapshotQueryLive), Layer.provide(OrchestrationProjectionPipelineLive), Layer.provide(OrchestrationEventStoreLive), Layer.provide(OrchestrationCommandReceiptRepositoryLive), + Layer.provide(RepositoryIdentityResolverLive), Layer.provide(SqlitePersistenceMemory), Layer.provideMerge(ServerConfigLayer), Layer.provideMerge(NodeServices.layer), @@ -59,7 +64,117 @@ function now() { return new Date().toISOString(); } +const hasMetricSnapshot = ( + snapshots: ReadonlyArray, + id: string, + attributes: Readonly>, +) => + snapshots.some( + (snapshot) => + snapshot.id === id && + Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value), + ); + describe("OrchestrationEngine", () => { + it("bootstraps the in-memory read model from persisted projections", async () => { + const failOnHistoricalReplayStore: OrchestrationEventStoreShape = { + append: () => + Effect.fail( + new PersistenceSqlError({ + operation: "test.append", + detail: "append should not be called during bootstrap", + }), + ), + readFromSequence: () => Stream.empty, + readAll: () => + Stream.fail( + new PersistenceSqlError({ + operation: "test.readAll", + detail: "historical replay should not be used during bootstrap", + }), + ), + }; + + const projectionSnapshot = { + snapshotSequence: 7, + updatedAt: "2026-03-03T00:00:04.000Z", + projects: [ + { + id: asProjectId("project-bootstrap"), + title: "Bootstrap Project", + workspaceRoot: "/tmp/project-bootstrap", + defaultModelSelection: { + provider: "codex" as const, + model: "gpt-5-codex", + }, + scripts: [], + createdAt: "2026-03-03T00:00:00.000Z", + updatedAt: "2026-03-03T00:00:01.000Z", + deletedAt: null, + }, + ], + threads: [ + { + id: ThreadId.make("thread-bootstrap"), + projectId: asProjectId("project-bootstrap"), + title: "Bootstrap Thread", + modelSelection: { + provider: "codex" as const, + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access" as const, + branch: null, + worktreePath: null, + latestTurn: null, + createdAt: "2026-03-03T00:00:02.000Z", + updatedAt: "2026-03-03T00:00:03.000Z", + archivedAt: null, + deletedAt: null, + messages: [], + proposedPlans: [], + activities: [], + checkpoints: [], + session: null, + }, + ], + }; + + const layer = OrchestrationEngineLive.pipe( + Layer.provide( + Layer.succeed(ProjectionSnapshotQuery, { + getSnapshot: () => Effect.succeed(projectionSnapshot), + getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }), + getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()), + getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()), + getThreadCheckpointContext: () => Effect.succeed(Option.none()), + }), + ), + Layer.provide( + Layer.succeed(OrchestrationProjectionPipeline, { + bootstrap: Effect.void, + projectEvent: () => Effect.void, + } satisfies OrchestrationProjectionPipelineShape), + ), + Layer.provide(Layer.succeed(OrchestrationEventStore, failOnHistoricalReplayStore)), + Layer.provide(OrchestrationCommandReceiptRepositoryLive), + Layer.provide(SqlitePersistenceMemory), + ); + + const runtime = ManagedRuntime.make(layer); + + const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService)); + const readModel = await runtime.runPromise(engine.getReadModel()); + + expect(readModel.snapshotSequence).toBe(7); + expect(readModel.projects).toHaveLength(1); + expect(readModel.projects[0]?.title).toBe("Bootstrap Project"); + expect(readModel.threads).toHaveLength(1); + expect(readModel.threads[0]?.title).toBe("Bootstrap Thread"); + + await runtime.dispose(); + }); + it("returns deterministic read models for repeated reads", async () => { const createdAt = now(); const system = await createOrchestrationSystem(); @@ -68,7 +183,7 @@ describe("OrchestrationEngine", () => { await system.run( engine.dispatch({ type: "project.create", - commandId: CommandId.makeUnsafe("cmd-project-1-create"), + commandId: CommandId.make("cmd-project-1-create"), projectId: asProjectId("project-1"), title: "Project 1", workspaceRoot: "/tmp/project-1", @@ -82,8 +197,8 @@ describe("OrchestrationEngine", () => { await system.run( engine.dispatch({ type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-thread-1-create"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-thread-1-create"), + threadId: ThreadId.make("thread-1"), projectId: asProjectId("project-1"), title: "Thread", modelSelection: { @@ -100,8 +215,8 @@ describe("OrchestrationEngine", () => { await system.run( engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-1"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-1"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("msg-1"), role: "user", @@ -128,7 +243,7 @@ describe("OrchestrationEngine", () => { await system.run( engine.dispatch({ type: "project.create", - commandId: CommandId.makeUnsafe("cmd-project-archive-create"), + commandId: CommandId.make("cmd-project-archive-create"), projectId: asProjectId("project-archive"), title: "Project Archive", workspaceRoot: "/tmp/project-archive", @@ -142,8 +257,8 @@ describe("OrchestrationEngine", () => { await system.run( engine.dispatch({ type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-thread-archive-create"), - threadId: ThreadId.makeUnsafe("thread-archive"), + commandId: CommandId.make("cmd-thread-archive-create"), + threadId: ThreadId.make("thread-archive"), projectId: asProjectId("project-archive"), title: "Archive me", modelSelection: { @@ -161,8 +276,8 @@ describe("OrchestrationEngine", () => { await system.run( engine.dispatch({ type: "thread.archive", - commandId: CommandId.makeUnsafe("cmd-thread-archive"), - threadId: ThreadId.makeUnsafe("thread-archive"), + commandId: CommandId.make("cmd-thread-archive"), + threadId: ThreadId.make("thread-archive"), }), ); expect( @@ -174,8 +289,8 @@ describe("OrchestrationEngine", () => { await system.run( engine.dispatch({ type: "thread.unarchive", - commandId: CommandId.makeUnsafe("cmd-thread-unarchive"), - threadId: ThreadId.makeUnsafe("thread-archive"), + commandId: CommandId.make("cmd-thread-unarchive"), + threadId: ThreadId.make("thread-archive"), }), ); expect( @@ -195,7 +310,7 @@ describe("OrchestrationEngine", () => { await system.run( engine.dispatch({ type: "project.create", - commandId: CommandId.makeUnsafe("cmd-project-replay-create"), + commandId: CommandId.make("cmd-project-replay-create"), projectId: asProjectId("project-replay"), title: "Replay Project", workspaceRoot: "/tmp/project-replay", @@ -209,8 +324,8 @@ describe("OrchestrationEngine", () => { await system.run( engine.dispatch({ type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-thread-replay-create"), - threadId: ThreadId.makeUnsafe("thread-replay"), + commandId: CommandId.make("cmd-thread-replay-create"), + threadId: ThreadId.make("thread-replay"), projectId: asProjectId("project-replay"), title: "replay", modelSelection: { @@ -227,8 +342,8 @@ describe("OrchestrationEngine", () => { await system.run( engine.dispatch({ type: "thread.delete", - commandId: CommandId.makeUnsafe("cmd-thread-replay-delete"), - threadId: ThreadId.makeUnsafe("thread-replay"), + commandId: CommandId.make("cmd-thread-replay-delete"), + threadId: ThreadId.make("thread-replay"), }), ); @@ -253,7 +368,7 @@ describe("OrchestrationEngine", () => { await system.run( engine.dispatch({ type: "project.create", - commandId: CommandId.makeUnsafe("cmd-project-stream-create"), + commandId: CommandId.make("cmd-project-stream-create"), projectId: asProjectId("project-stream"), title: "Stream Project", workspaceRoot: "/tmp/project-stream", @@ -277,8 +392,8 @@ describe("OrchestrationEngine", () => { yield* Effect.sleep("10 millis"); yield* engine.dispatch({ type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-stream-thread-create"), - threadId: ThreadId.makeUnsafe("thread-stream"), + commandId: CommandId.make("cmd-stream-thread-create"), + threadId: ThreadId.make("thread-stream"), projectId: asProjectId("project-stream"), title: "domain-stream", modelSelection: { @@ -293,8 +408,8 @@ describe("OrchestrationEngine", () => { }); yield* engine.dispatch({ type: "thread.meta.update", - commandId: CommandId.makeUnsafe("cmd-stream-thread-update"), - threadId: ThreadId.makeUnsafe("thread-stream"), + commandId: CommandId.make("cmd-stream-thread-update"), + threadId: ThreadId.make("thread-stream"), title: "domain-stream-updated", }); eventTypes.push((yield* Queue.take(eventQueue)).type); @@ -306,6 +421,95 @@ describe("OrchestrationEngine", () => { await system.dispose(); }); + it("records command ack duration using the first committed event type", async () => { + const system = await createOrchestrationSystem(); + const { engine } = system; + const createdAt = now(); + + await system.run( + engine.dispatch({ + type: "project.create", + commandId: CommandId.make("cmd-project-ack-create"), + projectId: asProjectId("project-ack"), + title: "Ack Project", + workspaceRoot: "/tmp/project-ack", + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + createdAt, + }), + ); + + await system.run( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.make("cmd-thread-ack-create"), + threadId: ThreadId.make("thread-ack"), + projectId: asProjectId("project-ack"), + title: "Ack Thread", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt, + }), + ); + + const snapshots = await system.run(Metric.snapshot); + expect( + hasMetricSnapshot(snapshots, "t3_orchestration_command_ack_duration", { + commandType: "thread.create", + aggregateKind: "thread", + ackEventType: "thread.created", + }), + ).toBe(true); + + await system.dispose(); + }); + + it("records failed command dispatches as metric failures", async () => { + const system = await createOrchestrationSystem(); + const { engine } = system; + const createdAt = now(); + + await expect( + system.run( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.make("cmd-thread-missing-project"), + threadId: ThreadId.make("thread-missing-project"), + projectId: asProjectId("project-missing"), + title: "Missing Project Thread", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt, + }), + ), + ).rejects.toThrow("does not exist"); + + const snapshots = await system.run(Metric.snapshot); + expect( + hasMetricSnapshot(snapshots, "t3_orchestration_commands_total", { + commandType: "thread.create", + aggregateKind: "thread", + outcome: "failure", + }), + ).toBe(true); + + await system.dispose(); + }); + it("stores completed checkpoint summaries even when no files changed", async () => { const system = await createOrchestrationSystem(); const { engine } = system; @@ -314,7 +518,7 @@ describe("OrchestrationEngine", () => { await system.run( engine.dispatch({ type: "project.create", - commandId: CommandId.makeUnsafe("cmd-project-turn-diff-create"), + commandId: CommandId.make("cmd-project-turn-diff-create"), projectId: asProjectId("project-turn-diff"), title: "Turn Diff Project", workspaceRoot: "/tmp/project-turn-diff", @@ -328,8 +532,8 @@ describe("OrchestrationEngine", () => { await system.run( engine.dispatch({ type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-thread-turn-diff-create"), - threadId: ThreadId.makeUnsafe("thread-turn-diff"), + commandId: CommandId.make("cmd-thread-turn-diff-create"), + threadId: ThreadId.make("thread-turn-diff"), projectId: asProjectId("project-turn-diff"), title: "Turn diff thread", modelSelection: { @@ -346,8 +550,8 @@ describe("OrchestrationEngine", () => { await system.run( engine.dispatch({ type: "thread.turn.diff.complete", - commandId: CommandId.makeUnsafe("cmd-turn-diff-complete"), - threadId: ThreadId.makeUnsafe("thread-turn-diff"), + commandId: CommandId.make("cmd-turn-diff-complete"), + threadId: ThreadId.make("thread-turn-diff"), turnId: asTurnId("turn-1"), completedAt: createdAt, checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"), @@ -386,7 +590,7 @@ describe("OrchestrationEngine", () => { const flakyStore: OrchestrationEventStoreShape = { append(event) { - if (shouldFailFirstAppend && event.commandId === CommandId.makeUnsafe("cmd-flaky-1")) { + if (shouldFailFirstAppend && event.commandId === CommandId.make("cmd-flaky-1")) { shouldFailFirstAppend = false; return Effect.fail( new PersistenceSqlError({ @@ -417,9 +621,11 @@ describe("OrchestrationEngine", () => { const runtime = ManagedRuntime.make( OrchestrationEngineLive.pipe( + Layer.provide(OrchestrationProjectionSnapshotQueryLive), Layer.provide(OrchestrationProjectionPipelineLive), Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)), Layer.provide(OrchestrationCommandReceiptRepositoryLive), + Layer.provide(RepositoryIdentityResolverLive), Layer.provide(SqlitePersistenceMemory), Layer.provideMerge(ServerConfigLayer), Layer.provideMerge(NodeServices.layer), @@ -431,7 +637,7 @@ describe("OrchestrationEngine", () => { await runtime.runPromise( engine.dispatch({ type: "project.create", - commandId: CommandId.makeUnsafe("cmd-project-flaky-create"), + commandId: CommandId.make("cmd-project-flaky-create"), projectId: asProjectId("project-flaky"), title: "Flaky Project", workspaceRoot: "/tmp/project-flaky", @@ -447,8 +653,8 @@ describe("OrchestrationEngine", () => { runtime.runPromise( engine.dispatch({ type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-flaky-1"), - threadId: ThreadId.makeUnsafe("thread-flaky-fail"), + commandId: CommandId.make("cmd-flaky-1"), + threadId: ThreadId.make("thread-flaky-fail"), projectId: asProjectId("project-flaky"), title: "flaky-fail", modelSelection: { @@ -467,8 +673,8 @@ describe("OrchestrationEngine", () => { const result = await runtime.runPromise( engine.dispatch({ type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-flaky-2"), - threadId: ThreadId.makeUnsafe("thread-flaky-ok"), + commandId: CommandId.make("cmd-flaky-2"), + threadId: ThreadId.make("thread-flaky-ok"), projectId: asProjectId("project-flaky"), title: "flaky-ok", modelSelection: { @@ -495,7 +701,7 @@ describe("OrchestrationEngine", () => { projectEvent: (event) => { if ( shouldFailRequestedProjection && - event.commandId === CommandId.makeUnsafe("cmd-turn-start-atomic") && + event.commandId === CommandId.make("cmd-turn-start-atomic") && event.type === "thread.turn-start-requested" ) { shouldFailRequestedProjection = false; @@ -512,9 +718,11 @@ describe("OrchestrationEngine", () => { const runtime = ManagedRuntime.make( OrchestrationEngineLive.pipe( + Layer.provide(OrchestrationProjectionSnapshotQueryLive), Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)), Layer.provide(OrchestrationEventStoreLive), Layer.provide(OrchestrationCommandReceiptRepositoryLive), + Layer.provide(RepositoryIdentityResolverLive), Layer.provide(SqlitePersistenceMemory), ), ); @@ -524,7 +732,7 @@ describe("OrchestrationEngine", () => { await runtime.runPromise( engine.dispatch({ type: "project.create", - commandId: CommandId.makeUnsafe("cmd-project-atomic-create"), + commandId: CommandId.make("cmd-project-atomic-create"), projectId: asProjectId("project-atomic"), title: "Atomic Project", workspaceRoot: "/tmp/project-atomic", @@ -538,8 +746,8 @@ describe("OrchestrationEngine", () => { await runtime.runPromise( engine.dispatch({ type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-thread-atomic-create"), - threadId: ThreadId.makeUnsafe("thread-atomic"), + commandId: CommandId.make("cmd-thread-atomic-create"), + threadId: ThreadId.make("thread-atomic"), projectId: asProjectId("project-atomic"), title: "atomic", modelSelection: { @@ -556,8 +764,8 @@ describe("OrchestrationEngine", () => { const turnStartCommand = { type: "thread.turn.start" as const, - commandId: CommandId.makeUnsafe("cmd-turn-start-atomic"), - threadId: ThreadId.makeUnsafe("thread-atomic"), + commandId: CommandId.make("cmd-turn-start-atomic"), + threadId: ThreadId.make("thread-atomic"), message: { messageId: asMessageId("msg-atomic-1"), role: "user" as const, @@ -637,7 +845,7 @@ describe("OrchestrationEngine", () => { projectEvent: (event) => { if ( shouldFailProjection && - event.commandId === CommandId.makeUnsafe("cmd-thread-meta-sync-fail") + event.commandId === CommandId.make("cmd-thread-meta-sync-fail") ) { shouldFailProjection = false; return Effect.fail( @@ -653,9 +861,11 @@ describe("OrchestrationEngine", () => { const runtime = ManagedRuntime.make( OrchestrationEngineLive.pipe( + Layer.provide(OrchestrationProjectionSnapshotQueryLive), Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)), Layer.provide(Layer.succeed(OrchestrationEventStore, nonTransactionalStore)), Layer.provide(OrchestrationCommandReceiptRepositoryLive), + Layer.provide(RepositoryIdentityResolverLive), Layer.provide(SqlitePersistenceMemory), ), ); @@ -665,7 +875,7 @@ describe("OrchestrationEngine", () => { await runtime.runPromise( engine.dispatch({ type: "project.create", - commandId: CommandId.makeUnsafe("cmd-project-sync-create"), + commandId: CommandId.make("cmd-project-sync-create"), projectId: asProjectId("project-sync"), title: "Sync Project", workspaceRoot: "/tmp/project-sync", @@ -679,8 +889,8 @@ describe("OrchestrationEngine", () => { await runtime.runPromise( engine.dispatch({ type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-thread-sync-create"), - threadId: ThreadId.makeUnsafe("thread-sync"), + commandId: CommandId.make("cmd-thread-sync-create"), + threadId: ThreadId.make("thread-sync"), projectId: asProjectId("project-sync"), title: "sync-before", modelSelection: { @@ -699,8 +909,8 @@ describe("OrchestrationEngine", () => { runtime.runPromise( engine.dispatch({ type: "thread.meta.update", - commandId: CommandId.makeUnsafe("cmd-thread-meta-sync-fail"), - threadId: ThreadId.makeUnsafe("thread-sync"), + commandId: CommandId.make("cmd-thread-meta-sync-fail"), + threadId: ThreadId.make("thread-sync"), title: "sync-after-failed-projection", }), ), @@ -724,8 +934,8 @@ describe("OrchestrationEngine", () => { system.run( engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-invariant-missing-thread"), - threadId: ThreadId.makeUnsafe("thread-missing"), + commandId: CommandId.make("cmd-invariant-missing-thread"), + threadId: ThreadId.make("thread-missing"), message: { messageId: asMessageId("msg-missing"), role: "user", @@ -750,7 +960,7 @@ describe("OrchestrationEngine", () => { await system.run( engine.dispatch({ type: "project.create", - commandId: CommandId.makeUnsafe("cmd-project-duplicate-create"), + commandId: CommandId.make("cmd-project-duplicate-create"), projectId: asProjectId("project-duplicate"), title: "Duplicate Project", workspaceRoot: "/tmp/project-duplicate", @@ -765,8 +975,8 @@ describe("OrchestrationEngine", () => { await system.run( engine.dispatch({ type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-thread-duplicate-1"), - threadId: ThreadId.makeUnsafe("thread-duplicate"), + commandId: CommandId.make("cmd-thread-duplicate-1"), + threadId: ThreadId.make("thread-duplicate"), projectId: asProjectId("project-duplicate"), title: "duplicate", modelSelection: { @@ -785,8 +995,8 @@ describe("OrchestrationEngine", () => { system.run( engine.dispatch({ type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-thread-duplicate-2"), - threadId: ThreadId.makeUnsafe("thread-duplicate"), + commandId: CommandId.make("cmd-thread-duplicate-2"), + threadId: ThreadId.make("thread-duplicate"), projectId: asProjectId("project-duplicate"), title: "duplicate", modelSelection: { diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts index 69b28b9d3c..ddd1718faf 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts @@ -5,9 +5,28 @@ import type { ThreadId, } from "@t3tools/contracts"; import { OrchestrationCommand } from "@t3tools/contracts"; -import { Deferred, Effect, Layer, Option, PubSub, Queue, Schema, Stream } from "effect"; +import { + Cause, + Deferred, + Duration, + Effect, + Exit, + Layer, + Metric, + Option, + PubSub, + Queue, + Schema, + Stream, +} from "effect"; import * as SqlClient from "effect/unstable/sql/SqlClient"; +import { + metricAttributes, + orchestrationCommandAckDuration, + orchestrationCommandsTotal, + orchestrationCommandDuration, +} from "../../observability/Metrics.ts"; import { toPersistenceSqlError } from "../../persistence/Errors.ts"; import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts"; import { OrchestrationCommandReceiptRepository } from "../../persistence/Services/OrchestrationCommandReceipts.ts"; @@ -19,6 +38,7 @@ import { import { decideOrchestrationCommand } from "../decider.ts"; import { createEmptyReadModel, projectEvent } from "../projector.ts"; import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts"; +import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"; import { OrchestrationEngineService, type OrchestrationEngineShape, @@ -27,6 +47,7 @@ import { interface CommandEnvelope { command: OrchestrationCommand; result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>; + startedAtMs: number; } function commandToAggregateRef(command: OrchestrationCommand): { @@ -54,6 +75,7 @@ const makeOrchestrationEngine = Effect.gen(function* () { const eventStore = yield* OrchestrationEventStore; const commandReceiptRepository = yield* OrchestrationCommandReceiptRepository; const projectionPipeline = yield* OrchestrationProjectionPipeline; + const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; let readModel = createEmptyReadModel(new Date().toISOString()); @@ -62,6 +84,12 @@ const makeOrchestrationEngine = Effect.gen(function* () { const processEnvelope = (envelope: CommandEnvelope): Effect.Effect => { const dispatchStartSequence = readModel.snapshotSequence; + const processingStartedAtMs = Date.now(); + const aggregateRef = commandToAggregateRef(envelope.command); + const baseMetricAttributes = { + commandType: envelope.command.type, + aggregateKind: aggregateRef.aggregateKind, + } as const; const reconcileReadModelAfterDispatchFailure = Effect.gen(function* () { const persistedEvents = yield* Stream.runCollect( eventStore.readFromSequence(dispatchStartSequence), @@ -81,113 +109,160 @@ const makeOrchestrationEngine = Effect.gen(function* () { } }); - return Effect.gen(function* () { - const existingReceipt = yield* commandReceiptRepository.getByCommandId({ - commandId: envelope.command.commandId, - }); - if (Option.isSome(existingReceipt)) { - if (existingReceipt.value.status === "accepted") { - yield* Deferred.succeed(envelope.result, { - sequence: existingReceipt.value.resultSequence, - }); - return; - } - yield* Deferred.fail( - envelope.result, - new OrchestrationCommandPreviouslyRejectedError({ + return Effect.exit( + Effect.gen(function* () { + yield* Effect.annotateCurrentSpan({ + "orchestration.command_id": envelope.command.commandId, + "orchestration.command_type": envelope.command.type, + "orchestration.aggregate_kind": aggregateRef.aggregateKind, + "orchestration.aggregate_id": aggregateRef.aggregateId, + }); + + const existingReceipt = yield* commandReceiptRepository.getByCommandId({ + commandId: envelope.command.commandId, + }); + if (Option.isSome(existingReceipt)) { + if (existingReceipt.value.status === "accepted") { + return { + sequence: existingReceipt.value.resultSequence, + }; + } + return yield* new OrchestrationCommandPreviouslyRejectedError({ commandId: envelope.command.commandId, detail: existingReceipt.value.error ?? "Previously rejected.", - }), - ); - return; - } + }); + } - const eventBase = yield* decideOrchestrationCommand({ - command: envelope.command, - readModel, - }); - const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase]; - const committedCommand = yield* sql - .withTransaction( - Effect.gen(function* () { - const committedEvents: OrchestrationEvent[] = []; - let nextReadModel = readModel; + const eventBase = yield* decideOrchestrationCommand({ + command: envelope.command, + readModel, + }); + const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase]; + const committedCommand = yield* sql + .withTransaction( + Effect.gen(function* () { + const committedEvents: OrchestrationEvent[] = []; + let nextReadModel = readModel; - for (const nextEvent of eventBases) { - const savedEvent = yield* eventStore.append(nextEvent); - nextReadModel = yield* projectEvent(nextReadModel, savedEvent); - yield* projectionPipeline.projectEvent(savedEvent); - committedEvents.push(savedEvent); - } + for (const nextEvent of eventBases) { + const savedEvent = yield* eventStore.append(nextEvent); + nextReadModel = yield* projectEvent(nextReadModel, savedEvent); + yield* projectionPipeline.projectEvent(savedEvent); + committedEvents.push(savedEvent); + } - const lastSavedEvent = committedEvents.at(-1) ?? null; - if (lastSavedEvent === null) { - return yield* new OrchestrationCommandInvariantError({ - commandType: envelope.command.type, - detail: "Command produced no events.", + const lastSavedEvent = committedEvents.at(-1) ?? null; + if (lastSavedEvent === null) { + return yield* new OrchestrationCommandInvariantError({ + commandType: envelope.command.type, + detail: "Command produced no events.", + }); + } + + yield* commandReceiptRepository.upsert({ + commandId: envelope.command.commandId, + aggregateKind: lastSavedEvent.aggregateKind, + aggregateId: lastSavedEvent.aggregateId, + acceptedAt: lastSavedEvent.occurredAt, + resultSequence: lastSavedEvent.sequence, + status: "accepted", + error: null, }); - } - yield* commandReceiptRepository.upsert({ - commandId: envelope.command.commandId, - aggregateKind: lastSavedEvent.aggregateKind, - aggregateId: lastSavedEvent.aggregateId, - acceptedAt: lastSavedEvent.occurredAt, - resultSequence: lastSavedEvent.sequence, - status: "accepted", - error: null, - }); - - return { - committedEvents, - lastSequence: lastSavedEvent.sequence, - nextReadModel, - } as const; - }), - ) - .pipe( - Effect.catchTag("SqlError", (sqlError) => - Effect.fail( - toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError), - ), - ), - ); - - readModel = committedCommand.nextReadModel; - for (const event of committedCommand.committedEvents) { - yield* PubSub.publish(eventPubSub, event); - } - yield* Deferred.succeed(envelope.result, { sequence: committedCommand.lastSequence }); - }).pipe( - Effect.catch((error) => - Effect.gen(function* () { - yield* reconcileReadModelAfterDispatchFailure.pipe( - Effect.catch(() => - Effect.logWarning( - "failed to reconcile orchestration read model after dispatch failure", - ).pipe( - Effect.annotateLogs({ - commandId: envelope.command.commandId, - snapshotSequence: readModel.snapshotSequence, - }), + return { + committedEvents, + lastSequence: lastSavedEvent.sequence, + nextReadModel, + } as const; + }), + ) + .pipe( + Effect.catchTag("SqlError", (sqlError) => + Effect.fail( + toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError), ), ), ); - if (Schema.is(OrchestrationCommandInvariantError)(error)) { - const aggregateRef = commandToAggregateRef(envelope.command); - yield* commandReceiptRepository - .upsert({ - commandId: envelope.command.commandId, - aggregateKind: aggregateRef.aggregateKind, - aggregateId: aggregateRef.aggregateId, - acceptedAt: new Date().toISOString(), - resultSequence: readModel.snapshotSequence, - status: "rejected", - error: error.message, - }) - .pipe(Effect.catch(() => Effect.void)); + readModel = committedCommand.nextReadModel; + for (const [index, event] of committedCommand.committedEvents.entries()) { + yield* PubSub.publish(eventPubSub, event); + if (index === 0) { + yield* Metric.update( + Metric.withAttributes( + orchestrationCommandAckDuration, + metricAttributes({ + ...baseMetricAttributes, + ackEventType: event.type, + }), + ), + Duration.millis(Math.max(0, Date.now() - envelope.startedAtMs)), + ); } + } + return { sequence: committedCommand.lastSequence }; + }).pipe(Effect.withSpan(`orchestration.command.${envelope.command.type}`)), + ).pipe( + Effect.flatMap((exit) => + Effect.gen(function* () { + const outcome = Exit.isSuccess(exit) + ? "success" + : Cause.hasInterruptsOnly(exit.cause) + ? "interrupt" + : "failure"; + yield* Metric.update( + Metric.withAttributes( + orchestrationCommandDuration, + metricAttributes(baseMetricAttributes), + ), + Duration.millis(Math.max(0, Date.now() - processingStartedAtMs)), + ); + yield* Metric.update( + Metric.withAttributes( + orchestrationCommandsTotal, + metricAttributes({ + ...baseMetricAttributes, + outcome, + }), + ), + 1, + ); + + if (Exit.isSuccess(exit)) { + yield* Deferred.succeed(envelope.result, exit.value); + return; + } + + const error = Cause.squash(exit.cause) as OrchestrationDispatchError; + if (!Schema.is(OrchestrationCommandPreviouslyRejectedError)(error)) { + yield* reconcileReadModelAfterDispatchFailure.pipe( + Effect.catch(() => + Effect.logWarning( + "failed to reconcile orchestration read model after dispatch failure", + ).pipe( + Effect.annotateLogs({ + commandId: envelope.command.commandId, + snapshotSequence: readModel.snapshotSequence, + }), + ), + ), + ); + + if (Schema.is(OrchestrationCommandInvariantError)(error)) { + yield* commandReceiptRepository + .upsert({ + commandId: envelope.command.commandId, + aggregateKind: aggregateRef.aggregateKind, + aggregateId: aggregateRef.aggregateId, + acceptedAt: new Date().toISOString(), + resultSequence: readModel.snapshotSequence, + status: "rejected", + error: error.message, + }) + .pipe(Effect.catch(() => Effect.void)); + } + } + yield* Deferred.fail(envelope.result, error); }), ), @@ -195,17 +270,11 @@ const makeOrchestrationEngine = Effect.gen(function* () { }; yield* projectionPipeline.bootstrap; - - // bootstrap in-memory read model from event store - yield* Stream.runForEach(eventStore.readAll(), (event) => - Effect.gen(function* () { - readModel = yield* projectEvent(readModel, event); - }), - ); + readModel = yield* projectionSnapshotQuery.getSnapshot(); 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 }), ); @@ -218,7 +287,7 @@ const makeOrchestrationEngine = Effect.gen(function* () { const dispatch: OrchestrationEngineShape["dispatch"] = (command) => Effect.gen(function* () { const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>(); - yield* Queue.offer(commandQueue, { command, result }); + yield* Queue.offer(commandQueue, { command, result, startedAtMs: Date.now() }); return yield* Deferred.await(result); }); diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts index 77b5d4d619..0796cb4905 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts @@ -20,11 +20,13 @@ import { SqlitePersistenceMemory, } from "../../persistence/Layers/Sqlite.ts"; import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts"; +import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts"; import { OrchestrationEngineLive } from "./OrchestrationEngine.ts"; import { ORCHESTRATION_PROJECTOR_NAMES, OrchestrationProjectionPipelineLive, } from "./ProjectionPipeline.ts"; +import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts"; import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts"; import { ServerConfig } from "../../config.ts"; @@ -56,16 +58,16 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* eventStore.append({ type: "project.created", - eventId: EventId.makeUnsafe("evt-1"), + eventId: EventId.make("evt-1"), aggregateKind: "project", - aggregateId: ProjectId.makeUnsafe("project-1"), + aggregateId: ProjectId.make("project-1"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-1"), + commandId: CommandId.make("cmd-1"), causationEventId: null, - correlationId: CommandId.makeUnsafe("cmd-1"), + correlationId: CommandId.make("cmd-1"), metadata: {}, payload: { - projectId: ProjectId.makeUnsafe("project-1"), + projectId: ProjectId.make("project-1"), title: "Project 1", workspaceRoot: "/tmp/project-1", defaultModelSelection: null, @@ -77,17 +79,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* eventStore.append({ type: "thread.created", - eventId: EventId.makeUnsafe("evt-2"), + eventId: EventId.make("evt-2"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-1"), + aggregateId: ThreadId.make("thread-1"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-2"), + commandId: CommandId.make("cmd-2"), causationEventId: null, - correlationId: CommandId.makeUnsafe("cmd-2"), + correlationId: CommandId.make("cmd-2"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-1"), - projectId: ProjectId.makeUnsafe("project-1"), + threadId: ThreadId.make("thread-1"), + projectId: ProjectId.make("project-1"), title: "Thread 1", modelSelection: { provider: "codex", @@ -103,17 +105,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* eventStore.append({ type: "thread.message-sent", - eventId: EventId.makeUnsafe("evt-3"), + eventId: EventId.make("evt-3"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-1"), + aggregateId: ThreadId.make("thread-1"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-3"), + commandId: CommandId.make("cmd-3"), causationEventId: null, - correlationId: CommandId.makeUnsafe("cmd-3"), + correlationId: CommandId.make("cmd-3"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-1"), - messageId: MessageId.makeUnsafe("message-1"), + threadId: ThreadId.make("thread-1"), + messageId: MessageId.make("message-1"), role: "assistant", text: "hello", turnId: null, @@ -181,17 +183,17 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-base-")))( yield* eventStore.append({ type: "thread.message-sent", - eventId: EventId.makeUnsafe("evt-attachments"), + eventId: EventId.make("evt-attachments"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-attachments"), + aggregateId: ThreadId.make("thread-attachments"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-attachments"), + commandId: CommandId.make("cmd-attachments"), causationEventId: null, - correlationId: CommandId.makeUnsafe("cmd-attachments"), + correlationId: CommandId.make("cmd-attachments"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-attachments"), - messageId: MessageId.makeUnsafe("message-attachments"), + threadId: ThreadId.make("thread-attachments"), + messageId: MessageId.make("message-attachments"), role: "user", text: "Inspect this", attachments: [ @@ -247,17 +249,17 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta yield* eventStore.append({ type: "thread.message-sent", - eventId: EventId.makeUnsafe("evt-attachments-safe"), + eventId: EventId.make("evt-attachments-safe"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-attachments-safe"), + aggregateId: ThreadId.make("thread-attachments-safe"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-attachments-safe"), + commandId: CommandId.make("cmd-attachments-safe"), causationEventId: null, - correlationId: CommandId.makeUnsafe("cmd-attachments-safe"), + correlationId: CommandId.make("cmd-attachments-safe"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-attachments-safe"), - messageId: MessageId.makeUnsafe("message-attachments-safe"), + threadId: ThreadId.make("thread-attachments-safe"), + messageId: MessageId.make("message-attachments-safe"), role: "user", text: "Inspect this", attachments: [ @@ -328,16 +330,16 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* eventStore.append({ type: "project.created", - eventId: EventId.makeUnsafe("evt-clear-attachments-1"), + eventId: EventId.make("evt-clear-attachments-1"), aggregateKind: "project", - aggregateId: ProjectId.makeUnsafe("project-clear-attachments"), + aggregateId: ProjectId.make("project-clear-attachments"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-clear-attachments-1"), + commandId: CommandId.make("cmd-clear-attachments-1"), causationEventId: null, - correlationId: CommandId.makeUnsafe("cmd-clear-attachments-1"), + correlationId: CommandId.make("cmd-clear-attachments-1"), metadata: {}, payload: { - projectId: ProjectId.makeUnsafe("project-clear-attachments"), + projectId: ProjectId.make("project-clear-attachments"), title: "Project Clear Attachments", workspaceRoot: "/tmp/project-clear-attachments", defaultModelSelection: null, @@ -349,17 +351,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* eventStore.append({ type: "thread.created", - eventId: EventId.makeUnsafe("evt-clear-attachments-2"), + eventId: EventId.make("evt-clear-attachments-2"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-clear-attachments"), + aggregateId: ThreadId.make("thread-clear-attachments"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-clear-attachments-2"), + commandId: CommandId.make("cmd-clear-attachments-2"), causationEventId: null, - correlationId: CommandId.makeUnsafe("cmd-clear-attachments-2"), + correlationId: CommandId.make("cmd-clear-attachments-2"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-clear-attachments"), - projectId: ProjectId.makeUnsafe("project-clear-attachments"), + threadId: ThreadId.make("thread-clear-attachments"), + projectId: ProjectId.make("project-clear-attachments"), title: "Thread Clear Attachments", modelSelection: { provider: "codex", @@ -375,17 +377,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* eventStore.append({ type: "thread.message-sent", - eventId: EventId.makeUnsafe("evt-clear-attachments-3"), + eventId: EventId.make("evt-clear-attachments-3"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-clear-attachments"), + aggregateId: ThreadId.make("thread-clear-attachments"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-clear-attachments-3"), + commandId: CommandId.make("cmd-clear-attachments-3"), causationEventId: null, - correlationId: CommandId.makeUnsafe("cmd-clear-attachments-3"), + correlationId: CommandId.make("cmd-clear-attachments-3"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-clear-attachments"), - messageId: MessageId.makeUnsafe("message-clear-attachments"), + threadId: ThreadId.make("thread-clear-attachments"), + messageId: MessageId.make("message-clear-attachments"), role: "user", text: "Has attachments", attachments: [ @@ -406,17 +408,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* eventStore.append({ type: "thread.message-sent", - eventId: EventId.makeUnsafe("evt-clear-attachments-4"), + eventId: EventId.make("evt-clear-attachments-4"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-clear-attachments"), + aggregateId: ThreadId.make("thread-clear-attachments"), occurredAt: later, - commandId: CommandId.makeUnsafe("cmd-clear-attachments-4"), + commandId: CommandId.make("cmd-clear-attachments-4"), causationEventId: null, - correlationId: CommandId.makeUnsafe("cmd-clear-attachments-4"), + correlationId: CommandId.make("cmd-clear-attachments-4"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-clear-attachments"), - messageId: MessageId.makeUnsafe("message-clear-attachments"), + threadId: ThreadId.make("thread-clear-attachments"), + messageId: MessageId.make("message-clear-attachments"), role: "user", text: "", attachments: [], @@ -456,16 +458,16 @@ it.layer( yield* eventStore.append({ type: "project.created", - eventId: EventId.makeUnsafe("evt-overwrite-1"), + eventId: EventId.make("evt-overwrite-1"), aggregateKind: "project", - aggregateId: ProjectId.makeUnsafe("project-overwrite"), + aggregateId: ProjectId.make("project-overwrite"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-overwrite-1"), + commandId: CommandId.make("cmd-overwrite-1"), causationEventId: null, - correlationId: CommandId.makeUnsafe("cmd-overwrite-1"), + correlationId: CommandId.make("cmd-overwrite-1"), metadata: {}, payload: { - projectId: ProjectId.makeUnsafe("project-overwrite"), + projectId: ProjectId.make("project-overwrite"), title: "Project Overwrite", workspaceRoot: "/tmp/project-overwrite", defaultModelSelection: null, @@ -477,17 +479,17 @@ it.layer( yield* eventStore.append({ type: "thread.created", - eventId: EventId.makeUnsafe("evt-overwrite-2"), + eventId: EventId.make("evt-overwrite-2"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-overwrite"), + aggregateId: ThreadId.make("thread-overwrite"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-overwrite-2"), + commandId: CommandId.make("cmd-overwrite-2"), causationEventId: null, - correlationId: CommandId.makeUnsafe("cmd-overwrite-2"), + correlationId: CommandId.make("cmd-overwrite-2"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-overwrite"), - projectId: ProjectId.makeUnsafe("project-overwrite"), + threadId: ThreadId.make("thread-overwrite"), + projectId: ProjectId.make("project-overwrite"), title: "Thread Overwrite", modelSelection: { provider: "codex", @@ -503,17 +505,17 @@ it.layer( yield* eventStore.append({ type: "thread.message-sent", - eventId: EventId.makeUnsafe("evt-overwrite-3"), + eventId: EventId.make("evt-overwrite-3"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-overwrite"), + aggregateId: ThreadId.make("thread-overwrite"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-overwrite-3"), + commandId: CommandId.make("cmd-overwrite-3"), causationEventId: null, - correlationId: CommandId.makeUnsafe("cmd-overwrite-3"), + correlationId: CommandId.make("cmd-overwrite-3"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-overwrite"), - messageId: MessageId.makeUnsafe("message-overwrite"), + threadId: ThreadId.make("thread-overwrite"), + messageId: MessageId.make("message-overwrite"), role: "user", text: "first image", attachments: [ @@ -534,17 +536,17 @@ it.layer( yield* eventStore.append({ type: "thread.message-sent", - eventId: EventId.makeUnsafe("evt-overwrite-4"), + eventId: EventId.make("evt-overwrite-4"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-overwrite"), + aggregateId: ThreadId.make("thread-overwrite"), occurredAt: later, - commandId: CommandId.makeUnsafe("cmd-overwrite-4"), + commandId: CommandId.make("cmd-overwrite-4"), causationEventId: null, - correlationId: CommandId.makeUnsafe("cmd-overwrite-4"), + correlationId: CommandId.make("cmd-overwrite-4"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-overwrite"), - messageId: MessageId.makeUnsafe("message-overwrite"), + threadId: ThreadId.make("thread-overwrite"), + messageId: MessageId.make("message-overwrite"), role: "user", text: "", attachments: [ @@ -604,16 +606,16 @@ it.layer( yield* appendAndProject({ type: "project.created", - eventId: EventId.makeUnsafe("evt-rollback-1"), + eventId: EventId.make("evt-rollback-1"), aggregateKind: "project", - aggregateId: ProjectId.makeUnsafe("project-rollback"), + aggregateId: ProjectId.make("project-rollback"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-rollback-1"), + commandId: CommandId.make("cmd-rollback-1"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-rollback-1"), + correlationId: CorrelationId.make("cmd-rollback-1"), metadata: {}, payload: { - projectId: ProjectId.makeUnsafe("project-rollback"), + projectId: ProjectId.make("project-rollback"), title: "Project Rollback", workspaceRoot: "/tmp/project-rollback", defaultModelSelection: null, @@ -625,17 +627,17 @@ it.layer( yield* appendAndProject({ type: "thread.created", - eventId: EventId.makeUnsafe("evt-rollback-2"), + eventId: EventId.make("evt-rollback-2"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-rollback"), + aggregateId: ThreadId.make("thread-rollback"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-rollback-2"), + commandId: CommandId.make("cmd-rollback-2"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-rollback-2"), + correlationId: CorrelationId.make("cmd-rollback-2"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-rollback"), - projectId: ProjectId.makeUnsafe("project-rollback"), + threadId: ThreadId.make("thread-rollback"), + projectId: ProjectId.make("project-rollback"), title: "Thread Rollback", modelSelection: { provider: "codex", @@ -661,17 +663,17 @@ it.layer( const result = yield* Effect.result( appendAndProject({ type: "thread.message-sent", - eventId: EventId.makeUnsafe("evt-rollback-3"), + eventId: EventId.make("evt-rollback-3"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-rollback"), + aggregateId: ThreadId.make("thread-rollback"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-rollback-3"), + commandId: CommandId.make("cmd-rollback-3"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-rollback-3"), + correlationId: CorrelationId.make("cmd-rollback-3"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-rollback"), - messageId: MessageId.makeUnsafe("message-rollback"), + threadId: ThreadId.make("thread-rollback"), + messageId: MessageId.make("message-rollback"), role: "user", text: "Rollback me", attachments: [ @@ -720,7 +722,7 @@ it.layer( const eventStore = yield* OrchestrationEventStore; const { attachmentsDir } = yield* ServerConfig; const now = new Date().toISOString(); - const threadId = ThreadId.makeUnsafe("Thread Revert.Files"); + const threadId = ThreadId.make("Thread Revert.Files"); const keepAttachmentId = "thread-revert-files-00000000-0000-4000-8000-000000000001"; const removeAttachmentId = "thread-revert-files-00000000-0000-4000-8000-000000000002"; const otherThreadAttachmentId = @@ -733,16 +735,16 @@ it.layer( yield* appendAndProject({ type: "project.created", - eventId: EventId.makeUnsafe("evt-revert-files-1"), + eventId: EventId.make("evt-revert-files-1"), aggregateKind: "project", - aggregateId: ProjectId.makeUnsafe("project-revert-files"), + aggregateId: ProjectId.make("project-revert-files"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-revert-files-1"), + commandId: CommandId.make("cmd-revert-files-1"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-revert-files-1"), + correlationId: CorrelationId.make("cmd-revert-files-1"), metadata: {}, payload: { - projectId: ProjectId.makeUnsafe("project-revert-files"), + projectId: ProjectId.make("project-revert-files"), title: "Project Revert Files", workspaceRoot: "/tmp/project-revert-files", defaultModelSelection: null, @@ -754,17 +756,17 @@ it.layer( yield* appendAndProject({ type: "thread.created", - eventId: EventId.makeUnsafe("evt-revert-files-2"), + eventId: EventId.make("evt-revert-files-2"), aggregateKind: "thread", aggregateId: threadId, occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-revert-files-2"), + commandId: CommandId.make("cmd-revert-files-2"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-revert-files-2"), + correlationId: CorrelationId.make("cmd-revert-files-2"), metadata: {}, payload: { threadId, - projectId: ProjectId.makeUnsafe("project-revert-files"), + projectId: ProjectId.make("project-revert-files"), title: "Thread Revert Files", modelSelection: { provider: "codex", @@ -780,39 +782,39 @@ it.layer( yield* appendAndProject({ type: "thread.turn-diff-completed", - eventId: EventId.makeUnsafe("evt-revert-files-3"), + eventId: EventId.make("evt-revert-files-3"), aggregateKind: "thread", aggregateId: threadId, occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-revert-files-3"), + commandId: CommandId.make("cmd-revert-files-3"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-revert-files-3"), + correlationId: CorrelationId.make("cmd-revert-files-3"), metadata: {}, payload: { threadId, - turnId: TurnId.makeUnsafe("turn-keep"), + turnId: TurnId.make("turn-keep"), checkpointTurnCount: 1, - checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-revert-files/turn/1"), + checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert-files/turn/1"), status: "ready", files: [], - assistantMessageId: MessageId.makeUnsafe("message-keep"), + assistantMessageId: MessageId.make("message-keep"), completedAt: now, }, }); yield* appendAndProject({ type: "thread.message-sent", - eventId: EventId.makeUnsafe("evt-revert-files-4"), + eventId: EventId.make("evt-revert-files-4"), aggregateKind: "thread", aggregateId: threadId, occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-revert-files-4"), + commandId: CommandId.make("cmd-revert-files-4"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-revert-files-4"), + correlationId: CorrelationId.make("cmd-revert-files-4"), metadata: {}, payload: { threadId, - messageId: MessageId.makeUnsafe("message-keep"), + messageId: MessageId.make("message-keep"), role: "assistant", text: "Keep", attachments: [ @@ -824,7 +826,7 @@ it.layer( sizeBytes: 5, }, ], - turnId: TurnId.makeUnsafe("turn-keep"), + turnId: TurnId.make("turn-keep"), streaming: false, createdAt: now, updatedAt: now, @@ -833,39 +835,39 @@ it.layer( yield* appendAndProject({ type: "thread.turn-diff-completed", - eventId: EventId.makeUnsafe("evt-revert-files-5"), + eventId: EventId.make("evt-revert-files-5"), aggregateKind: "thread", aggregateId: threadId, occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-revert-files-5"), + commandId: CommandId.make("cmd-revert-files-5"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-revert-files-5"), + correlationId: CorrelationId.make("cmd-revert-files-5"), metadata: {}, payload: { threadId, - turnId: TurnId.makeUnsafe("turn-remove"), + turnId: TurnId.make("turn-remove"), checkpointTurnCount: 2, - checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-revert-files/turn/2"), + checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert-files/turn/2"), status: "ready", files: [], - assistantMessageId: MessageId.makeUnsafe("message-remove"), + assistantMessageId: MessageId.make("message-remove"), completedAt: now, }, }); yield* appendAndProject({ type: "thread.message-sent", - eventId: EventId.makeUnsafe("evt-revert-files-6"), + eventId: EventId.make("evt-revert-files-6"), aggregateKind: "thread", aggregateId: threadId, occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-revert-files-6"), + commandId: CommandId.make("cmd-revert-files-6"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-revert-files-6"), + correlationId: CorrelationId.make("cmd-revert-files-6"), metadata: {}, payload: { threadId, - messageId: MessageId.makeUnsafe("message-remove"), + messageId: MessageId.make("message-remove"), role: "assistant", text: "Remove", attachments: [ @@ -877,7 +879,7 @@ it.layer( sizeBytes: 5, }, ], - turnId: TurnId.makeUnsafe("turn-remove"), + turnId: TurnId.make("turn-remove"), streaming: false, createdAt: now, updatedAt: now, @@ -897,13 +899,13 @@ it.layer( yield* appendAndProject({ type: "thread.reverted", - eventId: EventId.makeUnsafe("evt-revert-files-7"), + eventId: EventId.make("evt-revert-files-7"), aggregateKind: "thread", aggregateId: threadId, occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-revert-files-7"), + commandId: CommandId.make("cmd-revert-files-7"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-revert-files-7"), + correlationId: CorrelationId.make("cmd-revert-files-7"), metadata: {}, payload: { threadId, @@ -929,7 +931,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta const eventStore = yield* OrchestrationEventStore; const { attachmentsDir } = yield* ServerConfig; const now = new Date().toISOString(); - const threadId = ThreadId.makeUnsafe("Thread Delete.Files"); + const threadId = ThreadId.make("Thread Delete.Files"); const attachmentId = "thread-delete-files-00000000-0000-4000-8000-000000000001"; const otherThreadAttachmentId = "thread-delete-files-extra-00000000-0000-4000-8000-000000000002"; @@ -941,16 +943,16 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta yield* appendAndProject({ type: "project.created", - eventId: EventId.makeUnsafe("evt-delete-files-1"), + eventId: EventId.make("evt-delete-files-1"), aggregateKind: "project", - aggregateId: ProjectId.makeUnsafe("project-delete-files"), + aggregateId: ProjectId.make("project-delete-files"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-delete-files-1"), + commandId: CommandId.make("cmd-delete-files-1"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-delete-files-1"), + correlationId: CorrelationId.make("cmd-delete-files-1"), metadata: {}, payload: { - projectId: ProjectId.makeUnsafe("project-delete-files"), + projectId: ProjectId.make("project-delete-files"), title: "Project Delete Files", workspaceRoot: "/tmp/project-delete-files", defaultModelSelection: null, @@ -962,17 +964,17 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta yield* appendAndProject({ type: "thread.created", - eventId: EventId.makeUnsafe("evt-delete-files-2"), + eventId: EventId.make("evt-delete-files-2"), aggregateKind: "thread", aggregateId: threadId, occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-delete-files-2"), + commandId: CommandId.make("cmd-delete-files-2"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-delete-files-2"), + correlationId: CorrelationId.make("cmd-delete-files-2"), metadata: {}, payload: { threadId, - projectId: ProjectId.makeUnsafe("project-delete-files"), + projectId: ProjectId.make("project-delete-files"), title: "Thread Delete Files", modelSelection: { provider: "codex", @@ -988,17 +990,17 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta yield* appendAndProject({ type: "thread.message-sent", - eventId: EventId.makeUnsafe("evt-delete-files-3"), + eventId: EventId.make("evt-delete-files-3"), aggregateKind: "thread", aggregateId: threadId, occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-delete-files-3"), + commandId: CommandId.make("cmd-delete-files-3"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-delete-files-3"), + correlationId: CorrelationId.make("cmd-delete-files-3"), metadata: {}, payload: { threadId, - messageId: MessageId.makeUnsafe("message-delete-files"), + messageId: MessageId.make("message-delete-files"), role: "user", text: "Delete", attachments: [ @@ -1030,13 +1032,13 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta yield* appendAndProject({ type: "thread.deleted", - eventId: EventId.makeUnsafe("evt-delete-files-4"), + eventId: EventId.make("evt-delete-files-4"), aggregateKind: "thread", aggregateId: threadId, occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-delete-files-4"), + commandId: CommandId.make("cmd-delete-files-4"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-delete-files-4"), + correlationId: CorrelationId.make("cmd-delete-files-4"), metadata: {}, payload: { threadId, @@ -1070,16 +1072,16 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta yield* eventStore.append({ type: "thread.deleted", - eventId: EventId.makeUnsafe("evt-unsafe-thread-delete"), + eventId: EventId.make("evt-unsafe-thread-delete"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe(".."), + aggregateId: ThreadId.make(".."), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-unsafe-thread-delete"), + commandId: CommandId.make("cmd-unsafe-thread-delete"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-unsafe-thread-delete"), + correlationId: CorrelationId.make("cmd-unsafe-thread-delete"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe(".."), + threadId: ThreadId.make(".."), deletedAt: now, }, }); @@ -1104,16 +1106,16 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* eventStore.append({ type: "project.created", - eventId: EventId.makeUnsafe("evt-a1"), + eventId: EventId.make("evt-a1"), aggregateKind: "project", - aggregateId: ProjectId.makeUnsafe("project-a"), + aggregateId: ProjectId.make("project-a"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-a1"), + commandId: CommandId.make("cmd-a1"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-a1"), + correlationId: CorrelationId.make("cmd-a1"), metadata: {}, payload: { - projectId: ProjectId.makeUnsafe("project-a"), + projectId: ProjectId.make("project-a"), title: "Project A", workspaceRoot: "/tmp/project-a", defaultModelSelection: null, @@ -1125,17 +1127,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* eventStore.append({ type: "thread.created", - eventId: EventId.makeUnsafe("evt-a2"), + eventId: EventId.make("evt-a2"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-a"), + aggregateId: ThreadId.make("thread-a"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-a2"), + commandId: CommandId.make("cmd-a2"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-a2"), + correlationId: CorrelationId.make("cmd-a2"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-a"), - projectId: ProjectId.makeUnsafe("project-a"), + threadId: ThreadId.make("thread-a"), + projectId: ProjectId.make("project-a"), title: "Thread A", modelSelection: { provider: "codex", @@ -1151,17 +1153,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* eventStore.append({ type: "thread.message-sent", - eventId: EventId.makeUnsafe("evt-a3"), + eventId: EventId.make("evt-a3"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-a"), + aggregateId: ThreadId.make("thread-a"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-a3"), + commandId: CommandId.make("cmd-a3"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-a3"), + correlationId: CorrelationId.make("cmd-a3"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-a"), - messageId: MessageId.makeUnsafe("message-a"), + threadId: ThreadId.make("thread-a"), + messageId: MessageId.make("message-a"), role: "assistant", text: "hello", turnId: null, @@ -1175,17 +1177,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* eventStore.append({ type: "thread.message-sent", - eventId: EventId.makeUnsafe("evt-a4"), + eventId: EventId.make("evt-a4"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-a"), + aggregateId: ThreadId.make("thread-a"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-a4"), + commandId: CommandId.make("cmd-a4"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-a4"), + correlationId: CorrelationId.make("cmd-a4"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-a"), - messageId: MessageId.makeUnsafe("message-a"), + threadId: ThreadId.make("thread-a"), + messageId: MessageId.make("message-a"), role: "assistant", text: " world", turnId: null, @@ -1231,16 +1233,16 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* eventStore.append({ type: "project.created", - eventId: EventId.makeUnsafe("evt-empty-1"), + eventId: EventId.make("evt-empty-1"), aggregateKind: "project", - aggregateId: ProjectId.makeUnsafe("project-empty"), + aggregateId: ProjectId.make("project-empty"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-empty-1"), + commandId: CommandId.make("cmd-empty-1"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-empty-1"), + correlationId: CorrelationId.make("cmd-empty-1"), metadata: {}, payload: { - projectId: ProjectId.makeUnsafe("project-empty"), + projectId: ProjectId.make("project-empty"), title: "Project Empty", workspaceRoot: "/tmp/project-empty", defaultModelSelection: null, @@ -1252,17 +1254,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* eventStore.append({ type: "thread.created", - eventId: EventId.makeUnsafe("evt-empty-2"), + eventId: EventId.make("evt-empty-2"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-empty"), + aggregateId: ThreadId.make("thread-empty"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-empty-2"), + commandId: CommandId.make("cmd-empty-2"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-empty-2"), + correlationId: CorrelationId.make("cmd-empty-2"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-empty"), - projectId: ProjectId.makeUnsafe("project-empty"), + threadId: ThreadId.make("thread-empty"), + projectId: ProjectId.make("project-empty"), title: "Thread Empty", modelSelection: { provider: "codex", @@ -1278,17 +1280,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* eventStore.append({ type: "thread.message-sent", - eventId: EventId.makeUnsafe("evt-empty-3"), + eventId: EventId.make("evt-empty-3"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-empty"), + aggregateId: ThreadId.make("thread-empty"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-empty-3"), + commandId: CommandId.make("cmd-empty-3"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-empty-3"), + correlationId: CorrelationId.make("cmd-empty-3"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-empty"), - messageId: MessageId.makeUnsafe("assistant-empty"), + threadId: ThreadId.make("thread-empty"), + messageId: MessageId.make("assistant-empty"), role: "assistant", text: "Hello", turnId: null, @@ -1300,17 +1302,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* eventStore.append({ type: "thread.message-sent", - eventId: EventId.makeUnsafe("evt-empty-4"), + eventId: EventId.make("evt-empty-4"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-empty"), + aggregateId: ThreadId.make("thread-empty"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-empty-4"), + commandId: CommandId.make("cmd-empty-4"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-empty-4"), + correlationId: CorrelationId.make("cmd-empty-4"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-empty"), - messageId: MessageId.makeUnsafe("assistant-empty"), + threadId: ThreadId.make("thread-empty"), + messageId: MessageId.make("assistant-empty"), role: "assistant", text: " world", turnId: null, @@ -1322,17 +1324,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* eventStore.append({ type: "thread.message-sent", - eventId: EventId.makeUnsafe("evt-empty-5"), + eventId: EventId.make("evt-empty-5"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-empty"), + aggregateId: ThreadId.make("thread-empty"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-empty-5"), + commandId: CommandId.make("cmd-empty-5"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-empty-5"), + correlationId: CorrelationId.make("cmd-empty-5"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-empty"), - messageId: MessageId.makeUnsafe("assistant-empty"), + threadId: ThreadId.make("thread-empty"), + messageId: MessageId.make("assistant-empty"), role: "assistant", text: "", turnId: null, @@ -1371,16 +1373,16 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* appendAndProject({ type: "project.created", - eventId: EventId.makeUnsafe("evt-conflict-1"), + eventId: EventId.make("evt-conflict-1"), aggregateKind: "project", - aggregateId: ProjectId.makeUnsafe("project-conflict"), + aggregateId: ProjectId.make("project-conflict"), occurredAt: "2026-02-26T13:00:00.000Z", - commandId: CommandId.makeUnsafe("cmd-conflict-1"), + commandId: CommandId.make("cmd-conflict-1"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-conflict-1"), + correlationId: CorrelationId.make("cmd-conflict-1"), metadata: {}, payload: { - projectId: ProjectId.makeUnsafe("project-conflict"), + projectId: ProjectId.make("project-conflict"), title: "Project Conflict", workspaceRoot: "/tmp/project-conflict", defaultModelSelection: null, @@ -1392,17 +1394,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* appendAndProject({ type: "thread.created", - eventId: EventId.makeUnsafe("evt-conflict-2"), + eventId: EventId.make("evt-conflict-2"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-conflict"), + aggregateId: ThreadId.make("thread-conflict"), occurredAt: "2026-02-26T13:00:01.000Z", - commandId: CommandId.makeUnsafe("cmd-conflict-2"), + commandId: CommandId.make("cmd-conflict-2"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-conflict-2"), + correlationId: CorrelationId.make("cmd-conflict-2"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-conflict"), - projectId: ProjectId.makeUnsafe("project-conflict"), + threadId: ThreadId.make("thread-conflict"), + projectId: ProjectId.make("project-conflict"), title: "Thread Conflict", modelSelection: { provider: "codex", @@ -1418,37 +1420,37 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* appendAndProject({ type: "thread.turn-interrupt-requested", - eventId: EventId.makeUnsafe("evt-conflict-3"), + eventId: EventId.make("evt-conflict-3"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-conflict"), + aggregateId: ThreadId.make("thread-conflict"), occurredAt: "2026-02-26T13:00:02.000Z", - commandId: CommandId.makeUnsafe("cmd-conflict-3"), + commandId: CommandId.make("cmd-conflict-3"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-conflict-3"), + correlationId: CorrelationId.make("cmd-conflict-3"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-conflict"), - turnId: TurnId.makeUnsafe("turn-interrupted"), + threadId: ThreadId.make("thread-conflict"), + turnId: TurnId.make("turn-interrupted"), createdAt: "2026-02-26T13:00:02.000Z", }, }); yield* appendAndProject({ type: "thread.message-sent", - eventId: EventId.makeUnsafe("evt-conflict-4"), + eventId: EventId.make("evt-conflict-4"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-conflict"), + aggregateId: ThreadId.make("thread-conflict"), occurredAt: "2026-02-26T13:00:03.000Z", - commandId: CommandId.makeUnsafe("cmd-conflict-4"), + commandId: CommandId.make("cmd-conflict-4"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-conflict-4"), + correlationId: CorrelationId.make("cmd-conflict-4"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-conflict"), - messageId: MessageId.makeUnsafe("assistant-conflict"), + threadId: ThreadId.make("thread-conflict"), + messageId: MessageId.make("assistant-conflict"), role: "assistant", text: "done", - turnId: TurnId.makeUnsafe("turn-completed"), + turnId: TurnId.make("turn-completed"), streaming: false, createdAt: "2026-02-26T13:00:03.000Z", updatedAt: "2026-02-26T13:00:03.000Z", @@ -1457,22 +1459,22 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* appendAndProject({ type: "thread.turn-diff-completed", - eventId: EventId.makeUnsafe("evt-conflict-5"), + eventId: EventId.make("evt-conflict-5"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-conflict"), + aggregateId: ThreadId.make("thread-conflict"), occurredAt: "2026-02-26T13:00:04.000Z", - commandId: CommandId.makeUnsafe("cmd-conflict-5"), + commandId: CommandId.make("cmd-conflict-5"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-conflict-5"), + correlationId: CorrelationId.make("cmd-conflict-5"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-conflict"), - turnId: TurnId.makeUnsafe("turn-completed"), + threadId: ThreadId.make("thread-conflict"), + turnId: TurnId.make("turn-completed"), checkpointTurnCount: 1, - checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-conflict/turn/1"), + checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-conflict/turn/1"), status: "ready", files: [], - assistantMessageId: MessageId.makeUnsafe("assistant-conflict"), + assistantMessageId: MessageId.make("assistant-conflict"), completedAt: "2026-02-26T13:00:04.000Z", }, }); @@ -1515,16 +1517,16 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* appendAndProject({ type: "project.created", - eventId: EventId.makeUnsafe("evt-revert-1"), + eventId: EventId.make("evt-revert-1"), aggregateKind: "project", - aggregateId: ProjectId.makeUnsafe("project-revert"), + aggregateId: ProjectId.make("project-revert"), occurredAt: "2026-02-26T12:00:00.000Z", - commandId: CommandId.makeUnsafe("cmd-revert-1"), + commandId: CommandId.make("cmd-revert-1"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-revert-1"), + correlationId: CorrelationId.make("cmd-revert-1"), metadata: {}, payload: { - projectId: ProjectId.makeUnsafe("project-revert"), + projectId: ProjectId.make("project-revert"), title: "Project Revert", workspaceRoot: "/tmp/project-revert", defaultModelSelection: null, @@ -1536,17 +1538,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* appendAndProject({ type: "thread.created", - eventId: EventId.makeUnsafe("evt-revert-2"), + eventId: EventId.make("evt-revert-2"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-revert"), + aggregateId: ThreadId.make("thread-revert"), occurredAt: "2026-02-26T12:00:01.000Z", - commandId: CommandId.makeUnsafe("cmd-revert-2"), + commandId: CommandId.make("cmd-revert-2"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-revert-2"), + correlationId: CorrelationId.make("cmd-revert-2"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-revert"), - projectId: ProjectId.makeUnsafe("project-revert"), + threadId: ThreadId.make("thread-revert"), + projectId: ProjectId.make("project-revert"), title: "Thread Revert", modelSelection: { provider: "codex", @@ -1562,42 +1564,42 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* appendAndProject({ type: "thread.turn-diff-completed", - eventId: EventId.makeUnsafe("evt-revert-3"), + eventId: EventId.make("evt-revert-3"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-revert"), + aggregateId: ThreadId.make("thread-revert"), occurredAt: "2026-02-26T12:00:02.000Z", - commandId: CommandId.makeUnsafe("cmd-revert-3"), + commandId: CommandId.make("cmd-revert-3"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-revert-3"), + correlationId: CorrelationId.make("cmd-revert-3"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-revert"), - turnId: TurnId.makeUnsafe("turn-1"), + threadId: ThreadId.make("thread-revert"), + turnId: TurnId.make("turn-1"), checkpointTurnCount: 1, - checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-revert/turn/1"), + checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert/turn/1"), status: "ready", files: [], - assistantMessageId: MessageId.makeUnsafe("assistant-keep"), + assistantMessageId: MessageId.make("assistant-keep"), completedAt: "2026-02-26T12:00:02.000Z", }, }); yield* appendAndProject({ type: "thread.message-sent", - eventId: EventId.makeUnsafe("evt-revert-4"), + eventId: EventId.make("evt-revert-4"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-revert"), + aggregateId: ThreadId.make("thread-revert"), occurredAt: "2026-02-26T12:00:02.100Z", - commandId: CommandId.makeUnsafe("cmd-revert-4"), + commandId: CommandId.make("cmd-revert-4"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-revert-4"), + correlationId: CorrelationId.make("cmd-revert-4"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-revert"), - messageId: MessageId.makeUnsafe("assistant-keep"), + threadId: ThreadId.make("thread-revert"), + messageId: MessageId.make("assistant-keep"), role: "assistant", text: "kept", - turnId: TurnId.makeUnsafe("turn-1"), + turnId: TurnId.make("turn-1"), streaming: false, createdAt: "2026-02-26T12:00:02.100Z", updatedAt: "2026-02-26T12:00:02.100Z", @@ -1606,42 +1608,42 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* appendAndProject({ type: "thread.turn-diff-completed", - eventId: EventId.makeUnsafe("evt-revert-5"), + eventId: EventId.make("evt-revert-5"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-revert"), + aggregateId: ThreadId.make("thread-revert"), occurredAt: "2026-02-26T12:00:03.000Z", - commandId: CommandId.makeUnsafe("cmd-revert-5"), + commandId: CommandId.make("cmd-revert-5"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-revert-5"), + correlationId: CorrelationId.make("cmd-revert-5"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-revert"), - turnId: TurnId.makeUnsafe("turn-2"), + threadId: ThreadId.make("thread-revert"), + turnId: TurnId.make("turn-2"), checkpointTurnCount: 2, - checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-revert/turn/2"), + checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert/turn/2"), status: "ready", files: [], - assistantMessageId: MessageId.makeUnsafe("assistant-remove"), + assistantMessageId: MessageId.make("assistant-remove"), completedAt: "2026-02-26T12:00:03.000Z", }, }); yield* appendAndProject({ type: "thread.message-sent", - eventId: EventId.makeUnsafe("evt-revert-6"), + eventId: EventId.make("evt-revert-6"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-revert"), + aggregateId: ThreadId.make("thread-revert"), occurredAt: "2026-02-26T12:00:03.050Z", - commandId: CommandId.makeUnsafe("cmd-revert-6"), + commandId: CommandId.make("cmd-revert-6"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-revert-6"), + correlationId: CorrelationId.make("cmd-revert-6"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-revert"), - messageId: MessageId.makeUnsafe("user-remove"), + threadId: ThreadId.make("thread-revert"), + messageId: MessageId.make("user-remove"), role: "user", text: "removed", - turnId: TurnId.makeUnsafe("turn-2"), + turnId: TurnId.make("turn-2"), streaming: false, createdAt: "2026-02-26T12:00:03.050Z", updatedAt: "2026-02-26T12:00:03.050Z", @@ -1650,20 +1652,20 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* appendAndProject({ type: "thread.message-sent", - eventId: EventId.makeUnsafe("evt-revert-7"), + eventId: EventId.make("evt-revert-7"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-revert"), + aggregateId: ThreadId.make("thread-revert"), occurredAt: "2026-02-26T12:00:03.100Z", - commandId: CommandId.makeUnsafe("cmd-revert-7"), + commandId: CommandId.make("cmd-revert-7"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-revert-7"), + correlationId: CorrelationId.make("cmd-revert-7"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-revert"), - messageId: MessageId.makeUnsafe("assistant-remove"), + threadId: ThreadId.make("thread-revert"), + messageId: MessageId.make("assistant-remove"), role: "assistant", text: "removed", - turnId: TurnId.makeUnsafe("turn-2"), + turnId: TurnId.make("turn-2"), streaming: false, createdAt: "2026-02-26T12:00:03.100Z", updatedAt: "2026-02-26T12:00:03.100Z", @@ -1672,16 +1674,16 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { yield* appendAndProject({ type: "thread.reverted", - eventId: EventId.makeUnsafe("evt-revert-8"), + eventId: EventId.make("evt-revert-8"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-revert"), + aggregateId: ThreadId.make("thread-revert"), occurredAt: "2026-02-26T12:00:04.000Z", - commandId: CommandId.makeUnsafe("cmd-revert-8"), + commandId: CommandId.make("cmd-revert-8"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-revert-8"), + correlationId: CorrelationId.make("cmd-revert-8"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-revert"), + threadId: ThreadId.make("thread-revert"), turnCount: 1, }, }); @@ -1723,10 +1725,10 @@ it.effect("restores pending turn-start metadata across projection pipeline resta Layer.provideMerge(persistenceLayer), ); - const threadId = ThreadId.makeUnsafe("thread-restart"); - const turnId = TurnId.makeUnsafe("turn-restart"); - const messageId = MessageId.makeUnsafe("message-restart"); - const sourcePlanThreadId = ThreadId.makeUnsafe("thread-plan-source"); + const threadId = ThreadId.make("thread-restart"); + const turnId = TurnId.make("turn-restart"); + const messageId = MessageId.make("message-restart"); + const sourcePlanThreadId = ThreadId.make("thread-plan-source"); const sourcePlanId = "plan-source"; const turnStartedAt = "2026-02-26T14:00:00.000Z"; const sessionSetAt = "2026-02-26T14:00:05.000Z"; @@ -1737,13 +1739,13 @@ it.effect("restores pending turn-start metadata across projection pipeline resta yield* eventStore.append({ type: "thread.turn-start-requested", - eventId: EventId.makeUnsafe("evt-restart-1"), + eventId: EventId.make("evt-restart-1"), aggregateKind: "thread", aggregateId: threadId, occurredAt: turnStartedAt, - commandId: CommandId.makeUnsafe("cmd-restart-1"), + commandId: CommandId.make("cmd-restart-1"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-restart-1"), + correlationId: CorrelationId.make("cmd-restart-1"), metadata: {}, payload: { threadId, @@ -1767,13 +1769,13 @@ it.effect("restores pending turn-start metadata across projection pipeline resta yield* eventStore.append({ type: "thread.session-set", - eventId: EventId.makeUnsafe("evt-restart-2"), + eventId: EventId.make("evt-restart-2"), aggregateKind: "thread", aggregateId: threadId, occurredAt: sessionSetAt, - commandId: CommandId.makeUnsafe("cmd-restart-2"), + commandId: CommandId.make("cmd-restart-2"), causationEventId: null, - correlationId: CorrelationId.makeUnsafe("cmd-restart-2"), + correlationId: CorrelationId.make("cmd-restart-2"), metadata: {}, payload: { threadId, @@ -1841,9 +1843,11 @@ it.effect("restores pending turn-start metadata across projection pipeline resta const engineLayer = it.layer( OrchestrationEngineLive.pipe( + Layer.provide(OrchestrationProjectionSnapshotQueryLive), Layer.provide(OrchestrationProjectionPipelineLive), Layer.provide(OrchestrationEventStoreLive), Layer.provide(OrchestrationCommandReceiptRepositoryLive), + Layer.provide(RepositoryIdentityResolverLive), Layer.provideMerge(SqlitePersistenceMemory), Layer.provideMerge( ServerConfig.layerTest(process.cwd(), { @@ -1863,8 +1867,8 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => { yield* engine.dispatch({ type: "project.create", - commandId: CommandId.makeUnsafe("cmd-live-project"), - projectId: ProjectId.makeUnsafe("project-live"), + commandId: CommandId.make("cmd-live-project"), + projectId: ProjectId.make("project-live"), title: "Live Project", workspaceRoot: "/tmp/project-live", defaultModelSelection: { @@ -1901,8 +1905,8 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => { yield* engine.dispatch({ type: "project.create", - commandId: CommandId.makeUnsafe("cmd-scripts-project-create"), - projectId: ProjectId.makeUnsafe("project-scripts"), + commandId: CommandId.make("cmd-scripts-project-create"), + projectId: ProjectId.make("project-scripts"), title: "Scripts Project", workspaceRoot: "/tmp/project-scripts", defaultModelSelection: { @@ -1914,8 +1918,8 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => { yield* engine.dispatch({ type: "project.meta.update", - commandId: CommandId.makeUnsafe("cmd-scripts-project-update"), - projectId: ProjectId.makeUnsafe("project-scripts"), + commandId: CommandId.make("cmd-scripts-project-update"), + projectId: ProjectId.make("project-scripts"), scripts: [ { id: "script-1", diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index f0f2ccabee..bdc6fac6d1 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"; @@ -87,7 +86,7 @@ function extractActivityRequestId(payload: unknown): ApprovalRequestId | null { return null; } const requestId = (payload as Record).requestId; - return typeof requestId === "string" ? ApprovalRequestId.makeUnsafe(requestId) : null; + return typeof requestId === "string" ? ApprovalRequestId.make(requestId) : null; } function retainProjectionMessagesAfterRevert( @@ -624,24 +623,28 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti )(function* (event, attachmentSideEffects) { switch (event.type) { case "thread.message-sent": { - const existingRows = yield* projectionThreadMessageRepository.listByThreadId({ - threadId: event.payload.threadId, + const existingMessage = yield* projectionThreadMessageRepository.getByMessageId({ + messageId: event.payload.messageId, + }); + const previousMessage = Option.getOrUndefined(existingMessage); + const nextText = Option.match(existingMessage, { + onNone: () => event.payload.text, + onSome: (message) => { + if (event.payload.streaming) { + return `${message.text}${event.payload.text}`; + } + if (event.payload.text.length === 0) { + return message.text; + } + return event.payload.text; + }, }); - const existingMessage = existingRows.find( - (row) => row.messageId === event.payload.messageId, - ); - const nextText = - existingMessage && event.payload.streaming - ? `${existingMessage.text}${event.payload.text}` - : existingMessage && event.payload.text.length === 0 - ? existingMessage.text - : event.payload.text; const nextAttachments = event.payload.attachments !== undefined ? yield* materializeAttachmentsForProjection({ attachments: event.payload.attachments, }) - : existingMessage?.attachments; + : previousMessage?.attachments; yield* projectionThreadMessageRepository.upsert({ messageId: event.payload.messageId, threadId: event.payload.threadId, @@ -650,7 +653,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti text: nextText, ...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}), isStreaming: event.payload.streaming, - createdAt: existingMessage?.createdAt ?? event.payload.createdAt, + createdAt: previousMessage?.createdAt ?? event.payload.createdAt, updatedAt: event.payload.updatedAt, }); return; @@ -1271,7 +1274,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti Effect.provideService(ServerConfig, serverConfig), Effect.asVoid, Effect.tap(() => - Effect.log("orchestration projection pipeline bootstrapped").pipe( + Effect.logDebug("orchestration projection pipeline bootstrapped").pipe( Effect.annotateLogs({ projectors: projectors.length }), ), ), @@ -1291,7 +1294,6 @@ export const OrchestrationProjectionPipelineLive = Layer.effect( OrchestrationProjectionPipeline, makeOrchestrationProjectionPipeline(), ).pipe( - Layer.provideMerge(NodeServices.layer), Layer.provideMerge(ProjectionProjectRepositoryLive), Layer.provideMerge(ProjectionThreadRepositoryLive), Layer.provideMerge(ProjectionThreadMessageRepositoryLive), diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts index 32143d751f..0eb312cbfd 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts @@ -4,18 +4,22 @@ import { Effect, Layer } from "effect"; import * as SqlClient from "effect/unstable/sql/SqlClient"; import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; +import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts"; import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts"; import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts"; import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"; -const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value); -const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value); -const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value); -const asEventId = (value: string): EventId => EventId.makeUnsafe(value); -const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value); +const asProjectId = (value: string): ProjectId => ProjectId.make(value); +const asTurnId = (value: string): TurnId => TurnId.make(value); +const asMessageId = (value: string): MessageId => MessageId.make(value); +const asEventId = (value: string): EventId => EventId.make(value); +const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(value); const projectionSnapshotLayer = it.layer( - OrchestrationProjectionSnapshotQueryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)), + OrchestrationProjectionSnapshotQueryLive.pipe( + Layer.provideMerge(RepositoryIdentityResolverLive), + Layer.provideMerge(SqlitePersistenceMemory), + ), ); projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { @@ -234,6 +238,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { id: asProjectId("project-1"), title: "Project 1", workspaceRoot: "/tmp/project-1", + repositoryIdentity: null, defaultModelSelection: { provider: "codex", model: "gpt-5-codex", @@ -254,7 +259,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { ]); assert.deepEqual(snapshot.threads, [ { - id: ThreadId.makeUnsafe("thread-1"), + id: ThreadId.make("thread-1"), projectId: asProjectId("project-1"), title: "Thread 1", modelSelection: { @@ -273,7 +278,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { completedAt: "2026-02-24T00:00:08.000Z", assistantMessageId: asMessageId("message-1"), sourceProposedPlan: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), planId: "plan-1", }, }, @@ -298,7 +303,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { turnId: asTurnId("turn-1"), planMarkdown: "# Ship it", implementedAt: "2026-02-24T00:00:05.500Z", - implementationThreadId: ThreadId.makeUnsafe("thread-2"), + implementationThreadId: ThreadId.make("thread-2"), createdAt: "2026-02-24T00:00:05.000Z", updatedAt: "2026-02-24T00:00:05.500Z", }, @@ -326,7 +331,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { }, ], session: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), status: "running", providerName: "codex", runtimeMode: "approval-required", @@ -338,4 +343,290 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { ]); }), ); + + it.effect( + "reads targeted project, thread, and count queries without hydrating the full snapshot", + () => + Effect.gen(function* () { + const snapshotQuery = yield* ProjectionSnapshotQuery; + const sql = yield* SqlClient.SqlClient; + + yield* sql`DELETE FROM projection_projects`; + yield* sql`DELETE FROM projection_threads`; + yield* sql`DELETE FROM projection_turns`; + + yield* sql` + INSERT INTO projection_projects ( + project_id, + title, + workspace_root, + default_model_selection_json, + scripts_json, + created_at, + updated_at, + deleted_at + ) + VALUES + ( + 'project-active', + 'Active Project', + '/tmp/workspace', + '{"provider":"codex","model":"gpt-5-codex"}', + '[]', + '2026-03-01T00:00:00.000Z', + '2026-03-01T00:00:01.000Z', + NULL + ), + ( + 'project-deleted', + 'Deleted Project', + '/tmp/deleted', + NULL, + '[]', + '2026-03-01T00:00:02.000Z', + '2026-03-01T00:00:03.000Z', + '2026-03-01T00:00:04.000Z' + ) + `; + + yield* sql` + INSERT INTO projection_threads ( + thread_id, + project_id, + title, + model_selection_json, + runtime_mode, + interaction_mode, + branch, + worktree_path, + latest_turn_id, + created_at, + updated_at, + archived_at, + deleted_at + ) + VALUES + ( + 'thread-first', + 'project-active', + 'First Thread', + '{"provider":"codex","model":"gpt-5-codex"}', + 'full-access', + 'default', + NULL, + NULL, + NULL, + '2026-03-01T00:00:05.000Z', + '2026-03-01T00:00:06.000Z', + NULL, + NULL + ), + ( + 'thread-second', + 'project-active', + 'Second Thread', + '{"provider":"codex","model":"gpt-5-codex"}', + 'full-access', + 'default', + NULL, + NULL, + NULL, + '2026-03-01T00:00:07.000Z', + '2026-03-01T00:00:08.000Z', + NULL, + NULL + ), + ( + 'thread-deleted', + 'project-active', + 'Deleted Thread', + '{"provider":"codex","model":"gpt-5-codex"}', + 'full-access', + 'default', + NULL, + NULL, + NULL, + '2026-03-01T00:00:09.000Z', + '2026-03-01T00:00:10.000Z', + NULL, + '2026-03-01T00:00:11.000Z' + ) + `; + + const counts = yield* snapshotQuery.getCounts(); + assert.deepEqual(counts, { + projectCount: 2, + threadCount: 3, + }); + + const project = yield* snapshotQuery.getActiveProjectByWorkspaceRoot("/tmp/workspace"); + assert.equal(project._tag, "Some"); + if (project._tag === "Some") { + assert.equal(project.value.id, asProjectId("project-active")); + } + + const missingProject = yield* snapshotQuery.getActiveProjectByWorkspaceRoot("/tmp/missing"); + assert.equal(missingProject._tag, "None"); + + const firstThreadId = yield* snapshotQuery.getFirstActiveThreadIdByProjectId( + asProjectId("project-active"), + ); + assert.equal(firstThreadId._tag, "Some"); + if (firstThreadId._tag === "Some") { + assert.equal(firstThreadId.value, ThreadId.make("thread-first")); + } + }), + ); + + it.effect("reads single-thread checkpoint context without hydrating unrelated threads", () => + Effect.gen(function* () { + const snapshotQuery = yield* ProjectionSnapshotQuery; + const sql = yield* SqlClient.SqlClient; + + yield* sql`DELETE FROM projection_projects`; + yield* sql`DELETE FROM projection_threads`; + yield* sql`DELETE FROM projection_turns`; + + yield* sql` + INSERT INTO projection_projects ( + project_id, + title, + workspace_root, + default_model_selection_json, + scripts_json, + created_at, + updated_at, + deleted_at + ) + VALUES ( + 'project-context', + 'Context Project', + '/tmp/context-workspace', + NULL, + '[]', + '2026-03-02T00:00:00.000Z', + '2026-03-02T00:00:01.000Z', + NULL + ) + `; + + yield* sql` + INSERT INTO projection_threads ( + thread_id, + project_id, + title, + model_selection_json, + runtime_mode, + interaction_mode, + branch, + worktree_path, + latest_turn_id, + created_at, + updated_at, + archived_at, + deleted_at + ) + VALUES ( + 'thread-context', + 'project-context', + 'Context Thread', + '{"provider":"codex","model":"gpt-5-codex"}', + 'full-access', + 'default', + 'feature/perf', + '/tmp/context-worktree', + NULL, + '2026-03-02T00:00:02.000Z', + '2026-03-02T00:00:03.000Z', + NULL, + NULL + ) + `; + + yield* sql` + INSERT INTO projection_turns ( + thread_id, + turn_id, + pending_message_id, + source_proposed_plan_thread_id, + source_proposed_plan_id, + assistant_message_id, + state, + requested_at, + started_at, + completed_at, + checkpoint_turn_count, + checkpoint_ref, + checkpoint_status, + checkpoint_files_json + ) + VALUES + ( + 'thread-context', + 'turn-1', + NULL, + NULL, + NULL, + NULL, + 'completed', + '2026-03-02T00:00:04.000Z', + '2026-03-02T00:00:04.000Z', + '2026-03-02T00:00:04.000Z', + 1, + 'checkpoint-a', + 'ready', + '[]' + ), + ( + 'thread-context', + 'turn-2', + NULL, + NULL, + NULL, + NULL, + 'completed', + '2026-03-02T00:00:05.000Z', + '2026-03-02T00:00:05.000Z', + '2026-03-02T00:00:05.000Z', + 2, + 'checkpoint-b', + 'ready', + '[]' + ) + `; + + const context = yield* snapshotQuery.getThreadCheckpointContext( + ThreadId.make("thread-context"), + ); + assert.equal(context._tag, "Some"); + if (context._tag === "Some") { + assert.deepEqual(context.value, { + threadId: ThreadId.make("thread-context"), + projectId: asProjectId("project-context"), + workspaceRoot: "/tmp/context-workspace", + worktreePath: "/tmp/context-worktree", + checkpoints: [ + { + turnId: asTurnId("turn-1"), + checkpointTurnCount: 1, + checkpointRef: asCheckpointRef("checkpoint-a"), + status: "ready", + files: [], + assistantMessageId: null, + completedAt: "2026-03-02T00:00:04.000Z", + }, + { + turnId: asTurnId("turn-2"), + checkpointTurnCount: 2, + checkpointRef: asCheckpointRef("checkpoint-b"), + status: "ready", + files: [], + assistantMessageId: null, + completedAt: "2026-03-02T00:00:05.000Z", + }, + ], + }); + } + }), + ); }); diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index f951c54b5b..b0f883f940 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -7,7 +7,6 @@ import { OrchestrationProposedPlanId, OrchestrationReadModel, ProjectScript, - ThreadId, TurnId, type OrchestrationCheckpointSummary, type OrchestrationLatestTurn, @@ -18,8 +17,10 @@ import { type OrchestrationThread, type OrchestrationThreadActivity, ModelSelection, + ProjectId, + ThreadId, } from "@t3tools/contracts"; -import { Effect, Layer, Schema, Struct } from "effect"; +import { Effect, Layer, Option, Schema, Struct } from "effect"; import * as SqlClient from "effect/unstable/sql/SqlClient"; import * as SqlSchema from "effect/unstable/sql/SqlSchema"; @@ -37,9 +38,12 @@ import { ProjectionThreadMessage } from "../../persistence/Services/ProjectionTh import { ProjectionThreadProposedPlan } from "../../persistence/Services/ProjectionThreadProposedPlans.ts"; import { ProjectionThreadSession } from "../../persistence/Services/ProjectionThreadSessions.ts"; import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.ts"; +import { RepositoryIdentityResolver } from "../../project/Services/RepositoryIdentityResolver.ts"; import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts"; import { ProjectionSnapshotQuery, + type ProjectionSnapshotCounts, + type ProjectionThreadCheckpointContext, type ProjectionSnapshotQueryShape, } from "../Services/ProjectionSnapshotQuery.ts"; @@ -86,6 +90,29 @@ const ProjectionLatestTurnDbRowSchema = Schema.Struct({ sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId), }); const ProjectionStateDbRowSchema = ProjectionState; +const ProjectionCountsRowSchema = Schema.Struct({ + projectCount: Schema.Number, + threadCount: Schema.Number, +}); +const WorkspaceRootLookupInput = Schema.Struct({ + workspaceRoot: Schema.String, +}); +const ProjectIdLookupInput = Schema.Struct({ + projectId: ProjectId, +}); +const ThreadIdLookupInput = Schema.Struct({ + threadId: ThreadId, +}); +const ProjectionProjectLookupRowSchema = ProjectionProjectDbRowSchema; +const ProjectionThreadIdLookupRowSchema = Schema.Struct({ + threadId: ThreadId, +}); +const ProjectionThreadCheckpointContextThreadRowSchema = Schema.Struct({ + threadId: ThreadId, + projectId: ProjectId, + workspaceRoot: Schema.String, + worktreePath: Schema.NullOr(Schema.String), +}); const REQUIRED_SNAPSHOT_PROJECTORS = [ ORCHESTRATION_PROJECTOR_NAMES.projects, @@ -137,6 +164,8 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st const makeProjectionSnapshotQuery = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; + const repositoryIdentityResolver = yield* RepositoryIdentityResolver; + const repositoryIdentityResolutionConcurrency = 4; const listProjectRows = SqlSchema.findAll({ Request: Schema.Void, @@ -319,11 +348,175 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { `, }); + const readProjectionCounts = SqlSchema.findOne({ + Request: Schema.Void, + Result: ProjectionCountsRowSchema, + execute: () => + sql` + SELECT + (SELECT COUNT(*) FROM projection_projects) AS "projectCount", + (SELECT COUNT(*) FROM projection_threads) AS "threadCount" + `, + }); + + const getActiveProjectRowByWorkspaceRoot = SqlSchema.findOneOption({ + Request: WorkspaceRootLookupInput, + Result: ProjectionProjectLookupRowSchema, + execute: ({ workspaceRoot }) => + sql` + SELECT + project_id AS "projectId", + title, + workspace_root AS "workspaceRoot", + default_model_selection_json AS "defaultModelSelection", + scripts_json AS "scripts", + created_at AS "createdAt", + updated_at AS "updatedAt", + deleted_at AS "deletedAt" + FROM projection_projects + WHERE workspace_root = ${workspaceRoot} + AND deleted_at IS NULL + ORDER BY created_at ASC, project_id ASC + LIMIT 1 + `, + }); + + const getFirstActiveThreadIdByProject = SqlSchema.findOneOption({ + Request: ProjectIdLookupInput, + Result: ProjectionThreadIdLookupRowSchema, + execute: ({ projectId }) => + sql` + SELECT + thread_id AS "threadId" + FROM projection_threads + WHERE project_id = ${projectId} + AND deleted_at IS NULL + ORDER BY created_at ASC, thread_id ASC + LIMIT 1 + `, + }); + + const getThreadCheckpointContextThreadRow = SqlSchema.findOneOption({ + Request: ThreadIdLookupInput, + Result: ProjectionThreadCheckpointContextThreadRowSchema, + execute: ({ threadId }) => + sql` + SELECT + threads.thread_id AS "threadId", + threads.project_id AS "projectId", + projects.workspace_root AS "workspaceRoot", + threads.worktree_path AS "worktreePath" + FROM projection_threads AS threads + INNER JOIN projection_projects AS projects + ON projects.project_id = threads.project_id + WHERE threads.thread_id = ${threadId} + AND threads.deleted_at IS NULL + LIMIT 1 + `, + }); + + const listCheckpointRowsByThread = SqlSchema.findAll({ + Request: ThreadIdLookupInput, + Result: ProjectionCheckpointDbRowSchema, + execute: ({ threadId }) => + sql` + SELECT + thread_id AS "threadId", + turn_id AS "turnId", + checkpoint_turn_count AS "checkpointTurnCount", + checkpoint_ref AS "checkpointRef", + checkpoint_status AS "status", + checkpoint_files_json AS "files", + assistant_message_id AS "assistantMessageId", + completed_at AS "completedAt" + FROM projection_turns + WHERE thread_id = ${threadId} + AND checkpoint_turn_count IS NOT NULL + ORDER BY checkpoint_turn_count ASC + `, + }); + const getSnapshot: ProjectionSnapshotQueryShape["getSnapshot"] = () => sql .withTransaction( - Effect.gen(function* () { - const [ + Effect.all([ + listProjectRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getSnapshot:listProjects:query", + "ProjectionSnapshotQuery.getSnapshot:listProjects:decodeRows", + ), + ), + ), + listThreadRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getSnapshot:listThreads:query", + "ProjectionSnapshotQuery.getSnapshot:listThreads:decodeRows", + ), + ), + ), + listThreadMessageRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getSnapshot:listThreadMessages:query", + "ProjectionSnapshotQuery.getSnapshot:listThreadMessages:decodeRows", + ), + ), + ), + listThreadProposedPlanRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:query", + "ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:decodeRows", + ), + ), + ), + listThreadActivityRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getSnapshot:listThreadActivities:query", + "ProjectionSnapshotQuery.getSnapshot:listThreadActivities:decodeRows", + ), + ), + ), + listThreadSessionRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getSnapshot:listThreadSessions:query", + "ProjectionSnapshotQuery.getSnapshot:listThreadSessions:decodeRows", + ), + ), + ), + listCheckpointRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getSnapshot:listCheckpoints:query", + "ProjectionSnapshotQuery.getSnapshot:listCheckpoints:decodeRows", + ), + ), + ), + listLatestTurnRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getSnapshot:listLatestTurns:query", + "ProjectionSnapshotQuery.getSnapshot:listLatestTurns:decodeRows", + ), + ), + ), + listProjectionStateRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getSnapshot:listProjectionState:query", + "ProjectionSnapshotQuery.getSnapshot:listProjectionState:decodeRows", + ), + ), + ), + ]), + ) + .pipe( + Effect.flatMap( + ([ projectRows, threadRows, messageRows, @@ -333,258 +526,196 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { checkpointRows, latestTurnRows, stateRows, - ] = yield* Effect.all([ - listProjectRows(undefined).pipe( - Effect.mapError( - toPersistenceSqlOrDecodeError( - "ProjectionSnapshotQuery.getSnapshot:listProjects:query", - "ProjectionSnapshotQuery.getSnapshot:listProjects:decodeRows", + ]) => + Effect.gen(function* () { + const messagesByThread = new Map>(); + const proposedPlansByThread = new Map>(); + const activitiesByThread = new Map>(); + const checkpointsByThread = new Map>(); + const sessionsByThread = new Map(); + const latestTurnByThread = new Map(); + + let updatedAt: string | null = null; + + for (const row of projectRows) { + updatedAt = maxIso(updatedAt, row.updatedAt); + } + for (const row of threadRows) { + updatedAt = maxIso(updatedAt, row.updatedAt); + } + for (const row of stateRows) { + updatedAt = maxIso(updatedAt, row.updatedAt); + } + + for (const row of messageRows) { + updatedAt = maxIso(updatedAt, row.updatedAt); + const threadMessages = messagesByThread.get(row.threadId) ?? []; + threadMessages.push({ + id: row.messageId, + role: row.role, + text: row.text, + ...(row.attachments !== null ? { attachments: row.attachments } : {}), + turnId: row.turnId, + streaming: row.isStreaming === 1, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + }); + messagesByThread.set(row.threadId, threadMessages); + } + + for (const row of proposedPlanRows) { + updatedAt = maxIso(updatedAt, row.updatedAt); + const threadProposedPlans = proposedPlansByThread.get(row.threadId) ?? []; + threadProposedPlans.push({ + id: row.planId, + turnId: row.turnId, + planMarkdown: row.planMarkdown, + implementedAt: row.implementedAt, + implementationThreadId: row.implementationThreadId, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + }); + proposedPlansByThread.set(row.threadId, threadProposedPlans); + } + + for (const row of activityRows) { + updatedAt = maxIso(updatedAt, row.createdAt); + const threadActivities = activitiesByThread.get(row.threadId) ?? []; + threadActivities.push({ + id: row.activityId, + tone: row.tone, + kind: row.kind, + summary: row.summary, + payload: row.payload, + turnId: row.turnId, + ...(row.sequence !== null ? { sequence: row.sequence } : {}), + createdAt: row.createdAt, + }); + activitiesByThread.set(row.threadId, threadActivities); + } + + for (const row of checkpointRows) { + updatedAt = maxIso(updatedAt, row.completedAt); + const threadCheckpoints = checkpointsByThread.get(row.threadId) ?? []; + threadCheckpoints.push({ + turnId: row.turnId, + checkpointTurnCount: row.checkpointTurnCount, + checkpointRef: row.checkpointRef, + status: row.status, + files: row.files, + assistantMessageId: row.assistantMessageId, + completedAt: row.completedAt, + }); + checkpointsByThread.set(row.threadId, threadCheckpoints); + } + + for (const row of latestTurnRows) { + updatedAt = maxIso(updatedAt, row.requestedAt); + if (row.startedAt !== null) { + updatedAt = maxIso(updatedAt, row.startedAt); + } + if (row.completedAt !== null) { + updatedAt = maxIso(updatedAt, row.completedAt); + } + if (latestTurnByThread.has(row.threadId)) { + continue; + } + latestTurnByThread.set(row.threadId, { + turnId: row.turnId, + state: + row.state === "error" + ? "error" + : row.state === "interrupted" + ? "interrupted" + : row.state === "completed" + ? "completed" + : "running", + requestedAt: row.requestedAt, + startedAt: row.startedAt, + completedAt: row.completedAt, + assistantMessageId: row.assistantMessageId, + ...(row.sourceProposedPlanThreadId !== null && row.sourceProposedPlanId !== null + ? { + sourceProposedPlan: { + threadId: row.sourceProposedPlanThreadId, + planId: row.sourceProposedPlanId, + }, + } + : {}), + }); + } + + for (const row of sessionRows) { + updatedAt = maxIso(updatedAt, row.updatedAt); + sessionsByThread.set(row.threadId, { + threadId: row.threadId, + status: row.status, + providerName: row.providerName, + runtimeMode: row.runtimeMode, + activeTurnId: row.activeTurnId, + lastError: row.lastError, + updatedAt: row.updatedAt, + }); + } + + const repositoryIdentities = new Map( + yield* Effect.forEach( + projectRows, + (row) => + repositoryIdentityResolver + .resolve(row.workspaceRoot) + .pipe(Effect.map((identity) => [row.projectId, identity] as const)), + { concurrency: repositoryIdentityResolutionConcurrency }, ), - ), - ), - listThreadRows(undefined).pipe( - Effect.mapError( - toPersistenceSqlOrDecodeError( - "ProjectionSnapshotQuery.getSnapshot:listThreads:query", - "ProjectionSnapshotQuery.getSnapshot:listThreads:decodeRows", + ); + + const projects: ReadonlyArray = projectRows.map((row) => ({ + id: row.projectId, + title: row.title, + workspaceRoot: row.workspaceRoot, + repositoryIdentity: repositoryIdentities.get(row.projectId) ?? null, + defaultModelSelection: row.defaultModelSelection, + scripts: row.scripts, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + deletedAt: row.deletedAt, + })); + + const threads: ReadonlyArray = threadRows.map((row) => ({ + id: row.threadId, + projectId: row.projectId, + title: row.title, + modelSelection: row.modelSelection, + runtimeMode: row.runtimeMode, + interactionMode: row.interactionMode, + branch: row.branch, + worktreePath: row.worktreePath, + 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) ?? [], + activities: activitiesByThread.get(row.threadId) ?? [], + checkpoints: checkpointsByThread.get(row.threadId) ?? [], + session: sessionsByThread.get(row.threadId) ?? null, + })); + + const snapshot = { + snapshotSequence: computeSnapshotSequence(stateRows), + projects, + threads, + updatedAt: updatedAt ?? new Date(0).toISOString(), + }; + + return yield* decodeReadModel(snapshot).pipe( + Effect.mapError( + toPersistenceDecodeError("ProjectionSnapshotQuery.getSnapshot:decodeReadModel"), ), - ), - ), - listThreadMessageRows(undefined).pipe( - Effect.mapError( - toPersistenceSqlOrDecodeError( - "ProjectionSnapshotQuery.getSnapshot:listThreadMessages:query", - "ProjectionSnapshotQuery.getSnapshot:listThreadMessages:decodeRows", - ), - ), - ), - listThreadProposedPlanRows(undefined).pipe( - Effect.mapError( - toPersistenceSqlOrDecodeError( - "ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:query", - "ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:decodeRows", - ), - ), - ), - listThreadActivityRows(undefined).pipe( - Effect.mapError( - toPersistenceSqlOrDecodeError( - "ProjectionSnapshotQuery.getSnapshot:listThreadActivities:query", - "ProjectionSnapshotQuery.getSnapshot:listThreadActivities:decodeRows", - ), - ), - ), - listThreadSessionRows(undefined).pipe( - Effect.mapError( - toPersistenceSqlOrDecodeError( - "ProjectionSnapshotQuery.getSnapshot:listThreadSessions:query", - "ProjectionSnapshotQuery.getSnapshot:listThreadSessions:decodeRows", - ), - ), - ), - listCheckpointRows(undefined).pipe( - Effect.mapError( - toPersistenceSqlOrDecodeError( - "ProjectionSnapshotQuery.getSnapshot:listCheckpoints:query", - "ProjectionSnapshotQuery.getSnapshot:listCheckpoints:decodeRows", - ), - ), - ), - listLatestTurnRows(undefined).pipe( - Effect.mapError( - toPersistenceSqlOrDecodeError( - "ProjectionSnapshotQuery.getSnapshot:listLatestTurns:query", - "ProjectionSnapshotQuery.getSnapshot:listLatestTurns:decodeRows", - ), - ), - ), - listProjectionStateRows(undefined).pipe( - Effect.mapError( - toPersistenceSqlOrDecodeError( - "ProjectionSnapshotQuery.getSnapshot:listProjectionState:query", - "ProjectionSnapshotQuery.getSnapshot:listProjectionState:decodeRows", - ), - ), - ), - ]); - - const messagesByThread = new Map>(); - const proposedPlansByThread = new Map>(); - const activitiesByThread = new Map>(); - const checkpointsByThread = new Map>(); - const sessionsByThread = new Map(); - const latestTurnByThread = new Map(); - - let updatedAt: string | null = null; - - for (const row of projectRows) { - updatedAt = maxIso(updatedAt, row.updatedAt); - } - for (const row of threadRows) { - updatedAt = maxIso(updatedAt, row.updatedAt); - } - for (const row of stateRows) { - updatedAt = maxIso(updatedAt, row.updatedAt); - } - - for (const row of messageRows) { - updatedAt = maxIso(updatedAt, row.updatedAt); - const threadMessages = messagesByThread.get(row.threadId) ?? []; - threadMessages.push({ - id: row.messageId, - role: row.role, - text: row.text, - ...(row.attachments !== null ? { attachments: row.attachments } : {}), - turnId: row.turnId, - streaming: row.isStreaming === 1, - createdAt: row.createdAt, - updatedAt: row.updatedAt, - }); - messagesByThread.set(row.threadId, threadMessages); - } - - for (const row of proposedPlanRows) { - updatedAt = maxIso(updatedAt, row.updatedAt); - const threadProposedPlans = proposedPlansByThread.get(row.threadId) ?? []; - threadProposedPlans.push({ - id: row.planId, - turnId: row.turnId, - planMarkdown: row.planMarkdown, - implementedAt: row.implementedAt, - implementationThreadId: row.implementationThreadId, - createdAt: row.createdAt, - updatedAt: row.updatedAt, - }); - proposedPlansByThread.set(row.threadId, threadProposedPlans); - } - - for (const row of activityRows) { - updatedAt = maxIso(updatedAt, row.createdAt); - const threadActivities = activitiesByThread.get(row.threadId) ?? []; - threadActivities.push({ - id: row.activityId, - tone: row.tone, - kind: row.kind, - summary: row.summary, - payload: row.payload, - turnId: row.turnId, - ...(row.sequence !== null ? { sequence: row.sequence } : {}), - createdAt: row.createdAt, - }); - activitiesByThread.set(row.threadId, threadActivities); - } - - for (const row of checkpointRows) { - updatedAt = maxIso(updatedAt, row.completedAt); - const threadCheckpoints = checkpointsByThread.get(row.threadId) ?? []; - threadCheckpoints.push({ - turnId: row.turnId, - checkpointTurnCount: row.checkpointTurnCount, - checkpointRef: row.checkpointRef, - status: row.status, - files: row.files, - assistantMessageId: row.assistantMessageId, - completedAt: row.completedAt, - }); - checkpointsByThread.set(row.threadId, threadCheckpoints); - } - - for (const row of latestTurnRows) { - updatedAt = maxIso(updatedAt, row.requestedAt); - if (row.startedAt !== null) { - updatedAt = maxIso(updatedAt, row.startedAt); - } - if (row.completedAt !== null) { - updatedAt = maxIso(updatedAt, row.completedAt); - } - if (latestTurnByThread.has(row.threadId)) { - continue; - } - latestTurnByThread.set(row.threadId, { - turnId: row.turnId, - state: - row.state === "error" - ? "error" - : row.state === "interrupted" - ? "interrupted" - : row.state === "completed" - ? "completed" - : "running", - requestedAt: row.requestedAt, - startedAt: row.startedAt, - completedAt: row.completedAt, - assistantMessageId: row.assistantMessageId, - ...(row.sourceProposedPlanThreadId !== null && row.sourceProposedPlanId !== null - ? { - sourceProposedPlan: { - threadId: row.sourceProposedPlanThreadId, - planId: row.sourceProposedPlanId, - }, - } - : {}), - }); - } - - for (const row of sessionRows) { - updatedAt = maxIso(updatedAt, row.updatedAt); - sessionsByThread.set(row.threadId, { - threadId: row.threadId, - status: row.status, - providerName: row.providerName, - runtimeMode: row.runtimeMode, - activeTurnId: row.activeTurnId, - lastError: row.lastError, - updatedAt: row.updatedAt, - }); - } - - const projects: ReadonlyArray = projectRows.map((row) => ({ - id: row.projectId, - title: row.title, - workspaceRoot: row.workspaceRoot, - defaultModelSelection: row.defaultModelSelection, - scripts: row.scripts, - createdAt: row.createdAt, - updatedAt: row.updatedAt, - deletedAt: row.deletedAt, - })); - - const threads: ReadonlyArray = threadRows.map((row) => ({ - id: row.threadId, - projectId: row.projectId, - title: row.title, - modelSelection: row.modelSelection, - runtimeMode: row.runtimeMode, - interactionMode: row.interactionMode, - branch: row.branch, - worktreePath: row.worktreePath, - 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) ?? [], - activities: activitiesByThread.get(row.threadId) ?? [], - checkpoints: checkpointsByThread.get(row.threadId) ?? [], - session: sessionsByThread.get(row.threadId) ?? null, - })); - - const snapshot = { - snapshotSequence: computeSnapshotSequence(stateRows), - projects, - threads, - updatedAt: updatedAt ?? new Date(0).toISOString(), - }; - - return yield* decodeReadModel(snapshot).pipe( - Effect.mapError( - toPersistenceDecodeError("ProjectionSnapshotQuery.getSnapshot:decodeReadModel"), - ), - ); - }), - ) - .pipe( + ); + }), + ), Effect.mapError((error) => { if (isPersistenceError(error)) { return error; @@ -593,8 +724,114 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { }), ); + const getCounts: ProjectionSnapshotQueryShape["getCounts"] = () => + readProjectionCounts(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getCounts:query", + "ProjectionSnapshotQuery.getCounts:decodeRow", + ), + ), + Effect.map( + (row): ProjectionSnapshotCounts => ({ + projectCount: row.projectCount, + threadCount: row.threadCount, + }), + ), + ); + + const getActiveProjectByWorkspaceRoot: ProjectionSnapshotQueryShape["getActiveProjectByWorkspaceRoot"] = + (workspaceRoot) => + getActiveProjectRowByWorkspaceRoot({ workspaceRoot }).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getActiveProjectByWorkspaceRoot:query", + "ProjectionSnapshotQuery.getActiveProjectByWorkspaceRoot:decodeRow", + ), + ), + Effect.flatMap((option) => + Option.isNone(option) + ? Effect.succeed(Option.none()) + : repositoryIdentityResolver.resolve(option.value.workspaceRoot).pipe( + Effect.map((repositoryIdentity) => + Option.some({ + id: option.value.projectId, + title: option.value.title, + workspaceRoot: option.value.workspaceRoot, + repositoryIdentity, + defaultModelSelection: option.value.defaultModelSelection, + scripts: option.value.scripts, + createdAt: option.value.createdAt, + updatedAt: option.value.updatedAt, + deletedAt: option.value.deletedAt, + } satisfies OrchestrationProject), + ), + ), + ), + ); + + const getFirstActiveThreadIdByProjectId: ProjectionSnapshotQueryShape["getFirstActiveThreadIdByProjectId"] = + (projectId) => + getFirstActiveThreadIdByProject({ projectId }).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getFirstActiveThreadIdByProjectId:query", + "ProjectionSnapshotQuery.getFirstActiveThreadIdByProjectId:decodeRow", + ), + ), + Effect.map(Option.map((row) => row.threadId)), + ); + + const getThreadCheckpointContext: ProjectionSnapshotQueryShape["getThreadCheckpointContext"] = ( + threadId, + ) => + Effect.gen(function* () { + const threadRow = yield* getThreadCheckpointContextThreadRow({ threadId }).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getThreadCheckpointContext:getThread:query", + "ProjectionSnapshotQuery.getThreadCheckpointContext:getThread:decodeRow", + ), + ), + ); + if (Option.isNone(threadRow)) { + return Option.none(); + } + + const checkpointRows = yield* listCheckpointRowsByThread({ threadId }).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getThreadCheckpointContext:listCheckpoints:query", + "ProjectionSnapshotQuery.getThreadCheckpointContext:listCheckpoints:decodeRows", + ), + ), + ); + + return Option.some({ + threadId: threadRow.value.threadId, + projectId: threadRow.value.projectId, + workspaceRoot: threadRow.value.workspaceRoot, + worktreePath: threadRow.value.worktreePath, + checkpoints: checkpointRows.map( + (row): OrchestrationCheckpointSummary => ({ + turnId: row.turnId, + checkpointTurnCount: row.checkpointTurnCount, + checkpointRef: row.checkpointRef, + status: row.status, + files: row.files, + assistantMessageId: row.assistantMessageId, + completedAt: row.completedAt, + }), + ), + }); + }); + return { getSnapshot, + getCounts, + getActiveProjectByWorkspaceRoot, + getFirstActiveThreadIdByProjectId, + getThreadCheckpointContext, } satisfies ProjectionSnapshotQueryShape; }); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index ed7037695f..ded64fb9e6 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"; @@ -28,19 +28,20 @@ import { } from "../../provider/Services/ProviderService.ts"; import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts"; import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts"; +import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts"; import { OrchestrationEngineLive } from "./OrchestrationEngine.ts"; import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts"; +import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts"; import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts"; import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { ServerSettingsService } from "../../serverSettings.ts"; -const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value); -const asApprovalRequestId = (value: string): ApprovalRequestId => - ApprovalRequestId.makeUnsafe(value); -const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value); -const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value); +const asProjectId = (value: string): ProjectId => ProjectId.make(value); +const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value); +const asMessageId = (value: string): MessageId => MessageId.make(value); +const asTurnId = (value: string): TurnId => TurnId.make(value); const deriveServerPathsSync = (baseDir: string, devUrl: URL | undefined) => Effect.runSync(deriveServerPaths(baseDir, devUrl).pipe(Effect.provide(NodeServices.layer))); @@ -120,8 +121,8 @@ describe("ProviderCommandReactor", () => { input !== null && "threadId" in input && typeof input.threadId === "string" - ? ThreadId.makeUnsafe(input.threadId) - : ThreadId.makeUnsafe(`thread-${sessionIndex}`); + ? ThreadId.make(input.threadId) + : ThreadId.make(`thread-${sessionIndex}`); const session: ProviderSession = { provider: modelSelection.provider, status: "ready" as const, @@ -143,7 +144,7 @@ describe("ProviderCommandReactor", () => { }); const sendTurn = vi.fn((_: unknown) => Effect.succeed({ - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-1"), }), ); @@ -207,13 +208,17 @@ describe("ProviderCommandReactor", () => { sessionModelSwitch: input?.sessionModelSwitch ?? "in-session", }), rollbackConversation: () => unsupported(), - streamEvents: Stream.fromPubSub(runtimeEventPubSub), + get streamEvents() { + return Stream.fromPubSub(runtimeEventPubSub); + }, }; const orchestrationLayer = OrchestrationEngineLive.pipe( + Layer.provide(OrchestrationProjectionSnapshotQueryLive), Layer.provide(OrchestrationProjectionPipelineLive), Layer.provide(OrchestrationEventStoreLive), Layer.provide(OrchestrationCommandReceiptRepositoryLive), + Layer.provide(RepositoryIdentityResolverLive), Layer.provide(SqlitePersistenceMemory), ); const layer = ProviderCommandReactorLive.pipe( @@ -241,7 +246,7 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( engine.dispatch({ type: "project.create", - commandId: CommandId.makeUnsafe("cmd-project-create"), + commandId: CommandId.make("cmd-project-create"), projectId: asProjectId("project-1"), title: "Provider Project", workspaceRoot: "/tmp/provider-project", @@ -252,8 +257,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( engine.dispatch({ type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-thread-create"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-thread-create"), + threadId: ThreadId.make("thread-1"), projectId: asProjectId("project-1"), title: "Thread", modelSelection: modelSelection, @@ -288,8 +293,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-1"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-1"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("user-message-1"), role: "user", @@ -304,7 +309,7 @@ describe("ProviderCommandReactor", () => { await waitFor(() => harness.startSession.mock.calls.length === 1); await waitFor(() => harness.sendTurn.mock.calls.length === 1); - expect(harness.startSession.mock.calls[0]?.[0]).toEqual(ThreadId.makeUnsafe("thread-1")); + expect(harness.startSession.mock.calls[0]?.[0]).toEqual(ThreadId.make("thread-1")); expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({ cwd: "/tmp/provider-project", modelSelection: { @@ -315,7 +320,7 @@ describe("ProviderCommandReactor", () => { }); const readModel = await Effect.runPromise(harness.engine.getReadModel()); - const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); expect(thread?.session?.threadId).toBe("thread-1"); expect(thread?.session?.runtimeMode).toBe("approval-required"); }); @@ -329,8 +334,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.meta.update", - commandId: CommandId.makeUnsafe("cmd-thread-title-seed"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-thread-title-seed"), + threadId: ThreadId.make("thread-1"), title: seededTitle, }), ); @@ -338,8 +343,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-title"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-title"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("user-message-title"), role: "user", @@ -361,12 +366,12 @@ describe("ProviderCommandReactor", () => { await waitFor(async () => { const readModel = await Effect.runPromise(harness.engine.getReadModel()); return ( - readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"))?.title === + readModel.threads.find((entry) => entry.id === ThreadId.make("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")); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); expect(thread?.title).toBe("Generated title"); }); @@ -378,8 +383,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.meta.update", - commandId: CommandId.makeUnsafe("cmd-thread-title-custom"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-thread-title-custom"), + threadId: ThreadId.make("thread-1"), title: "Keep this custom title", }), ); @@ -387,8 +392,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-title-preserve"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-title-preserve"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("user-message-title-preserve"), role: "user", @@ -406,7 +411,7 @@ describe("ProviderCommandReactor", () => { 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")); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); expect(thread?.title).toBe("Keep this custom title"); }); @@ -423,8 +428,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.meta.update", - commandId: CommandId.makeUnsafe("cmd-thread-title-formatted-seed"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-thread-title-formatted-seed"), + threadId: ThreadId.make("thread-1"), title: seededTitle, }), ); @@ -432,8 +437,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-title-formatted"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-title-formatted"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("user-message-title-formatted"), role: "user", @@ -451,13 +456,13 @@ describe("ProviderCommandReactor", () => { await waitFor(async () => { const readModel = await Effect.runPromise(harness.engine.getReadModel()); return ( - readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"))?.title === + readModel.threads.find((entry) => entry.id === ThreadId.make("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")); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); expect(thread?.title).toBe("Reconnect spinner resume bug"); }); @@ -468,8 +473,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.meta.update", - commandId: CommandId.makeUnsafe("cmd-thread-branch"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-thread-branch"), + threadId: ThreadId.make("thread-1"), branch: "t3code/1234abcd", worktreePath: "/tmp/provider-project-worktree", }), @@ -493,8 +498,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-branch-model"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-branch-model"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("user-message-branch-model"), role: "user", @@ -520,8 +525,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-fast"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-fast"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("user-message-fast"), role: "user", @@ -555,7 +560,7 @@ describe("ProviderCommandReactor", () => { }, }); expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({ - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), modelSelection: { provider: "codex", model: "gpt-5.3-codex", @@ -576,8 +581,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-claude-effort"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("user-message-claude-effort"), role: "user", @@ -609,7 +614,7 @@ describe("ProviderCommandReactor", () => { }, }); expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({ - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), modelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6", @@ -629,8 +634,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-claude-fast-mode"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-claude-fast-mode"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("user-message-claude-fast-mode"), role: "user", @@ -662,7 +667,7 @@ describe("ProviderCommandReactor", () => { }, }); expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({ - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), modelSelection: { provider: "claudeAgent", model: "claude-opus-4-6", @@ -680,8 +685,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.interaction-mode.set", - commandId: CommandId.makeUnsafe("cmd-interaction-mode-set-plan"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-interaction-mode-set-plan"), + threadId: ThreadId.make("thread-1"), interactionMode: "plan", createdAt: now, }), @@ -690,8 +695,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-plan"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-plan"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("user-message-plan"), role: "user", @@ -706,7 +711,7 @@ describe("ProviderCommandReactor", () => { await waitFor(() => harness.sendTurn.mock.calls.length === 1); expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({ - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), interactionMode: "plan", }); }); @@ -720,8 +725,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-provider-first"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-provider-first"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("user-message-provider-first"), role: "user", @@ -740,9 +745,7 @@ describe("ProviderCommandReactor", () => { await waitFor(async () => { const readModel = await Effect.runPromise(harness.engine.getReadModel()); - const thread = readModel.threads.find( - (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), - ); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); return ( thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ?? false @@ -753,7 +756,7 @@ describe("ProviderCommandReactor", () => { expect(harness.sendTurn).not.toHaveBeenCalled(); const readModel = await Effect.runPromise(harness.engine.getReadModel()); - const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); expect(thread?.session).toBeNull(); expect( thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"), @@ -772,8 +775,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-1"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-unsupported-1"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("user-message-unsupported-1"), role: "user", @@ -791,8 +794,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-2"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-unsupported-2"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("user-message-unsupported-2"), role: "user", @@ -808,7 +811,7 @@ describe("ProviderCommandReactor", () => { await waitFor(() => harness.sendTurn.mock.calls.length === 2); expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({ - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), modelSelection: { provider: "codex", model: "gpt-5-codex", @@ -823,8 +826,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-unchanged-1"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-unchanged-1"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("user-message-unchanged-1"), role: "user", @@ -843,8 +846,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-unchanged-2"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-unchanged-2"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("user-message-unchanged-2"), role: "user", @@ -871,8 +874,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-1"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-claude-effort-1"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("user-message-claude-effort-1"), role: "user", @@ -898,8 +901,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-2"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-claude-effort-2"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("user-message-claude-effort-2"), role: "user", @@ -940,8 +943,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.runtime-mode.set", - commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-initial-full-access"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-runtime-mode-set-initial-full-access"), + threadId: ThreadId.make("thread-1"), runtimeMode: "full-access", createdAt: now, }), @@ -950,8 +953,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-runtime-mode-1"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-runtime-mode-1"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("user-message-runtime-mode-1"), role: "user", @@ -970,8 +973,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.runtime-mode.set", - commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-1"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-runtime-mode-set-1"), + threadId: ThreadId.make("thread-1"), runtimeMode: "approval-required", createdAt: now, }), @@ -979,17 +982,15 @@ describe("ProviderCommandReactor", () => { await waitFor(async () => { const readModel = await Effect.runPromise(harness.engine.getReadModel()); - const thread = readModel.threads.find( - (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), - ); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); return thread?.runtimeMode === "approval-required"; }); await waitFor(() => harness.startSession.mock.calls.length === 2); await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-runtime-mode-2"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-runtime-mode-2"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("user-message-runtime-mode-2"), role: "user", @@ -1006,16 +1007,16 @@ describe("ProviderCommandReactor", () => { expect(harness.stopSession.mock.calls.length).toBe(0); expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({ - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), resumeCursor: { opaque: "resume-1" }, runtimeMode: "approval-required", }); expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({ - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), }); const readModel = await Effect.runPromise(harness.engine.getReadModel()); - const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); expect(thread?.session?.threadId).toBe("thread-1"); expect(thread?.session?.runtimeMode).toBe("approval-required"); }); @@ -1029,10 +1030,10 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set-runtime-mode-claude"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-session-set-runtime-mode-claude"), + threadId: ThreadId.make("thread-1"), session: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), status: "ready", providerName: "claudeAgent", runtimeMode: "full-access", @@ -1047,8 +1048,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.runtime-mode.set", - commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-claude-no-options"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-runtime-mode-set-claude-no-options"), + threadId: ThreadId.make("thread-1"), runtimeMode: "approval-required", createdAt: now, }), @@ -1072,8 +1073,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-provider-switch-1"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-provider-switch-1"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("user-message-provider-switch-1"), role: "user", @@ -1092,8 +1093,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-provider-switch-2"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-provider-switch-2"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("user-message-provider-switch-2"), role: "user", @@ -1112,9 +1113,7 @@ describe("ProviderCommandReactor", () => { await waitFor(async () => { const readModel = await Effect.runPromise(harness.engine.getReadModel()); - const thread = readModel.threads.find( - (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), - ); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); return ( thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ?? false @@ -1126,7 +1125,7 @@ describe("ProviderCommandReactor", () => { expect(harness.stopSession.mock.calls.length).toBe(0); const readModel = await Effect.runPromise(harness.engine.getReadModel()); - const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); expect(thread?.session?.threadId).toBe("thread-1"); expect(thread?.session?.providerName).toBe("codex"); expect(thread?.session?.runtimeMode).toBe("approval-required"); @@ -1146,8 +1145,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.runtime-mode.set", - commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-initial-full-access-2"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-runtime-mode-set-initial-full-access-2"), + threadId: ThreadId.make("thread-1"), runtimeMode: "full-access", createdAt: now, }), @@ -1156,8 +1155,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-restart-failure-1"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-restart-failure-1"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("user-message-restart-failure-1"), role: "user", @@ -1180,8 +1179,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.runtime-mode.set", - commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-restart-failure"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-runtime-mode-set-restart-failure"), + threadId: ThreadId.make("thread-1"), runtimeMode: "approval-required", createdAt: now, }), @@ -1189,9 +1188,7 @@ describe("ProviderCommandReactor", () => { await waitFor(async () => { const readModel = await Effect.runPromise(harness.engine.getReadModel()); - const thread = readModel.threads.find( - (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), - ); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); return thread?.runtimeMode === "approval-required"; }); await waitFor(() => harness.startSession.mock.calls.length === 2); @@ -1201,7 +1198,7 @@ describe("ProviderCommandReactor", () => { expect(harness.sendTurn.mock.calls.length).toBe(1); const readModel = await Effect.runPromise(harness.engine.getReadModel()); - const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); expect(thread?.session?.threadId).toBe("thread-1"); expect(thread?.session?.runtimeMode).toBe("full-access"); }); @@ -1213,10 +1210,10 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-session-set"), + threadId: ThreadId.make("thread-1"), session: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), status: "running", providerName: "codex", runtimeMode: "approval-required", @@ -1231,8 +1228,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.interrupt", - commandId: CommandId.makeUnsafe("cmd-turn-interrupt"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-interrupt"), + threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-1"), createdAt: now, }), @@ -1251,10 +1248,10 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set-for-approval"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-session-set-for-approval"), + threadId: ThreadId.make("thread-1"), session: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), status: "running", providerName: "codex", runtimeMode: "approval-required", @@ -1269,8 +1266,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.approval.respond", - commandId: CommandId.makeUnsafe("cmd-approval-respond"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-approval-respond"), + threadId: ThreadId.make("thread-1"), requestId: asApprovalRequestId("approval-request-1"), decision: "accept", createdAt: now, @@ -1292,10 +1289,10 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set-for-user-input"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-session-set-for-user-input"), + threadId: ThreadId.make("thread-1"), session: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), status: "running", providerName: "codex", runtimeMode: "approval-required", @@ -1310,8 +1307,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.user-input.respond", - commandId: CommandId.makeUnsafe("cmd-user-input-respond"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-user-input-respond"), + threadId: ThreadId.make("thread-1"), requestId: asApprovalRequestId("user-input-request-1"), answers: { sandbox_mode: "workspace-write", @@ -1346,10 +1343,10 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set-for-approval-error"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-session-set-for-approval-error"), + threadId: ThreadId.make("thread-1"), session: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), status: "running", providerName: "codex", runtimeMode: "approval-required", @@ -1364,10 +1361,10 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.activity.append", - commandId: CommandId.makeUnsafe("cmd-approval-requested"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-approval-requested"), + threadId: ThreadId.make("thread-1"), activity: { - id: EventId.makeUnsafe("activity-approval-requested"), + id: EventId.make("activity-approval-requested"), tone: "approval", kind: "approval.requested", summary: "Command approval requested", @@ -1385,8 +1382,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.approval.respond", - commandId: CommandId.makeUnsafe("cmd-approval-respond-stale"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-approval-respond-stale"), + threadId: ThreadId.make("thread-1"), requestId: asApprovalRequestId("approval-request-1"), decision: "acceptForSession", createdAt: now, @@ -1395,9 +1392,7 @@ describe("ProviderCommandReactor", () => { await waitFor(async () => { const readModel = await Effect.runPromise(harness.engine.getReadModel()); - const thread = readModel.threads.find( - (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), - ); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); if (!thread) return false; return thread.activities.some( (activity) => activity.kind === "provider.approval.respond.failed", @@ -1405,7 +1400,7 @@ describe("ProviderCommandReactor", () => { }); const readModel = await Effect.runPromise(harness.engine.getReadModel()); - const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); expect(thread).toBeDefined(); const failureActivity = thread?.activities.find( @@ -1443,10 +1438,10 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set-for-user-input-error"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-session-set-for-user-input-error"), + threadId: ThreadId.make("thread-1"), session: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), status: "running", providerName: "claudeAgent", runtimeMode: "approval-required", @@ -1461,10 +1456,10 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.activity.append", - commandId: CommandId.makeUnsafe("cmd-user-input-requested"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-user-input-requested"), + threadId: ThreadId.make("thread-1"), activity: { - id: EventId.makeUnsafe("activity-user-input-requested"), + id: EventId.make("activity-user-input-requested"), tone: "info", kind: "user-input.requested", summary: "User input requested", @@ -1494,8 +1489,8 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.user-input.respond", - commandId: CommandId.makeUnsafe("cmd-user-input-respond-stale"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-user-input-respond-stale"), + threadId: ThreadId.make("thread-1"), requestId: asApprovalRequestId("user-input-request-1"), answers: { sandbox_mode: "workspace-write", @@ -1506,9 +1501,7 @@ describe("ProviderCommandReactor", () => { await waitFor(async () => { const readModel = await Effect.runPromise(harness.engine.getReadModel()); - const thread = readModel.threads.find( - (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), - ); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); if (!thread) return false; return thread.activities.some( (activity) => activity.kind === "provider.user-input.respond.failed", @@ -1516,7 +1509,7 @@ describe("ProviderCommandReactor", () => { }); const readModel = await Effect.runPromise(harness.engine.getReadModel()); - const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); expect(thread).toBeDefined(); const failureActivity = thread?.activities.find( @@ -1545,10 +1538,10 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set-for-stop"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-session-set-for-stop"), + threadId: ThreadId.make("thread-1"), session: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), status: "ready", providerName: "codex", runtimeMode: "approval-required", @@ -1563,15 +1556,15 @@ describe("ProviderCommandReactor", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.stop", - commandId: CommandId.makeUnsafe("cmd-session-stop"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-session-stop"), + threadId: ThreadId.make("thread-1"), createdAt: now, }), ); await waitFor(() => harness.stopSession.mock.calls.length === 1); const readModel = await Effect.runPromise(harness.engine.getReadModel()); - const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); expect(thread?.session).not.toBeNull(); expect(thread?.session?.status).toBe("stopped"); expect(thread?.session?.threadId).toBe("thread-1"); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index d4f13ec727..a1a69f0efa 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -16,6 +16,7 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts"; import { GitCore } from "../../git/Services/GitCore.ts"; +import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts"; import { ProviderAdapterRequestError, ProviderServiceError } from "../../provider/Errors.ts"; import { TextGeneration } from "../../git/Services/TextGeneration.ts"; import { ProviderService } from "../../provider/Services/ProviderService.ts"; @@ -66,7 +67,7 @@ const turnStartKeyForEvent = (event: ProviderIntentEvent): string => event.commandId !== null ? `command:${event.commandId}` : `event:${event.eventId}`; const serverCommandId = (tag: string): CommandId => - CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`); + CommandId.make(`server:${tag}:${crypto.randomUUID()}`); const HANDLED_TURN_START_KEY_MAX = 10_000; const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30); @@ -185,7 +186,7 @@ const make = Effect.gen(function* () { commandId: serverCommandId("provider-failure-activity"), threadId: input.threadId, activity: { - id: EventId.makeUnsafe(crypto.randomUUID()), + id: EventId.make(crypto.randomUUID()), tone: "error", kind: input.kind, summary: input.summary, @@ -212,12 +213,12 @@ const make = Effect.gen(function* () { createdAt: input.createdAt, }); - const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) { + const resolveThread = Effect.fn("resolveThread")(function* (threadId: ThreadId) { const readModel = yield* orchestrationEngine.getReadModel(); return readModel.threads.find((entry) => entry.id === threadId); }); - const ensureSessionForThread = Effect.fnUntraced(function* ( + const ensureSessionForThread = Effect.fn("ensureSessionForThread")(function* ( threadId: ThreadId, createdAt: string, options?: { @@ -357,7 +358,7 @@ const make = Effect.gen(function* () { return startedSession.threadId; }); - const sendTurnForThread = Effect.fnUntraced(function* (input: { + const sendTurnForThread = Effect.fn("sendTurnForThread")(function* (input: { readonly threadId: ThreadId; readonly messageText: string; readonly attachments?: ReadonlyArray; @@ -409,7 +410,9 @@ const make = Effect.gen(function* () { }); }); - const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fnUntraced(function* (input: { + const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fn( + "maybeGenerateAndRenameWorktreeBranchForFirstTurn", + )(function* (input: { readonly threadId: ThreadId; readonly branch: string | null; readonly worktreePath: string | null; @@ -461,50 +464,52 @@ 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 maybeGenerateThreadTitleForFirstTurn = Effect.fn("maybeGenerateThreadTitleForFirstTurn")( + 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, + const generated = yield* textGeneration.generateThreadTitle({ cwd: input.cwd, - cause: Cause.pretty(cause), - }), - ), - ); - }); + message: input.messageText, + ...(attachments.length > 0 ? { attachments } : {}), + modelSelection, + }); + if (!generated) return; - const processTurnStartRequested = Effect.fnUntraced(function* ( + 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.fn("processTurnStartRequested")(function* ( event: Extract, ) { const key = turnStartKeyForEvent(event); @@ -583,7 +588,7 @@ const make = Effect.gen(function* () { ); }); - const processTurnInterruptRequested = Effect.fnUntraced(function* ( + const processTurnInterruptRequested = Effect.fn("processTurnInterruptRequested")(function* ( event: Extract, ) { const thread = yield* resolveThread(event.payload.threadId); @@ -606,7 +611,7 @@ const make = Effect.gen(function* () { yield* providerService.interruptTurn({ threadId: event.payload.threadId }); }); - const processApprovalResponseRequested = Effect.fnUntraced(function* ( + const processApprovalResponseRequested = Effect.fn("processApprovalResponseRequested")(function* ( event: Extract, ) { const thread = yield* resolveThread(event.payload.threadId); @@ -653,50 +658,52 @@ const make = Effect.gen(function* () { ); }); - const processUserInputResponseRequested = Effect.fnUntraced(function* ( - event: Extract, - ) { - const thread = yield* resolveThread(event.payload.threadId); - if (!thread) { - return; - } - const hasSession = thread.session && thread.session.status !== "stopped"; - if (!hasSession) { - return yield* appendProviderFailureActivity({ - threadId: event.payload.threadId, - kind: "provider.user-input.respond.failed", - summary: "Provider user input response failed", - detail: "No active provider session is bound to this thread.", - turnId: null, - createdAt: event.payload.createdAt, - requestId: event.payload.requestId, - }); - } + const processUserInputResponseRequested = Effect.fn("processUserInputResponseRequested")( + function* ( + event: Extract, + ) { + const thread = yield* resolveThread(event.payload.threadId); + if (!thread) { + return; + } + const hasSession = thread.session && thread.session.status !== "stopped"; + if (!hasSession) { + return yield* appendProviderFailureActivity({ + threadId: event.payload.threadId, + kind: "provider.user-input.respond.failed", + summary: "Provider user input response failed", + detail: "No active provider session is bound to this thread.", + turnId: null, + createdAt: event.payload.createdAt, + requestId: event.payload.requestId, + }); + } - yield* providerService - .respondToUserInput({ - threadId: event.payload.threadId, - requestId: event.payload.requestId, - answers: event.payload.answers, - }) - .pipe( - Effect.catchCause((cause) => - appendProviderFailureActivity({ - threadId: event.payload.threadId, - kind: "provider.user-input.respond.failed", - summary: "Provider user input response failed", - detail: isUnknownPendingUserInputRequestError(cause) - ? stalePendingRequestDetail("user-input", event.payload.requestId) - : Cause.pretty(cause), - turnId: null, - createdAt: event.payload.createdAt, - requestId: event.payload.requestId, - }), - ), - ); - }); + yield* providerService + .respondToUserInput({ + threadId: event.payload.threadId, + requestId: event.payload.requestId, + answers: event.payload.answers, + }) + .pipe( + Effect.catchCause((cause) => + appendProviderFailureActivity({ + threadId: event.payload.threadId, + kind: "provider.user-input.respond.failed", + summary: "Provider user input response failed", + detail: isUnknownPendingUserInputRequestError(cause) + ? stalePendingRequestDetail("user-input", event.payload.requestId) + : Cause.pretty(cause), + turnId: null, + createdAt: event.payload.createdAt, + requestId: event.payload.requestId, + }), + ), + ); + }, + ); - const processSessionStopRequested = Effect.fnUntraced(function* ( + const processSessionStopRequested = Effect.fn("processSessionStopRequested")(function* ( event: Extract, ) { const thread = yield* resolveThread(event.payload.threadId); @@ -724,39 +731,48 @@ const make = Effect.gen(function* () { }); }); - const processDomainEvent = (event: ProviderIntentEvent) => - Effect.gen(function* () { - switch (event.type) { - case "thread.runtime-mode-set": { - const thread = yield* resolveThread(event.payload.threadId); - if (!thread?.session || thread.session.status === "stopped") { - return; - } - const cachedModelSelection = threadModelSelections.get(event.payload.threadId); - yield* ensureSessionForThread( - event.payload.threadId, - event.occurredAt, - cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {}, - ); + const processDomainEvent = Effect.fn("processDomainEvent")(function* ( + event: ProviderIntentEvent, + ) { + yield* Effect.annotateCurrentSpan({ + "orchestration.event_type": event.type, + "orchestration.thread_id": event.payload.threadId, + ...(event.commandId ? { "orchestration.command_id": event.commandId } : {}), + }); + yield* increment(orchestrationEventsProcessedTotal, { + eventType: event.type, + }); + switch (event.type) { + case "thread.runtime-mode-set": { + const thread = yield* resolveThread(event.payload.threadId); + if (!thread?.session || thread.session.status === "stopped") { return; } - case "thread.turn-start-requested": - yield* processTurnStartRequested(event); - return; - case "thread.turn-interrupt-requested": - yield* processTurnInterruptRequested(event); - return; - case "thread.approval-response-requested": - yield* processApprovalResponseRequested(event); - return; - case "thread.user-input-response-requested": - yield* processUserInputResponseRequested(event); - return; - case "thread.session-stop-requested": - yield* processSessionStopRequested(event); - return; + const cachedModelSelection = threadModelSelections.get(event.payload.threadId); + yield* ensureSessionForThread( + event.payload.threadId, + event.occurredAt, + cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {}, + ); + return; } - }); + case "thread.turn-start-requested": + yield* processTurnStartRequested(event); + return; + case "thread.turn-interrupt-requested": + yield* processTurnInterruptRequested(event); + return; + case "thread.approval-response-requested": + yield* processApprovalResponseRequested(event); + return; + case "thread.user-input-response-requested": + yield* processUserInputResponseRequested(event); + return; + case "thread.session-stop-requested": + yield* processSessionStopRequested(event); + return; + } + }); const processDomainEventSafely = (event: ProviderIntentEvent) => processDomainEvent(event).pipe( diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 529eae2444..2a330a36b5 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -29,8 +29,10 @@ import { ProviderService, type ProviderServiceShape, } from "../../provider/Services/ProviderService.ts"; +import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts"; import { OrchestrationEngineLive } from "./OrchestrationEngine.ts"; import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts"; +import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts"; import { ProviderRuntimeIngestionLive } from "./ProviderRuntimeIngestion.ts"; import { OrchestrationEngineService, @@ -45,12 +47,12 @@ function makeTestServerSettingsLayer(overrides: Partial = {}) { return ServerSettingsService.layerTest(overrides); } -const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value); -const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value); -const asEventId = (value: string): EventId => EventId.makeUnsafe(value); -const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value); -const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value); -const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value); +const asProjectId = (value: string): ProjectId => ProjectId.make(value); +const asItemId = (value: string): ProviderItemId => ProviderItemId.make(value); +const asEventId = (value: string): EventId => EventId.make(value); +const asMessageId = (value: string): MessageId => MessageId.make(value); +const asThreadId = (value: string): ThreadId => ThreadId.make(value); +const asTurnId = (value: string): TurnId => TurnId.make(value); type LegacyProviderRuntimeEvent = { readonly type: string; @@ -97,7 +99,9 @@ function createProviderServiceHarness() { listSessions: () => Effect.succeed([...runtimeSessions]), getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }), rollbackConversation: () => unsupported(), - streamEvents: Stream.fromPubSub(runtimeEventPubSub), + get streamEvents() { + return Stream.fromPubSub(runtimeEventPubSub); + }, }; const setSession = (session: ProviderSession): void => { @@ -197,9 +201,11 @@ describe("ProviderRuntimeIngestion", () => { fs.mkdirSync(path.join(workspaceRoot, ".git")); const provider = createProviderServiceHarness(); const orchestrationLayer = OrchestrationEngineLive.pipe( + Layer.provide(OrchestrationProjectionSnapshotQueryLive), Layer.provide(OrchestrationProjectionPipelineLive), Layer.provide(OrchestrationEventStoreLive), Layer.provide(OrchestrationCommandReceiptRepositoryLive), + Layer.provide(RepositoryIdentityResolverLive), Layer.provide(SqlitePersistenceMemory), ); const layer = ProviderRuntimeIngestionLive.pipe( @@ -221,7 +227,7 @@ describe("ProviderRuntimeIngestion", () => { await Effect.runPromise( engine.dispatch({ type: "project.create", - commandId: CommandId.makeUnsafe("cmd-provider-project-create"), + commandId: CommandId.make("cmd-provider-project-create"), projectId: asProjectId("project-1"), title: "Provider Project", workspaceRoot, @@ -235,8 +241,8 @@ describe("ProviderRuntimeIngestion", () => { await Effect.runPromise( engine.dispatch({ type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-thread-create"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-thread-create"), + threadId: ThreadId.make("thread-1"), projectId: asProjectId("project-1"), title: "Thread", modelSelection: { @@ -253,10 +259,10 @@ describe("ProviderRuntimeIngestion", () => { await Effect.runPromise( engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-seed"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-session-seed"), + threadId: ThreadId.make("thread-1"), session: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), status: "ready", providerName: "codex", runtimeMode: "approval-required", @@ -271,7 +277,7 @@ describe("ProviderRuntimeIngestion", () => { provider: "codex", status: "ready", runtimeMode: "approval-required", - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), createdAt, updatedAt: createdAt, }); @@ -451,9 +457,7 @@ describe("ProviderRuntimeIngestion", () => { await harness.drain(); const midReadModel = await Effect.runPromise(harness.engine.getReadModel()); - const midThread = midReadModel.threads.find( - (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), - ); + const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); expect(midThread?.session?.status).toBe("running"); expect(midThread?.session?.activeTurnId).toBe("turn-midturn-lifecycle"); @@ -480,10 +484,10 @@ describe("ProviderRuntimeIngestion", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-seed-claude-placeholder"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-session-seed-claude-placeholder"), + threadId: ThreadId.make("thread-1"), session: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), status: "ready", providerName: "claudeAgent", runtimeMode: "approval-required", @@ -558,9 +562,7 @@ describe("ProviderRuntimeIngestion", () => { await harness.drain(); const midReadModel = await Effect.runPromise(harness.engine.getReadModel()); - const midThread = midReadModel.threads.find( - (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), - ); + const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); expect(midThread?.session?.status).toBe("running"); expect(midThread?.session?.activeTurnId).toBe("turn-primary"); @@ -612,9 +614,7 @@ describe("ProviderRuntimeIngestion", () => { await harness.drain(); const midReadModel = await Effect.runPromise(harness.engine.getReadModel()); - const midThread = midReadModel.threads.find( - (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), - ); + const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); expect(midThread?.session?.status).toBe("running"); expect(midThread?.session?.activeTurnId).toBe("turn-guarded-main"); @@ -764,7 +764,7 @@ describe("ProviderRuntimeIngestion", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source"), + commandId: CommandId.make("cmd-thread-create-plan-source"), threadId: sourceThreadId, projectId: asProjectId("project-1"), title: "Plan Source", @@ -782,7 +782,7 @@ describe("ProviderRuntimeIngestion", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set-plan-source"), + commandId: CommandId.make("cmd-session-set-plan-source"), threadId: sourceThreadId, session: { threadId: sourceThreadId, @@ -799,7 +799,7 @@ describe("ProviderRuntimeIngestion", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-thread-create-plan-target"), + commandId: CommandId.make("cmd-thread-create-plan-target"), threadId: targetThreadId, projectId: asProjectId("project-1"), title: "Plan Target", @@ -817,7 +817,7 @@ describe("ProviderRuntimeIngestion", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set-plan-target"), + commandId: CommandId.make("cmd-session-set-plan-target"), threadId: targetThreadId, session: { threadId: targetThreadId, @@ -876,7 +876,7 @@ describe("ProviderRuntimeIngestion", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target"), + commandId: CommandId.make("cmd-turn-start-plan-target"), threadId: targetThreadId, message: { messageId: asMessageId("msg-plan-target"), @@ -951,7 +951,7 @@ describe("ProviderRuntimeIngestion", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source-guarded"), + commandId: CommandId.make("cmd-thread-create-plan-source-guarded"), threadId: sourceThreadId, projectId: asProjectId("project-1"), title: "Plan Source", @@ -969,7 +969,7 @@ describe("ProviderRuntimeIngestion", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set-plan-source-guarded"), + commandId: CommandId.make("cmd-session-set-plan-source-guarded"), threadId: sourceThreadId, session: { threadId: sourceThreadId, @@ -1045,7 +1045,7 @@ describe("ProviderRuntimeIngestion", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target-guarded"), + commandId: CommandId.make("cmd-turn-start-plan-target-guarded"), threadId: targetThreadId, message: { messageId: asMessageId("msg-plan-target-guarded"), @@ -1104,7 +1104,7 @@ describe("ProviderRuntimeIngestion", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source-unrelated"), + commandId: CommandId.make("cmd-thread-create-plan-source-unrelated"), threadId: sourceThreadId, projectId: asProjectId("project-1"), title: "Plan Source", @@ -1122,7 +1122,7 @@ describe("ProviderRuntimeIngestion", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set-plan-source-unrelated"), + commandId: CommandId.make("cmd-session-set-plan-source-unrelated"), threadId: sourceThreadId, session: { threadId: sourceThreadId, @@ -1139,7 +1139,7 @@ describe("ProviderRuntimeIngestion", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-thread-create-plan-target-unrelated"), + commandId: CommandId.make("cmd-thread-create-plan-target-unrelated"), threadId: targetThreadId, projectId: asProjectId("project-1"), title: "Plan Target", @@ -1157,7 +1157,7 @@ describe("ProviderRuntimeIngestion", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.makeUnsafe("cmd-session-set-plan-target-unrelated"), + commandId: CommandId.make("cmd-session-set-plan-target-unrelated"), threadId: targetThreadId, session: { threadId: targetThreadId, @@ -1207,7 +1207,7 @@ describe("ProviderRuntimeIngestion", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target-unrelated"), + commandId: CommandId.make("cmd-turn-start-plan-target-unrelated"), threadId: targetThreadId, message: { messageId: asMessageId("msg-plan-target-unrelated"), @@ -1358,9 +1358,7 @@ describe("ProviderRuntimeIngestion", () => { await harness.drain(); const midReadModel = await Effect.runPromise(harness.engine.getReadModel()); - const midThread = midReadModel.threads.find( - (entry) => entry.id === ThreadId.makeUnsafe("thread-1"), - ); + const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); expect( midThread?.messages.some( (message: ProviderRuntimeTestMessage) => message.id === "assistant:item-buffered", @@ -1401,8 +1399,8 @@ describe("ProviderRuntimeIngestion", () => { await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start-streaming-mode"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start-streaming-mode"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("message-streaming-mode"), role: "user", @@ -1643,7 +1641,7 @@ describe("ProviderRuntimeIngestion", () => { provider: "codex", createdAt: now, threadId: asThreadId("thread-1"), - requestId: ApprovalRequestId.makeUnsafe("req-open"), + requestId: ApprovalRequestId.make("req-open"), payload: { requestType: "command_execution_approval", detail: "pwd", @@ -1656,7 +1654,7 @@ describe("ProviderRuntimeIngestion", () => { provider: "codex", createdAt: now, threadId: asThreadId("thread-1"), - requestId: ApprovalRequestId.makeUnsafe("req-open"), + requestId: ApprovalRequestId.make("req-open"), payload: { requestType: "command_execution_approval", decision: "accept", @@ -1675,7 +1673,7 @@ describe("ProviderRuntimeIngestion", () => { ); const readModel = await Effect.runPromise(harness.engine.getReadModel()); - const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); expect(thread).toBeDefined(); const requested = thread?.activities.find( @@ -2280,7 +2278,7 @@ describe("ProviderRuntimeIngestion", () => { createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-user-input"), - requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"), + requestId: ApprovalRequestId.make("req-user-input-1"), payload: { questions: [ { @@ -2305,7 +2303,7 @@ describe("ProviderRuntimeIngestion", () => { createdAt: new Date().toISOString(), threadId: asThreadId("thread-1"), turnId: asTurnId("turn-user-input"), - requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"), + requestId: ApprovalRequestId.make("req-user-input-1"), payload: { answers: { sandbox_mode: "workspace-write", diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index b479d1c28a..c1241241cc 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -30,7 +30,7 @@ import { ServerSettingsService } from "../../serverSettings.ts"; const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`; const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId => - CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`); + CommandId.make(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`); const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000; const TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120); @@ -57,11 +57,11 @@ type RuntimeIngestionInput = }; function toTurnId(value: TurnId | string | undefined): TurnId | undefined { - return value === undefined ? undefined : TurnId.makeUnsafe(String(value)); + return value === undefined ? undefined : TurnId.make(String(value)); } function toApprovalRequestId(value: string | undefined): ApprovalRequestId | undefined { - return value === undefined ? undefined : ApprovalRequestId.makeUnsafe(value); + return value === undefined ? undefined : ApprovalRequestId.make(value); } function sameId(left: string | null | undefined, right: string | null | undefined): boolean { @@ -524,7 +524,7 @@ const make = Effect.fn("make")(function* () { lookup: () => Effect.succeed({ text: "", createdAt: "" }), }); - const isGitRepoForThread = Effect.fnUntraced(function* (threadId: ThreadId) { + const isGitRepoForThread = Effect.fn("isGitRepoForThread")(function* (threadId: ThreadId) { const readModel = yield* orchestrationEngine.getReadModel(); const thread = readModel.threads.find((entry) => entry.id === threadId); if (!thread) { @@ -796,9 +796,9 @@ const make = Effect.fn("make")(function* () { ).pipe(Effect.asVoid); }); - const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fnUntraced(function* ( - threadId: ThreadId, - ) { + const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fn( + "getSourceProposedPlanReferenceForPendingTurnStart", + )(function* (threadId: ThreadId) { const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({ threadId, }); @@ -818,16 +818,17 @@ const make = Effect.fn("make")(function* () { } as const; }); - const getExpectedProviderTurnIdForThread = Effect.fnUntraced(function* (threadId: ThreadId) { - const sessions = yield* providerService.listSessions(); - const session = sessions.find((entry) => entry.threadId === threadId); - return session?.activeTurnId; - }); + const getExpectedProviderTurnIdForThread = Effect.fn("getExpectedProviderTurnIdForThread")( + function* (threadId: ThreadId) { + const sessions = yield* providerService.listSessions(); + const session = sessions.find((entry) => entry.threadId === threadId); + return session?.activeTurnId; + }, + ); - const getSourceProposedPlanReferenceForAcceptedTurnStart = Effect.fnUntraced(function* ( - threadId: ThreadId, - eventTurnId: TurnId | undefined, - ) { + const getSourceProposedPlanReferenceForAcceptedTurnStart = Effect.fn( + "getSourceProposedPlanReferenceForAcceptedTurnStart", + )(function* (threadId: ThreadId, eventTurnId: TurnId | undefined) { if (eventTurnId === undefined) { return null; } @@ -840,34 +841,36 @@ const make = Effect.fn("make")(function* () { return yield* getSourceProposedPlanReferenceForPendingTurnStart(threadId); }); - const markSourceProposedPlanImplemented = Effect.fnUntraced(function* ( - sourceThreadId: ThreadId, - sourcePlanId: OrchestrationProposedPlanId, - implementationThreadId: ThreadId, - implementedAt: string, - ) { - const readModel = yield* orchestrationEngine.getReadModel(); - const sourceThread = readModel.threads.find((entry) => entry.id === sourceThreadId); - const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId); - if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) { - return; - } + const markSourceProposedPlanImplemented = Effect.fn("markSourceProposedPlanImplemented")( + function* ( + sourceThreadId: ThreadId, + sourcePlanId: OrchestrationProposedPlanId, + implementationThreadId: ThreadId, + implementedAt: string, + ) { + const readModel = yield* orchestrationEngine.getReadModel(); + const sourceThread = readModel.threads.find((entry) => entry.id === sourceThreadId); + const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId); + if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) { + return; + } - yield* orchestrationEngine.dispatch({ - type: "thread.proposed-plan.upsert", - commandId: CommandId.makeUnsafe( - `provider:source-proposed-plan-implemented:${implementationThreadId}:${crypto.randomUUID()}`, - ), - threadId: sourceThread.id, - proposedPlan: { - ...sourcePlan, - implementedAt, - implementationThreadId, - updatedAt: implementedAt, - }, - createdAt: implementedAt, - }); - }); + yield* orchestrationEngine.dispatch({ + type: "thread.proposed-plan.upsert", + commandId: CommandId.make( + `provider:source-proposed-plan-implemented:${implementationThreadId}:${crypto.randomUUID()}`, + ), + threadId: sourceThread.id, + proposedPlan: { + ...sourcePlan, + implementedAt, + implementationThreadId, + updatedAt: implementedAt, + }, + createdAt: implementedAt, + }); + }, + ); const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* ( event: ProviderRuntimeEvent, @@ -1000,7 +1003,7 @@ const make = Effect.fn("make")(function* () { event.type === "turn.proposed.delta" ? event.payload.delta : undefined; if (assistantDelta && assistantDelta.length > 0) { - const assistantMessageId = MessageId.makeUnsafe( + const assistantMessageId = MessageId.make( `assistant:${event.itemId ?? event.turnId ?? event.eventId}`, ); const turnId = toTurnId(event.turnId); @@ -1046,9 +1049,7 @@ const make = Effect.fn("make")(function* () { const assistantCompletion = event.type === "item.completed" && event.payload.itemType === "assistant_message" ? { - messageId: MessageId.makeUnsafe( - `assistant:${event.itemId ?? event.turnId ?? event.eventId}`, - ), + messageId: MessageId.make(`assistant:${event.itemId ?? event.turnId ?? event.eventId}`), fallbackText: event.payload.detail, } : undefined; @@ -1183,7 +1184,7 @@ const make = Effect.fn("make")(function* () { if (thread.checkpoints.some((c) => c.turnId === turnId)) { // Already tracked; no-op. } else { - const assistantMessageId = MessageId.makeUnsafe( + const assistantMessageId = MessageId.make( `assistant:${event.itemId ?? event.turnId ?? event.eventId}`, ); const maxTurnCount = thread.checkpoints.reduce( @@ -1196,7 +1197,7 @@ const make = Effect.fn("make")(function* () { threadId: thread.id, turnId, completedAt: now, - checkpointRef: CheckpointRef.makeUnsafe(`provider-diff:${event.eventId}`), + checkpointRef: CheckpointRef.make(`provider-diff:${event.eventId}`), status: "missing", files: [], assistantMessageId, diff --git a/apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts b/apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts index 56c526c08b..5c3148c943 100644 --- a/apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts +++ b/apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts @@ -1,3 +1,13 @@ +/** + * RuntimeReceiptBus layers. + * + * `RuntimeReceiptBusLive` is the production default and intentionally does not + * retain or broadcast receipts. `RuntimeReceiptBusTest` installs the in-memory + * PubSub-backed implementation used by integration tests that need to await + * checkpoint-reactor milestones precisely. + * + * @module RuntimeReceiptBus + */ import { Effect, Layer, PubSub, Stream } from "effect"; import { @@ -6,13 +16,21 @@ import { type OrchestrationRuntimeReceipt, } from "../Services/RuntimeReceiptBus.ts"; -const makeRuntimeReceiptBus = Effect.gen(function* () { +const makeRuntimeReceiptBus = Effect.succeed({ + publish: () => Effect.void, + streamEventsForTest: Stream.empty, +} satisfies RuntimeReceiptBusShape); + +const makeRuntimeReceiptBusTest = Effect.gen(function* () { const pubSub = yield* PubSub.unbounded(); return { publish: (receipt) => PubSub.publish(pubSub, receipt).pipe(Effect.asVoid), - stream: Stream.fromPubSub(pubSub), + get streamEventsForTest() { + return Stream.fromPubSub(pubSub); + }, } satisfies RuntimeReceiptBusShape; }); export const RuntimeReceiptBusLive = Layer.effect(RuntimeReceiptBus, makeRuntimeReceiptBus); +export const RuntimeReceiptBusTest = Layer.effect(RuntimeReceiptBus, makeRuntimeReceiptBusTest); 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/Services/CheckpointReactor.ts b/apps/server/src/orchestration/Services/CheckpointReactor.ts index 539ac784cd..9e9c83beb4 100644 --- a/apps/server/src/orchestration/Services/CheckpointReactor.ts +++ b/apps/server/src/orchestration/Services/CheckpointReactor.ts @@ -6,7 +6,7 @@ * * @module CheckpointReactor */ -import { ServiceMap } from "effect"; +import { Context } from "effect"; import type { Effect, Scope } from "effect"; /** @@ -34,7 +34,6 @@ export interface CheckpointReactorShape { /** * CheckpointReactor - Service tag for checkpoint reactor workers. */ -export class CheckpointReactor extends ServiceMap.Service< - CheckpointReactor, - CheckpointReactorShape ->()("t3/orchestration/Services/CheckpointReactor") {} +export class CheckpointReactor extends Context.Service()( + "t3/orchestration/Services/CheckpointReactor", +) {} diff --git a/apps/server/src/orchestration/Services/OrchestrationEngine.ts b/apps/server/src/orchestration/Services/OrchestrationEngine.ts index 33ac75049f..376b87d30a 100644 --- a/apps/server/src/orchestration/Services/OrchestrationEngine.ts +++ b/apps/server/src/orchestration/Services/OrchestrationEngine.ts @@ -5,7 +5,7 @@ * `OrchestrationEventStore` persistence. It does not own provider process * management or transport concerns (e.g. websocket request parsing). * - * Uses Effect `ServiceMap.Service` for dependency injection. Command dispatch, + * Uses Effect `Context.Service` for dependency injection. Command dispatch, * replay, and unknown-input decoding all return typed domain errors. * * @module OrchestrationEngineService @@ -15,7 +15,7 @@ import type { OrchestrationEvent, OrchestrationReadModel, } from "@t3tools/contracts"; -import { ServiceMap } from "effect"; +import { Context } from "effect"; import type { Effect, Stream } from "effect"; import type { OrchestrationDispatchError } from "../Errors.ts"; @@ -74,7 +74,7 @@ export interface OrchestrationEngineShape { * }) * ``` */ -export class OrchestrationEngineService extends ServiceMap.Service< +export class OrchestrationEngineService extends Context.Service< OrchestrationEngineService, OrchestrationEngineShape >()("t3/orchestration/Services/OrchestrationEngine/OrchestrationEngineService") {} diff --git a/apps/server/src/orchestration/Services/OrchestrationReactor.ts b/apps/server/src/orchestration/Services/OrchestrationReactor.ts index 9b628eebda..a3edeaac61 100644 --- a/apps/server/src/orchestration/Services/OrchestrationReactor.ts +++ b/apps/server/src/orchestration/Services/OrchestrationReactor.ts @@ -6,7 +6,7 @@ * * @module OrchestrationReactor */ -import { ServiceMap } from "effect"; +import { Context } from "effect"; import type { Effect, Scope } from "effect"; /** @@ -25,7 +25,7 @@ export interface OrchestrationReactorShape { /** * OrchestrationReactor - Service tag for orchestration reactor coordination. */ -export class OrchestrationReactor extends ServiceMap.Service< +export class OrchestrationReactor extends Context.Service< OrchestrationReactor, OrchestrationReactorShape >()("t3/orchestration/Services/OrchestrationReactor") {} diff --git a/apps/server/src/orchestration/Services/ProjectionPipeline.ts b/apps/server/src/orchestration/Services/ProjectionPipeline.ts index f8c86bf09b..349f3430ad 100644 --- a/apps/server/src/orchestration/Services/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Services/ProjectionPipeline.ts @@ -7,7 +7,7 @@ * @module OrchestrationProjectionPipeline */ import type { OrchestrationEvent } from "@t3tools/contracts"; -import { ServiceMap } from "effect"; +import { Context } from "effect"; import type { Effect } from "effect"; import type { ProjectionRepositoryError } from "../../persistence/Errors.ts"; @@ -36,7 +36,7 @@ export interface OrchestrationProjectionPipelineShape { /** * OrchestrationProjectionPipeline - Service tag for orchestration projections. */ -export class OrchestrationProjectionPipeline extends ServiceMap.Service< +export class OrchestrationProjectionPipeline extends Context.Service< OrchestrationProjectionPipeline, OrchestrationProjectionPipelineShape >()("t3/orchestration/Services/ProjectionPipeline/OrchestrationProjectionPipeline") {} diff --git a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts index 91e42f02ff..36bbf5028b 100644 --- a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts @@ -6,12 +6,32 @@ * * @module ProjectionSnapshotQuery */ -import type { OrchestrationReadModel } from "@t3tools/contracts"; -import { ServiceMap } from "effect"; +import type { + OrchestrationCheckpointSummary, + OrchestrationProject, + OrchestrationReadModel, + ProjectId, + ThreadId, +} from "@t3tools/contracts"; +import { Context } from "effect"; +import type { Option } from "effect"; import type { Effect } from "effect"; import type { ProjectionRepositoryError } from "../../persistence/Errors.ts"; +export interface ProjectionSnapshotCounts { + readonly projectCount: number; + readonly threadCount: number; +} + +export interface ProjectionThreadCheckpointContext { + readonly threadId: ThreadId; + readonly projectId: ProjectId; + readonly workspaceRoot: string; + readonly worktreePath: string | null; + readonly checkpoints: ReadonlyArray; +} + /** * ProjectionSnapshotQueryShape - Service API for read-model snapshots. */ @@ -23,12 +43,38 @@ export interface ProjectionSnapshotQueryShape { * projector cursor state. */ readonly getSnapshot: () => Effect.Effect; + + /** + * Read aggregate projection counts without hydrating the full read model. + */ + readonly getCounts: () => Effect.Effect; + + /** + * Read the active project for an exact workspace root match. + */ + readonly getActiveProjectByWorkspaceRoot: ( + workspaceRoot: string, + ) => Effect.Effect, ProjectionRepositoryError>; + + /** + * Read the earliest active thread for a project. + */ + readonly getFirstActiveThreadIdByProjectId: ( + projectId: ProjectId, + ) => Effect.Effect, ProjectionRepositoryError>; + + /** + * Read the checkpoint context needed to resolve a single thread diff. + */ + readonly getThreadCheckpointContext: ( + threadId: ThreadId, + ) => Effect.Effect, ProjectionRepositoryError>; } /** * ProjectionSnapshotQuery - Service tag for projection snapshot queries. */ -export class ProjectionSnapshotQuery extends ServiceMap.Service< +export class ProjectionSnapshotQuery extends Context.Service< ProjectionSnapshotQuery, ProjectionSnapshotQueryShape >()("t3/orchestration/Services/ProjectionSnapshotQuery") {} diff --git a/apps/server/src/orchestration/Services/ProviderCommandReactor.ts b/apps/server/src/orchestration/Services/ProviderCommandReactor.ts index 8f96d8fb99..c8b8580682 100644 --- a/apps/server/src/orchestration/Services/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Services/ProviderCommandReactor.ts @@ -6,7 +6,7 @@ * * @module ProviderCommandReactor */ -import { ServiceMap } from "effect"; +import { Context } from "effect"; import type { Effect, Scope } from "effect"; /** @@ -34,7 +34,7 @@ export interface ProviderCommandReactorShape { /** * ProviderCommandReactor - Service tag for provider command reaction workers. */ -export class ProviderCommandReactor extends ServiceMap.Service< +export class ProviderCommandReactor extends Context.Service< ProviderCommandReactor, ProviderCommandReactorShape >()("t3/orchestration/Services/ProviderCommandReactor") {} diff --git a/apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts index f1b95762a2..831ce3a6f0 100644 --- a/apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts @@ -6,7 +6,7 @@ * * @module ProviderRuntimeIngestionService */ -import { ServiceMap } from "effect"; +import { Context } from "effect"; import type { Effect, Scope } from "effect"; /** @@ -34,7 +34,7 @@ export interface ProviderRuntimeIngestionShape { /** * ProviderRuntimeIngestionService - Service tag for runtime ingestion workers. */ -export class ProviderRuntimeIngestionService extends ServiceMap.Service< +export class ProviderRuntimeIngestionService extends Context.Service< ProviderRuntimeIngestionService, ProviderRuntimeIngestionShape >()("t3/orchestration/Services/ProviderRuntimeIngestion/ProviderRuntimeIngestionService") {} diff --git a/apps/server/src/orchestration/Services/RuntimeReceiptBus.ts b/apps/server/src/orchestration/Services/RuntimeReceiptBus.ts index a08ff91685..53038006de 100644 --- a/apps/server/src/orchestration/Services/RuntimeReceiptBus.ts +++ b/apps/server/src/orchestration/Services/RuntimeReceiptBus.ts @@ -1,5 +1,21 @@ +/** + * RuntimeReceiptBus - Internal checkpoint-reactor synchronization receipts. + * + * This service exists to expose short-lived orchestration milestones that are + * useful in tests and harnesses but are not part of the production runtime + * event model. `CheckpointReactor` publishes receipts such as baseline capture, + * diff finalization, and turn-processing quiescence so integration tests can + * wait for those exact points without inferring them indirectly from persisted + * state. + * + * Production code should only call `publish`. Test code may subscribe via + * `streamEventsForTest`, which is intentionally named to make the intended + * usage explicit. + * + * @module RuntimeReceiptBus + */ import { CheckpointRef, IsoDateTime, NonNegativeInt, ThreadId, TurnId } from "@t3tools/contracts"; -import { Schema, ServiceMap } from "effect"; +import { Schema, Context } from "effect"; import type { Effect, Stream } from "effect"; export const CheckpointBaselineCapturedReceipt = Schema.Struct({ @@ -40,10 +56,9 @@ export type OrchestrationRuntimeReceipt = typeof OrchestrationRuntimeReceipt.Typ export interface RuntimeReceiptBusShape { readonly publish: (receipt: OrchestrationRuntimeReceipt) => Effect.Effect; - readonly stream: Stream.Stream; + readonly streamEventsForTest: Stream.Stream; } -export class RuntimeReceiptBus extends ServiceMap.Service< - RuntimeReceiptBus, - RuntimeReceiptBusShape ->()("t3/orchestration/Services/RuntimeReceiptBus") {} +export class RuntimeReceiptBus extends Context.Service()( + "t3/orchestration/Services/RuntimeReceiptBus", +) {} diff --git a/apps/server/src/orchestration/commandInvariants.test.ts b/apps/server/src/orchestration/commandInvariants.test.ts index 43d665a2c9..a678bcea16 100644 --- a/apps/server/src/orchestration/commandInvariants.test.ts +++ b/apps/server/src/orchestration/commandInvariants.test.ts @@ -25,7 +25,7 @@ const readModel: OrchestrationReadModel = { updatedAt: now, projects: [ { - id: ProjectId.makeUnsafe("project-a"), + id: ProjectId.make("project-a"), title: "Project A", workspaceRoot: "/tmp/project-a", defaultModelSelection: { @@ -38,7 +38,7 @@ const readModel: OrchestrationReadModel = { deletedAt: null, }, { - id: ProjectId.makeUnsafe("project-b"), + id: ProjectId.make("project-b"), title: "Project B", workspaceRoot: "/tmp/project-b", defaultModelSelection: { @@ -53,8 +53,8 @@ const readModel: OrchestrationReadModel = { ], threads: [ { - id: ThreadId.makeUnsafe("thread-1"), - projectId: ProjectId.makeUnsafe("project-a"), + id: ThreadId.make("thread-1"), + projectId: ProjectId.make("project-a"), title: "Thread A", modelSelection: { provider: "codex", @@ -76,8 +76,8 @@ const readModel: OrchestrationReadModel = { deletedAt: null, }, { - id: ThreadId.makeUnsafe("thread-2"), - projectId: ProjectId.makeUnsafe("project-b"), + id: ThreadId.make("thread-2"), + projectId: ProjectId.make("project-b"), title: "Thread B", modelSelection: { provider: "codex", @@ -103,10 +103,10 @@ const readModel: OrchestrationReadModel = { const messageSendCommand: OrchestrationCommand = { type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-1"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-1"), + threadId: ThreadId.make("thread-1"), message: { - messageId: MessageId.makeUnsafe("msg-1"), + messageId: MessageId.make("msg-1"), role: "user", text: "hello", attachments: [], @@ -118,13 +118,11 @@ const messageSendCommand: OrchestrationCommand = { describe("commandInvariants", () => { it("finds threads by id and project", () => { - expect(findThreadById(readModel, ThreadId.makeUnsafe("thread-1"))?.projectId).toBe("project-a"); - expect(findThreadById(readModel, ThreadId.makeUnsafe("missing"))).toBeUndefined(); + expect(findThreadById(readModel, ThreadId.make("thread-1"))?.projectId).toBe("project-a"); + expect(findThreadById(readModel, ThreadId.make("missing"))).toBeUndefined(); expect( - listThreadsByProjectId(readModel, ProjectId.makeUnsafe("project-b")).map( - (thread) => thread.id, - ), - ).toEqual([ThreadId.makeUnsafe("thread-2")]); + listThreadsByProjectId(readModel, ProjectId.make("project-b")).map((thread) => thread.id), + ).toEqual([ThreadId.make("thread-2")]); }); it("requires existing thread", async () => { @@ -132,17 +130,17 @@ describe("commandInvariants", () => { requireThread({ readModel, command: messageSendCommand, - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), }), ); - expect(thread.id).toBe(ThreadId.makeUnsafe("thread-1")); + expect(thread.id).toBe(ThreadId.make("thread-1")); await expect( Effect.runPromise( requireThread({ readModel, command: messageSendCommand, - threadId: ThreadId.makeUnsafe("missing"), + threadId: ThreadId.make("missing"), }), ), ).rejects.toThrow("does not exist"); @@ -154,9 +152,9 @@ describe("commandInvariants", () => { readModel, command: { type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-2"), - threadId: ThreadId.makeUnsafe("thread-3"), - projectId: ProjectId.makeUnsafe("project-a"), + commandId: CommandId.make("cmd-2"), + threadId: ThreadId.make("thread-3"), + projectId: ProjectId.make("project-a"), title: "new", modelSelection: { provider: "codex", @@ -168,7 +166,7 @@ describe("commandInvariants", () => { worktreePath: null, createdAt: now, }, - threadId: ThreadId.makeUnsafe("thread-3"), + threadId: ThreadId.make("thread-3"), }), ); @@ -178,9 +176,9 @@ describe("commandInvariants", () => { readModel, command: { type: "thread.create", - commandId: CommandId.makeUnsafe("cmd-3"), - threadId: ThreadId.makeUnsafe("thread-1"), - projectId: ProjectId.makeUnsafe("project-a"), + commandId: CommandId.make("cmd-3"), + threadId: ThreadId.make("thread-1"), + projectId: ProjectId.make("project-a"), title: "dup", modelSelection: { provider: "codex", @@ -192,7 +190,7 @@ describe("commandInvariants", () => { worktreePath: null, createdAt: now, }, - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), }), ), ).rejects.toThrow("already exists"); diff --git a/apps/server/src/orchestration/decider.projectScripts.test.ts b/apps/server/src/orchestration/decider.projectScripts.test.ts index 465865549b..a85e21c53f 100644 --- a/apps/server/src/orchestration/decider.projectScripts.test.ts +++ b/apps/server/src/orchestration/decider.projectScripts.test.ts @@ -12,9 +12,9 @@ import { Effect } from "effect"; import { decideOrchestrationCommand } from "./decider.ts"; import { createEmptyReadModel, projectEvent } from "./projector.ts"; -const asEventId = (value: string): EventId => EventId.makeUnsafe(value); -const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value); -const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value); +const asEventId = (value: string): EventId => EventId.make(value); +const asProjectId = (value: string): ProjectId => ProjectId.make(value); +const asMessageId = (value: string): MessageId => MessageId.make(value); describe("decider project scripts", () => { it("emits empty scripts on project.create", async () => { @@ -25,7 +25,7 @@ describe("decider project scripts", () => { decideOrchestrationCommand({ command: { type: "project.create", - commandId: CommandId.makeUnsafe("cmd-project-create-scripts"), + commandId: CommandId.make("cmd-project-create-scripts"), projectId: asProjectId("project-scripts"), title: "Scripts", workspaceRoot: "/tmp/scripts", @@ -51,9 +51,9 @@ describe("decider project scripts", () => { aggregateId: asProjectId("project-scripts"), type: "project.created", occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-project-create-scripts"), + commandId: CommandId.make("cmd-project-create-scripts"), causationEventId: null, - correlationId: CommandId.makeUnsafe("cmd-project-create-scripts"), + correlationId: CommandId.make("cmd-project-create-scripts"), metadata: {}, payload: { projectId: asProjectId("project-scripts"), @@ -81,7 +81,7 @@ describe("decider project scripts", () => { decideOrchestrationCommand({ command: { type: "project.meta.update", - commandId: CommandId.makeUnsafe("cmd-project-update-scripts"), + commandId: CommandId.make("cmd-project-update-scripts"), projectId: asProjectId("project-scripts"), scripts: Array.from(scripts), }, @@ -105,9 +105,9 @@ describe("decider project scripts", () => { aggregateId: asProjectId("project-1"), type: "project.created", occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-project-create"), + commandId: CommandId.make("cmd-project-create"), causationEventId: null, - correlationId: CommandId.makeUnsafe("cmd-project-create"), + correlationId: CommandId.make("cmd-project-create"), metadata: {}, payload: { projectId: asProjectId("project-1"), @@ -125,15 +125,15 @@ describe("decider project scripts", () => { sequence: 2, eventId: asEventId("evt-thread-create"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-1"), + aggregateId: ThreadId.make("thread-1"), type: "thread.created", occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-thread-create"), + commandId: CommandId.make("cmd-thread-create"), causationEventId: null, - correlationId: CommandId.makeUnsafe("cmd-thread-create"), + correlationId: CommandId.make("cmd-thread-create"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), projectId: asProjectId("project-1"), title: "Thread", modelSelection: { @@ -154,8 +154,8 @@ describe("decider project scripts", () => { decideOrchestrationCommand({ command: { type: "thread.turn.start", - commandId: CommandId.makeUnsafe("cmd-turn-start"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-turn-start"), + threadId: ThreadId.make("thread-1"), message: { messageId: asMessageId("message-user-1"), role: "user", @@ -189,7 +189,7 @@ describe("decider project scripts", () => { return; } expect(turnStartEvent.payload).toMatchObject({ - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), messageId: asMessageId("message-user-1"), modelSelection: { provider: "codex", @@ -214,9 +214,9 @@ describe("decider project scripts", () => { aggregateId: asProjectId("project-1"), type: "project.created", occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-project-create"), + commandId: CommandId.make("cmd-project-create"), causationEventId: null, - correlationId: CommandId.makeUnsafe("cmd-project-create"), + correlationId: CommandId.make("cmd-project-create"), metadata: {}, payload: { projectId: asProjectId("project-1"), @@ -234,15 +234,15 @@ describe("decider project scripts", () => { sequence: 2, eventId: asEventId("evt-thread-create"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-1"), + aggregateId: ThreadId.make("thread-1"), type: "thread.created", occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-thread-create"), + commandId: CommandId.make("cmd-thread-create"), causationEventId: null, - correlationId: CommandId.makeUnsafe("cmd-thread-create"), + correlationId: CommandId.make("cmd-thread-create"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), projectId: asProjectId("project-1"), title: "Thread", modelSelection: { @@ -263,8 +263,8 @@ describe("decider project scripts", () => { decideOrchestrationCommand({ command: { type: "thread.runtime-mode.set", - commandId: CommandId.makeUnsafe("cmd-runtime-mode-set"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-runtime-mode-set"), + threadId: ThreadId.make("thread-1"), runtimeMode: "approval-required", createdAt: now, }, @@ -279,7 +279,7 @@ describe("decider project scripts", () => { expect(singleResult).toMatchObject({ type: "thread.runtime-mode-set", payload: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), runtimeMode: "approval-required", }, }); @@ -296,9 +296,9 @@ describe("decider project scripts", () => { aggregateId: asProjectId("project-1"), type: "project.created", occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-project-create"), + commandId: CommandId.make("cmd-project-create"), causationEventId: null, - correlationId: CommandId.makeUnsafe("cmd-project-create"), + correlationId: CommandId.make("cmd-project-create"), metadata: {}, payload: { projectId: asProjectId("project-1"), @@ -316,15 +316,15 @@ describe("decider project scripts", () => { sequence: 2, eventId: asEventId("evt-thread-create"), aggregateKind: "thread", - aggregateId: ThreadId.makeUnsafe("thread-1"), + aggregateId: ThreadId.make("thread-1"), type: "thread.created", occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-thread-create"), + commandId: CommandId.make("cmd-thread-create"), causationEventId: null, - correlationId: CommandId.makeUnsafe("cmd-thread-create"), + correlationId: CommandId.make("cmd-thread-create"), metadata: {}, payload: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), projectId: asProjectId("project-1"), title: "Thread", modelSelection: { @@ -345,8 +345,8 @@ describe("decider project scripts", () => { decideOrchestrationCommand({ command: { type: "thread.interaction-mode.set", - commandId: CommandId.makeUnsafe("cmd-interaction-mode-set"), - threadId: ThreadId.makeUnsafe("thread-1"), + commandId: CommandId.make("cmd-interaction-mode-set"), + threadId: ThreadId.make("thread-1"), interactionMode: "plan", createdAt: now, }, @@ -361,7 +361,7 @@ describe("decider project scripts", () => { expect(singleResult).toMatchObject({ type: "thread.interaction-mode-set", payload: { - threadId: ThreadId.makeUnsafe("thread-1"), + threadId: ThreadId.make("thread-1"), interactionMode: "plan", }, }); diff --git a/apps/server/src/orchestration/http.ts b/apps/server/src/orchestration/http.ts new file mode 100644 index 0000000000..959d841f67 --- /dev/null +++ b/apps/server/src/orchestration/http.ts @@ -0,0 +1,93 @@ +import { + ClientOrchestrationCommand, + OrchestrationDispatchCommandError, + OrchestrationGetSnapshotError, + type OrchestrationReadModel, +} from "@t3tools/contracts"; +import { Effect } from "effect"; +import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http"; + +import { ServerAuth } from "../auth/Services/ServerAuth.ts"; +import { normalizeDispatchCommand } from "./Normalizer.ts"; +import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts"; +import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts"; + +const respondToOrchestrationHttpError = ( + error: OrchestrationDispatchCommandError | OrchestrationGetSnapshotError, +) => + Effect.gen(function* () { + if (error._tag === "OrchestrationGetSnapshotError") { + yield* Effect.logError("orchestration http route failed", { + message: error.message, + cause: error.cause, + }); + return HttpServerResponse.jsonUnsafe({ error: error.message }, { status: 500 }); + } + + return HttpServerResponse.jsonUnsafe({ error: error.message }, { status: 400 }); + }); + +const authenticateOwnerSession = Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const serverAuth = yield* ServerAuth; + const session = yield* serverAuth.authenticateHttpRequest(request); + if (session.role !== "owner") { + return yield* new OrchestrationDispatchCommandError({ + message: "Only owner sessions can manage projects.", + }); + } + return session; +}); + +export const orchestrationSnapshotRouteLayer = HttpRouter.add( + "GET", + "/api/orchestration/snapshot", + Effect.gen(function* () { + yield* authenticateOwnerSession; + const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; + const snapshot = yield* projectionSnapshotQuery.getSnapshot().pipe( + Effect.mapError( + (cause) => + new OrchestrationGetSnapshotError({ + message: "Failed to load orchestration snapshot.", + cause, + }), + ), + ); + return HttpServerResponse.jsonUnsafe(snapshot satisfies OrchestrationReadModel, { + status: 200, + }); + }).pipe( + Effect.catchTag("OrchestrationDispatchCommandError", respondToOrchestrationHttpError), + Effect.catchTag("OrchestrationGetSnapshotError", respondToOrchestrationHttpError), + ), +); + +export const orchestrationDispatchRouteLayer = HttpRouter.add( + "POST", + "/api/orchestration/dispatch", + Effect.gen(function* () { + yield* authenticateOwnerSession; + const orchestrationEngine = yield* OrchestrationEngineService; + const command = yield* HttpServerRequest.schemaBodyJson(ClientOrchestrationCommand).pipe( + Effect.mapError( + (cause) => + new OrchestrationDispatchCommandError({ + message: "Invalid orchestration command payload.", + cause, + }), + ), + ); + const normalizedCommand = yield* normalizeDispatchCommand(command); + const result = yield* orchestrationEngine.dispatch(normalizedCommand).pipe( + Effect.mapError( + (cause) => + new OrchestrationDispatchCommandError({ + message: "Failed to dispatch orchestration command.", + cause, + }), + ), + ); + return HttpServerResponse.jsonUnsafe(result, { status: 200 }); + }).pipe(Effect.catchTag("OrchestrationDispatchCommandError", respondToOrchestrationHttpError)), +); diff --git a/apps/server/src/orchestration/projector.test.ts b/apps/server/src/orchestration/projector.test.ts index 3dcdd19250..a61153bb52 100644 --- a/apps/server/src/orchestration/projector.test.ts +++ b/apps/server/src/orchestration/projector.test.ts @@ -21,15 +21,15 @@ function makeEvent(input: { }): OrchestrationEvent { return { sequence: input.sequence, - eventId: EventId.makeUnsafe(`event-${input.sequence}`), + eventId: EventId.make(`event-${input.sequence}`), type: input.type, aggregateKind: input.aggregateKind, aggregateId: input.aggregateKind === "project" - ? ProjectId.makeUnsafe(input.aggregateId) - : ThreadId.makeUnsafe(input.aggregateId), + ? ProjectId.make(input.aggregateId) + : ThreadId.make(input.aggregateId), occurredAt: input.occurredAt, - commandId: input.commandId === null ? null : CommandId.makeUnsafe(input.commandId), + commandId: input.commandId === null ? null : CommandId.make(input.commandId), causationEventId: null, correlationId: null, metadata: {}, diff --git a/apps/server/src/orchestration/runtimeLayer.ts b/apps/server/src/orchestration/runtimeLayer.ts new file mode 100644 index 0000000000..1b964709ae --- /dev/null +++ b/apps/server/src/orchestration/runtimeLayer.ts @@ -0,0 +1,27 @@ +import { Layer } from "effect"; + +import { OrchestrationCommandReceiptRepositoryLive } from "../persistence/Layers/OrchestrationCommandReceipts.ts"; +import { OrchestrationEventStoreLive } from "../persistence/Layers/OrchestrationEventStore.ts"; +import { OrchestrationEngineLive } from "./Layers/OrchestrationEngine.ts"; +import { OrchestrationProjectionPipelineLive } from "./Layers/ProjectionPipeline.ts"; +import { OrchestrationProjectionSnapshotQueryLive } from "./Layers/ProjectionSnapshotQuery.ts"; + +export const OrchestrationEventInfrastructureLayerLive = Layer.mergeAll( + OrchestrationEventStoreLive, + OrchestrationCommandReceiptRepositoryLive, +); + +export const OrchestrationProjectionPipelineLayerLive = OrchestrationProjectionPipelineLive.pipe( + Layer.provide(OrchestrationEventStoreLive), +); + +export const OrchestrationInfrastructureLayerLive = Layer.mergeAll( + OrchestrationProjectionSnapshotQueryLive, + OrchestrationEventInfrastructureLayerLive, + OrchestrationProjectionPipelineLayerLive, +); + +export const OrchestrationLayerLive = Layer.mergeAll( + OrchestrationInfrastructureLayerLive, + OrchestrationEngineLive.pipe(Layer.provide(OrchestrationInfrastructureLayerLive)), +); diff --git a/apps/server/src/persistence/Errors.ts b/apps/server/src/persistence/Errors.ts index cb1cb2f3f8..eb05bf5ae9 100644 --- a/apps/server/src/persistence/Errors.ts +++ b/apps/server/src/persistence/Errors.ts @@ -101,5 +101,7 @@ export type OrchestrationCommandReceiptRepositoryError = | PersistenceDecodeError; export type ProviderSessionRuntimeRepositoryError = PersistenceSqlError | PersistenceDecodeError; +export type AuthPairingLinkRepositoryError = PersistenceSqlError | PersistenceDecodeError; +export type AuthSessionRepositoryError = PersistenceSqlError | PersistenceDecodeError; export type ProjectionRepositoryError = PersistenceSqlError | PersistenceDecodeError; diff --git a/apps/server/src/persistence/Layers/AuthPairingLinks.ts b/apps/server/src/persistence/Layers/AuthPairingLinks.ts new file mode 100644 index 0000000000..9767f24993 --- /dev/null +++ b/apps/server/src/persistence/Layers/AuthPairingLinks.ts @@ -0,0 +1,209 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as SqlSchema from "effect/unstable/sql/SqlSchema"; +import { Effect, Layer, Schema } from "effect"; + +import { + toPersistenceDecodeError, + toPersistenceSqlError, + type AuthPairingLinkRepositoryError, +} from "../Errors.ts"; +import { + AuthPairingLinkRecord, + AuthPairingLinkRepository, + type AuthPairingLinkRepositoryShape, + ConsumeAuthPairingLinkInput, + CreateAuthPairingLinkInput, + GetAuthPairingLinkByCredentialInput, + ListActiveAuthPairingLinksInput, + RevokeAuthPairingLinkInput, +} from "../Services/AuthPairingLinks.ts"; + +function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) { + return (cause: unknown): AuthPairingLinkRepositoryError => + Schema.isSchemaError(cause) + ? toPersistenceDecodeError(decodeOperation)(cause) + : toPersistenceSqlError(sqlOperation)(cause); +} + +const makeAuthPairingLinkRepository = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const createPairingLinkRow = SqlSchema.void({ + Request: CreateAuthPairingLinkInput, + execute: (input) => + sql` + INSERT INTO auth_pairing_links ( + id, + credential, + method, + role, + subject, + label, + created_at, + expires_at, + consumed_at, + revoked_at + ) + VALUES ( + ${input.id}, + ${input.credential}, + ${input.method}, + ${input.role}, + ${input.subject}, + ${input.label}, + ${input.createdAt}, + ${input.expiresAt}, + NULL, + NULL + ) + `, + }); + + const consumeAvailablePairingLinkRow = SqlSchema.findOneOption({ + Request: ConsumeAuthPairingLinkInput, + Result: AuthPairingLinkRecord, + execute: ({ credential, consumedAt, now }) => + sql` + UPDATE auth_pairing_links + SET consumed_at = ${consumedAt} + WHERE credential = ${credential} + AND revoked_at IS NULL + AND consumed_at IS NULL + AND expires_at > ${now} + RETURNING + id AS "id", + credential AS "credential", + method AS "method", + role AS "role", + subject AS "subject", + label AS "label", + created_at AS "createdAt", + expires_at AS "expiresAt", + consumed_at AS "consumedAt", + revoked_at AS "revokedAt" + `, + }); + + const listActivePairingLinkRows = SqlSchema.findAll({ + Request: ListActiveAuthPairingLinksInput, + Result: AuthPairingLinkRecord, + execute: ({ now }) => + sql` + SELECT + id AS "id", + credential AS "credential", + method AS "method", + role AS "role", + subject AS "subject", + label AS "label", + created_at AS "createdAt", + expires_at AS "expiresAt", + consumed_at AS "consumedAt", + revoked_at AS "revokedAt" + FROM auth_pairing_links + WHERE revoked_at IS NULL + AND consumed_at IS NULL + AND expires_at > ${now} + ORDER BY created_at DESC, id DESC + `, + }); + + const revokePairingLinkRow = SqlSchema.findAll({ + Request: RevokeAuthPairingLinkInput, + Result: Schema.Struct({ id: Schema.String }), + execute: ({ id, revokedAt }) => + sql` + UPDATE auth_pairing_links + SET revoked_at = ${revokedAt} + WHERE id = ${id} + AND revoked_at IS NULL + AND consumed_at IS NULL + RETURNING id AS "id" + `, + }); + + const getPairingLinkRowByCredential = SqlSchema.findOneOption({ + Request: GetAuthPairingLinkByCredentialInput, + Result: AuthPairingLinkRecord, + execute: ({ credential }) => + sql` + SELECT + id AS "id", + credential AS "credential", + method AS "method", + role AS "role", + subject AS "subject", + label AS "label", + created_at AS "createdAt", + expires_at AS "expiresAt", + consumed_at AS "consumedAt", + revoked_at AS "revokedAt" + FROM auth_pairing_links + WHERE credential = ${credential} + `, + }); + + const create: AuthPairingLinkRepositoryShape["create"] = (input) => + createPairingLinkRow(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthPairingLinkRepository.create:query", + "AuthPairingLinkRepository.create:encodeRequest", + ), + ), + ); + + const consumeAvailable: AuthPairingLinkRepositoryShape["consumeAvailable"] = (input) => + consumeAvailablePairingLinkRow(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthPairingLinkRepository.consumeAvailable:query", + "AuthPairingLinkRepository.consumeAvailable:decodeRow", + ), + ), + ); + + const listActive: AuthPairingLinkRepositoryShape["listActive"] = (input) => + listActivePairingLinkRows(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthPairingLinkRepository.listActive:query", + "AuthPairingLinkRepository.listActive:decodeRows", + ), + ), + ); + + const revoke: AuthPairingLinkRepositoryShape["revoke"] = (input) => + revokePairingLinkRow(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthPairingLinkRepository.revoke:query", + "AuthPairingLinkRepository.revoke:decodeRows", + ), + ), + Effect.map((rows) => rows.length > 0), + ); + + const getByCredential: AuthPairingLinkRepositoryShape["getByCredential"] = (input) => + getPairingLinkRowByCredential(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthPairingLinkRepository.getByCredential:query", + "AuthPairingLinkRepository.getByCredential:decodeRow", + ), + ), + ); + + return { + create, + consumeAvailable, + listActive, + revoke, + getByCredential, + } satisfies AuthPairingLinkRepositoryShape; +}); + +export const AuthPairingLinkRepositoryLive = Layer.effect( + AuthPairingLinkRepository, + makeAuthPairingLinkRepository, +); diff --git a/apps/server/src/persistence/Layers/AuthSessions.ts b/apps/server/src/persistence/Layers/AuthSessions.ts new file mode 100644 index 0000000000..66e02ed2a7 --- /dev/null +++ b/apps/server/src/persistence/Layers/AuthSessions.ts @@ -0,0 +1,279 @@ +import { AuthSessionId } from "@t3tools/contracts"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as SqlSchema from "effect/unstable/sql/SqlSchema"; +import { Effect, Layer, Option, Schema } from "effect"; + +import { + toPersistenceDecodeError, + toPersistenceSqlError, + type AuthSessionRepositoryError, +} from "../Errors.ts"; +import { + AuthSessionRecord, + AuthSessionRepository, + type AuthSessionRepositoryShape, + CreateAuthSessionInput, + GetAuthSessionByIdInput, + ListActiveAuthSessionsInput, + RevokeAuthSessionInput, + RevokeOtherAuthSessionsInput, + SetAuthSessionLastConnectedAtInput, +} from "../Services/AuthSessions.ts"; + +const AuthSessionDbRow = Schema.Struct({ + sessionId: AuthSessionId, + subject: Schema.String, + role: Schema.Literals(["owner", "client"]), + method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]), + clientLabel: Schema.NullOr(Schema.String), + clientIpAddress: Schema.NullOr(Schema.String), + clientUserAgent: Schema.NullOr(Schema.String), + clientDeviceType: Schema.Literals(["desktop", "mobile", "tablet", "bot", "unknown"]), + clientOs: Schema.NullOr(Schema.String), + clientBrowser: Schema.NullOr(Schema.String), + issuedAt: Schema.DateTimeUtcFromString, + expiresAt: Schema.DateTimeUtcFromString, + lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString), + revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString), +}); + +function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): typeof AuthSessionRecord.Type { + return { + sessionId: row.sessionId, + subject: row.subject, + role: row.role, + method: row.method, + client: { + label: row.clientLabel, + ipAddress: row.clientIpAddress, + userAgent: row.clientUserAgent, + deviceType: row.clientDeviceType, + os: row.clientOs, + browser: row.clientBrowser, + }, + issuedAt: row.issuedAt, + expiresAt: row.expiresAt, + lastConnectedAt: row.lastConnectedAt, + revokedAt: row.revokedAt, + }; +} + +function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) { + return (cause: unknown): AuthSessionRepositoryError => + Schema.isSchemaError(cause) + ? toPersistenceDecodeError(decodeOperation)(cause) + : toPersistenceSqlError(sqlOperation)(cause); +} + +const makeAuthSessionRepository = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const createSessionRow = SqlSchema.void({ + Request: CreateAuthSessionInput, + execute: (input) => + sql` + INSERT INTO auth_sessions ( + session_id, + subject, + role, + method, + client_label, + client_ip_address, + client_user_agent, + client_device_type, + client_os, + client_browser, + issued_at, + expires_at, + revoked_at + ) + VALUES ( + ${input.sessionId}, + ${input.subject}, + ${input.role}, + ${input.method}, + ${input.client.label}, + ${input.client.ipAddress}, + ${input.client.userAgent}, + ${input.client.deviceType}, + ${input.client.os}, + ${input.client.browser}, + ${input.issuedAt}, + ${input.expiresAt}, + NULL + ) + `, + }); + + const getSessionRowById = SqlSchema.findOneOption({ + Request: GetAuthSessionByIdInput, + Result: AuthSessionDbRow, + execute: ({ sessionId }) => + sql` + SELECT + session_id AS "sessionId", + subject AS "subject", + role AS "role", + method AS "method", + client_label AS "clientLabel", + client_ip_address AS "clientIpAddress", + client_user_agent AS "clientUserAgent", + client_device_type AS "clientDeviceType", + client_os AS "clientOs", + client_browser AS "clientBrowser", + issued_at AS "issuedAt", + expires_at AS "expiresAt", + last_connected_at AS "lastConnectedAt", + revoked_at AS "revokedAt" + FROM auth_sessions + WHERE session_id = ${sessionId} + `, + }); + + const listActiveSessionRows = SqlSchema.findAll({ + Request: ListActiveAuthSessionsInput, + Result: AuthSessionDbRow, + execute: ({ now }) => + sql` + SELECT + session_id AS "sessionId", + subject AS "subject", + role AS "role", + method AS "method", + client_label AS "clientLabel", + client_ip_address AS "clientIpAddress", + client_user_agent AS "clientUserAgent", + client_device_type AS "clientDeviceType", + client_os AS "clientOs", + client_browser AS "clientBrowser", + issued_at AS "issuedAt", + expires_at AS "expiresAt", + last_connected_at AS "lastConnectedAt", + revoked_at AS "revokedAt" + FROM auth_sessions + WHERE revoked_at IS NULL + AND expires_at > ${now} + ORDER BY issued_at DESC, session_id DESC + `, + }); + + const setLastConnectedAtRow = SqlSchema.void({ + Request: SetAuthSessionLastConnectedAtInput, + execute: ({ sessionId, lastConnectedAt }) => + sql` + UPDATE auth_sessions + SET last_connected_at = ${lastConnectedAt} + WHERE session_id = ${sessionId} + AND revoked_at IS NULL + `, + }); + + const revokeSessionRows = SqlSchema.findAll({ + Request: RevokeAuthSessionInput, + Result: Schema.Struct({ sessionId: AuthSessionId }), + execute: ({ sessionId, revokedAt }) => + sql` + UPDATE auth_sessions + SET revoked_at = ${revokedAt} + WHERE session_id = ${sessionId} + AND revoked_at IS NULL + RETURNING session_id AS "sessionId" + `, + }); + + const revokeOtherSessionRows = SqlSchema.findAll({ + Request: RevokeOtherAuthSessionsInput, + Result: Schema.Struct({ sessionId: AuthSessionId }), + execute: ({ currentSessionId, revokedAt }) => + sql` + UPDATE auth_sessions + SET revoked_at = ${revokedAt} + WHERE session_id <> ${currentSessionId} + AND revoked_at IS NULL + RETURNING session_id AS "sessionId" + `, + }); + + const create: AuthSessionRepositoryShape["create"] = (input) => + createSessionRow(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthSessionRepository.create:query", + "AuthSessionRepository.create:encodeRequest", + ), + ), + ); + + const getById: AuthSessionRepositoryShape["getById"] = (input) => + getSessionRowById(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthSessionRepository.getById:query", + "AuthSessionRepository.getById:decodeRow", + ), + ), + Effect.flatMap((rowOption) => + Option.match(rowOption, { + onNone: () => Effect.succeed(Option.none()), + onSome: (row) => Effect.succeed(Option.some(toAuthSessionRecord(row))), + }), + ), + ); + + const listActive: AuthSessionRepositoryShape["listActive"] = (input) => + listActiveSessionRows(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthSessionRepository.listActive:query", + "AuthSessionRepository.listActive:decodeRows", + ), + ), + Effect.flatMap((rows) => Effect.succeed(rows.map((row) => toAuthSessionRecord(row)))), + ); + + const revoke: AuthSessionRepositoryShape["revoke"] = (input) => + revokeSessionRows(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthSessionRepository.revoke:query", + "AuthSessionRepository.revoke:decodeRows", + ), + ), + Effect.map((rows) => rows.length > 0), + ); + + const revokeAllExcept: AuthSessionRepositoryShape["revokeAllExcept"] = (input) => + revokeOtherSessionRows(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthSessionRepository.revokeAllExcept:query", + "AuthSessionRepository.revokeAllExcept:decodeRows", + ), + ), + Effect.map((rows) => rows.map((row) => row.sessionId)), + ); + + const setLastConnectedAt: AuthSessionRepositoryShape["setLastConnectedAt"] = (input) => + setLastConnectedAtRow(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthSessionRepository.setLastConnectedAt:query", + "AuthSessionRepository.setLastConnectedAt:encodeRequest", + ), + ), + ); + + return { + create, + getById, + listActive, + revoke, + revokeAllExcept, + setLastConnectedAt, + } satisfies AuthSessionRepositoryShape; +}); + +export const AuthSessionRepositoryLive = Layer.effect( + AuthSessionRepository, + makeAuthSessionRepository, +); diff --git a/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts b/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts index 249e9d1e36..80526986a7 100644 --- a/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts +++ b/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts @@ -21,18 +21,18 @@ layer("OrchestrationEventStore", (it) => { const appended = yield* eventStore.append({ type: "project.created", - eventId: EventId.makeUnsafe("evt-store-roundtrip"), + eventId: EventId.make("evt-store-roundtrip"), aggregateKind: "project", - aggregateId: ProjectId.makeUnsafe("project-roundtrip"), + aggregateId: ProjectId.make("project-roundtrip"), occurredAt: now, - commandId: CommandId.makeUnsafe("cmd-store-roundtrip"), + commandId: CommandId.make("cmd-store-roundtrip"), causationEventId: null, - correlationId: CommandId.makeUnsafe("cmd-store-roundtrip"), + correlationId: CommandId.make("cmd-store-roundtrip"), metadata: { adapterKey: "codex", }, payload: { - projectId: ProjectId.makeUnsafe("project-roundtrip"), + projectId: ProjectId.make("project-roundtrip"), title: "Roundtrip Project", workspaceRoot: "/tmp/project-roundtrip", defaultModelSelection: null, @@ -87,13 +87,13 @@ layer("OrchestrationEventStore", (it) => { metadata_json ) VALUES ( - ${EventId.makeUnsafe("evt-store-invalid-json")}, + ${EventId.make("evt-store-invalid-json")}, ${"project"}, - ${ProjectId.makeUnsafe("project-invalid-json")}, + ${ProjectId.make("project-invalid-json")}, ${0}, ${"project.created"}, ${now}, - ${CommandId.makeUnsafe("cmd-store-invalid-json")}, + ${CommandId.make("cmd-store-invalid-json")}, ${null}, ${null}, ${"server"}, diff --git a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts b/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts index b0e1774837..08bc248122 100644 --- a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts +++ b/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts @@ -24,7 +24,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => { const sql = yield* SqlClient.SqlClient; yield* projects.upsert({ - projectId: ProjectId.makeUnsafe("project-null-options"), + projectId: ProjectId.make("project-null-options"), title: "Null options project", workspaceRoot: "/tmp/project-null-options", defaultModelSelection: { @@ -58,7 +58,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => { ); const persisted = yield* projects.getById({ - projectId: ProjectId.makeUnsafe("project-null-options"), + projectId: ProjectId.make("project-null-options"), }); assert.deepStrictEqual(Option.getOrNull(persisted)?.defaultModelSelection, { provider: "codex", @@ -73,8 +73,8 @@ projectionRepositoriesLayer("Projection repositories", (it) => { const sql = yield* SqlClient.SqlClient; yield* threads.upsert({ - threadId: ThreadId.makeUnsafe("thread-null-options"), - projectId: ProjectId.makeUnsafe("project-null-options"), + threadId: ThreadId.make("thread-null-options"), + projectId: ProjectId.make("project-null-options"), title: "Null options thread", modelSelection: { provider: "claudeAgent", @@ -112,7 +112,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => { ); const persisted = yield* threads.getById({ - threadId: ThreadId.makeUnsafe("thread-null-options"), + threadId: ThreadId.make("thread-null-options"), }); assert.deepStrictEqual(Option.getOrNull(persisted)?.modelSelection, { provider: "claudeAgent", diff --git a/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts b/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts index b761387d47..8bbe723bf3 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts @@ -14,8 +14,8 @@ layer("ProjectionThreadMessageRepository", (it) => { it.effect("preserves existing attachments when upsert omits attachments", () => Effect.gen(function* () { const repository = yield* ProjectionThreadMessageRepository; - const threadId = ThreadId.makeUnsafe("thread-preserve-attachments"); - const messageId = MessageId.makeUnsafe("message-preserve-attachments"); + const threadId = ThreadId.make("thread-preserve-attachments"); + const messageId = MessageId.make("message-preserve-attachments"); const createdAt = "2026-02-28T19:00:00.000Z"; const updatedAt = "2026-02-28T19:00:01.000Z"; const persistedAttachments = [ @@ -55,14 +55,21 @@ layer("ProjectionThreadMessageRepository", (it) => { assert.equal(rows.length, 1); assert.equal(rows[0]?.text, "updated"); assert.deepEqual(rows[0]?.attachments, persistedAttachments); + + const rowById = yield* repository.getByMessageId({ messageId }); + assert.equal(rowById._tag, "Some"); + if (rowById._tag === "Some") { + assert.equal(rowById.value.text, "updated"); + assert.deepEqual(rowById.value.attachments, persistedAttachments); + } }), ); it.effect("allows explicit attachment clearing with an empty array", () => Effect.gen(function* () { const repository = yield* ProjectionThreadMessageRepository; - const threadId = ThreadId.makeUnsafe("thread-clear-attachments"); - const messageId = MessageId.makeUnsafe("message-clear-attachments"); + const threadId = ThreadId.make("thread-clear-attachments"); + const messageId = MessageId.make("message-clear-attachments"); const createdAt = "2026-02-28T19:10:00.000Z"; yield* repository.upsert({ diff --git a/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts b/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts index 6f0b25ddff..13b7086cec 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts @@ -1,10 +1,11 @@ import * as SqlClient from "effect/unstable/sql/SqlClient"; import * as SqlSchema from "effect/unstable/sql/SqlSchema"; -import { Effect, Layer, Schema, Struct } from "effect"; +import { Effect, Layer, Option, Schema, Struct } from "effect"; import { ChatAttachment } from "@t3tools/contracts"; import { toPersistenceSqlError } from "../Errors.ts"; import { + GetProjectionThreadMessageInput, ProjectionThreadMessageRepository, type ProjectionThreadMessageRepositoryShape, DeleteProjectionThreadMessagesInput, @@ -19,6 +20,22 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields( }), ); +function toProjectionThreadMessage( + row: Schema.Schema.Type, +): ProjectionThreadMessage { + return { + messageId: row.messageId, + threadId: row.threadId, + turnId: row.turnId, + role: row.role, + text: row.text, + isStreaming: row.isStreaming === 1, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + ...(row.attachments !== null ? { attachments: row.attachments } : {}), + }; +} + const makeProjectionThreadMessageRepository = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; @@ -74,6 +91,27 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { }, }); + const getProjectionThreadMessageRow = SqlSchema.findOneOption({ + Request: GetProjectionThreadMessageInput, + Result: ProjectionThreadMessageDbRowSchema, + execute: ({ messageId }) => + sql` + SELECT + message_id AS "messageId", + thread_id AS "threadId", + turn_id AS "turnId", + role, + text, + attachments_json AS "attachments", + is_streaming AS "isStreaming", + created_at AS "createdAt", + updated_at AS "updatedAt" + FROM projection_thread_messages + WHERE message_id = ${messageId} + LIMIT 1 + `, + }); + const listProjectionThreadMessageRows = SqlSchema.findAll({ Request: ListProjectionThreadMessagesInput, Result: ProjectionThreadMessageDbRowSchema, @@ -109,24 +147,20 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { Effect.mapError(toPersistenceSqlError("ProjectionThreadMessageRepository.upsert:query")), ); + const getByMessageId: ProjectionThreadMessageRepositoryShape["getByMessageId"] = (input) => + getProjectionThreadMessageRow(input).pipe( + Effect.mapError( + toPersistenceSqlError("ProjectionThreadMessageRepository.getByMessageId:query"), + ), + Effect.map(Option.map(toProjectionThreadMessage)), + ); + const listByThreadId: ProjectionThreadMessageRepositoryShape["listByThreadId"] = (input) => listProjectionThreadMessageRows(input).pipe( Effect.mapError( toPersistenceSqlError("ProjectionThreadMessageRepository.listByThreadId:query"), ), - Effect.map((rows) => - rows.map((row) => ({ - messageId: row.messageId, - threadId: row.threadId, - turnId: row.turnId, - role: row.role, - text: row.text, - isStreaming: row.isStreaming === 1, - createdAt: row.createdAt, - updatedAt: row.updatedAt, - ...(row.attachments !== null ? { attachments: row.attachments } : {}), - })), - ), + Effect.map((rows) => rows.map(toProjectionThreadMessage)), ); const deleteByThreadId: ProjectionThreadMessageRepositoryShape["deleteByThreadId"] = (input) => @@ -138,6 +172,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { return { upsert, + getByMessageId, listByThreadId, deleteByThreadId, } satisfies ProjectionThreadMessageRepositoryShape; diff --git a/apps/server/src/persistence/Layers/Sqlite.ts b/apps/server/src/persistence/Layers/Sqlite.ts index 2dddfc3bfa..58556099db 100644 --- a/apps/server/src/persistence/Layers/Sqlite.ts +++ b/apps/server/src/persistence/Layers/Sqlite.ts @@ -6,6 +6,7 @@ import { ServerConfig } from "../../config.ts"; type RuntimeSqliteLayerConfig = { readonly filename: string; + readonly spanAttributes?: Record; }; type Loader = { @@ -16,15 +17,14 @@ const defaultSqliteClientLoaders = { node: () => import("../NodeSqliteClient.ts"), } satisfies Record Promise>; -const makeRuntimeSqliteLayer = ( +const makeRuntimeSqliteLayer = Effect.fn("makeRuntimeSqliteLayer")(function* ( config: RuntimeSqliteLayerConfig, -): Layer.Layer => - Effect.gen(function* () { - const runtime = process.versions.bun !== undefined ? "bun" : "node"; - const loader = defaultSqliteClientLoaders[runtime]; - const clientModule = yield* Effect.promise(loader); - return clientModule.layer(config); - }).pipe(Layer.unwrap); +) { + const runtime = process.versions.bun !== undefined ? "bun" : "node"; + const loader = defaultSqliteClientLoaders[runtime]; + const clientModule = yield* Effect.promise(loader); + return clientModule.layer(config); +}, Layer.unwrap); const setup = Layer.effectDiscard( Effect.gen(function* () { @@ -35,14 +35,24 @@ const setup = Layer.effectDiscard( }), ); -export const makeSqlitePersistenceLive = (dbPath: string) => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true }); +export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")(function* ( + dbPath: string, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true }); - return Layer.provideMerge(setup, makeRuntimeSqliteLayer({ filename: dbPath })); - }).pipe(Layer.unwrap); + return Layer.provideMerge( + setup, + makeRuntimeSqliteLayer({ + filename: dbPath, + spanAttributes: { + "db.name": path.basename(dbPath), + "service.name": "t3-server", + }, + }), + ); +}, Layer.unwrap); export const SqlitePersistenceMemory = Layer.provideMerge( setup, diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index c759665f06..8c9fe4d9fd 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -31,6 +31,10 @@ 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"; +import Migration0019 from "./Migrations/019_ProjectionSnapshotLookupIndexes.ts"; +import Migration0020 from "./Migrations/020_AuthAccessManagement.ts"; +import Migration0021 from "./Migrations/021_AuthSessionClientMetadata.ts"; +import Migration0022 from "./Migrations/022_AuthSessionLastConnectedAt.ts"; /** * Migration loader with all migrations defined inline. @@ -61,6 +65,10 @@ export const migrationEntries = [ [16, "CanonicalizeModelSelections", Migration0016], [17, "ProjectionThreadsArchivedAt", Migration0017], [18, "ProjectionThreadsArchivedAtIndex", Migration0018], + [19, "ProjectionSnapshotLookupIndexes", Migration0019], + [20, "AuthAccessManagement", Migration0020], + [21, "AuthSessionClientMetadata", Migration0021], + [22, "AuthSessionLastConnectedAt", Migration0022], ] as const; export const makeMigrationLoader = (throughId?: number) => @@ -92,19 +100,20 @@ export interface RunMigrationsOptions { * * @returns Effect containing array of executed migrations */ -export const runMigrations = ({ toMigrationInclusive }: RunMigrationsOptions = {}) => - Effect.gen(function* () { - yield* Effect.log( - toMigrationInclusive === undefined - ? "Running all migrations..." - : `Running migrations 1 through ${toMigrationInclusive}...`, - ); - const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) }); - yield* Effect.log("Migrations ran successfully").pipe( - Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }), - ); - return executedMigrations; - }); +export const runMigrations = Effect.fn("runMigrations")(function* ({ + toMigrationInclusive, +}: RunMigrationsOptions = {}) { + yield* Effect.log( + toMigrationInclusive === undefined + ? "Running all migrations..." + : `Running migrations 1 through ${toMigrationInclusive}...`, + ); + const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) }); + yield* Effect.log("Migrations ran successfully").pipe( + Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }), + ); + return executedMigrations; +}); /** * Layer that runs migrations when the layer is built. diff --git a/apps/server/src/persistence/Migrations/019_ProjectionSnapshotLookupIndexes.test.ts b/apps/server/src/persistence/Migrations/019_ProjectionSnapshotLookupIndexes.test.ts new file mode 100644 index 0000000000..6207a9bcb6 --- /dev/null +++ b/apps/server/src/persistence/Migrations/019_ProjectionSnapshotLookupIndexes.test.ts @@ -0,0 +1,73 @@ +import { assert, it } from "@effect/vitest"; +import { Effect, Layer } from "effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; +import * as NodeSqliteClient from "../NodeSqliteClient.ts"; + +const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory())); + +layer("019_ProjectionSnapshotLookupIndexes", (it) => { + it.effect("creates indexes for targeted projection lookup filters", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* runMigrations({ toMigrationInclusive: 18 }); + yield* runMigrations({ toMigrationInclusive: 19 }); + + const projectIndexes = yield* sql<{ + readonly seq: number; + readonly name: string; + readonly unique: number; + readonly origin: string; + readonly partial: number; + }>` + PRAGMA index_list(projection_projects) + `; + assert.ok( + projectIndexes.some( + (index) => index.name === "idx_projection_projects_workspace_root_deleted_at", + ), + ); + + const projectIndexColumns = yield* sql<{ + readonly seqno: number; + readonly cid: number; + readonly name: string; + }>` + PRAGMA index_info('idx_projection_projects_workspace_root_deleted_at') + `; + assert.deepStrictEqual( + projectIndexColumns.map((column) => column.name), + ["workspace_root", "deleted_at"], + ); + + const threadIndexes = yield* sql<{ + readonly seq: number; + readonly name: string; + readonly unique: number; + readonly origin: string; + readonly partial: number; + }>` + PRAGMA index_list(projection_threads) + `; + assert.ok( + threadIndexes.some( + (index) => index.name === "idx_projection_threads_project_deleted_created", + ), + ); + + const threadIndexColumns = yield* sql<{ + readonly seqno: number; + readonly cid: number; + readonly name: string; + }>` + PRAGMA index_info('idx_projection_threads_project_deleted_created') + `; + assert.deepStrictEqual( + threadIndexColumns.map((column) => column.name), + ["project_id", "deleted_at", "created_at"], + ); + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/019_ProjectionSnapshotLookupIndexes.ts b/apps/server/src/persistence/Migrations/019_ProjectionSnapshotLookupIndexes.ts new file mode 100644 index 0000000000..bf74a5147d --- /dev/null +++ b/apps/server/src/persistence/Migrations/019_ProjectionSnapshotLookupIndexes.ts @@ -0,0 +1,16 @@ +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_projects_workspace_root_deleted_at + ON projection_projects(workspace_root, deleted_at) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_projection_threads_project_deleted_created + ON projection_threads(project_id, deleted_at, created_at) + `; +}); diff --git a/apps/server/src/persistence/Migrations/020_AuthAccessManagement.ts b/apps/server/src/persistence/Migrations/020_AuthAccessManagement.ts new file mode 100644 index 0000000000..1be7fa80ff --- /dev/null +++ b/apps/server/src/persistence/Migrations/020_AuthAccessManagement.ts @@ -0,0 +1,42 @@ +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 TABLE IF NOT EXISTS auth_pairing_links ( + id TEXT PRIMARY KEY, + credential TEXT NOT NULL UNIQUE, + method TEXT NOT NULL, + role TEXT NOT NULL, + subject TEXT NOT NULL, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + consumed_at TEXT, + revoked_at TEXT + ) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_auth_pairing_links_active + ON auth_pairing_links(revoked_at, consumed_at, expires_at) + `; + + yield* sql` + CREATE TABLE IF NOT EXISTS auth_sessions ( + session_id TEXT PRIMARY KEY, + subject TEXT NOT NULL, + role TEXT NOT NULL, + method TEXT NOT NULL, + issued_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + revoked_at TEXT + ) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_auth_sessions_active + ON auth_sessions(revoked_at, expires_at, issued_at) + `; +}); diff --git a/apps/server/src/persistence/Migrations/021_AuthSessionClientMetadata.ts b/apps/server/src/persistence/Migrations/021_AuthSessionClientMetadata.ts new file mode 100644 index 0000000000..3b387fdcfd --- /dev/null +++ b/apps/server/src/persistence/Migrations/021_AuthSessionClientMetadata.ts @@ -0,0 +1,62 @@ +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 pairingLinkColumns = yield* sql<{ readonly name: string }>` + PRAGMA table_info(auth_pairing_links) + `; + if (!pairingLinkColumns.some((column) => column.name === "label")) { + yield* sql` + ALTER TABLE auth_pairing_links + ADD COLUMN label TEXT + `; + } + + const sessionColumns = yield* sql<{ readonly name: string }>` + PRAGMA table_info(auth_sessions) + `; + + if (!sessionColumns.some((column) => column.name === "client_label")) { + yield* sql` + ALTER TABLE auth_sessions + ADD COLUMN client_label TEXT + `; + } + + if (!sessionColumns.some((column) => column.name === "client_ip_address")) { + yield* sql` + ALTER TABLE auth_sessions + ADD COLUMN client_ip_address TEXT + `; + } + + if (!sessionColumns.some((column) => column.name === "client_user_agent")) { + yield* sql` + ALTER TABLE auth_sessions + ADD COLUMN client_user_agent TEXT + `; + } + + if (!sessionColumns.some((column) => column.name === "client_device_type")) { + yield* sql` + ALTER TABLE auth_sessions + ADD COLUMN client_device_type TEXT NOT NULL DEFAULT 'unknown' + `; + } + + if (!sessionColumns.some((column) => column.name === "client_os")) { + yield* sql` + ALTER TABLE auth_sessions + ADD COLUMN client_os TEXT + `; + } + + if (!sessionColumns.some((column) => column.name === "client_browser")) { + yield* sql` + ALTER TABLE auth_sessions + ADD COLUMN client_browser TEXT + `; + } +}); diff --git a/apps/server/src/persistence/Migrations/022_AuthSessionLastConnectedAt.ts b/apps/server/src/persistence/Migrations/022_AuthSessionLastConnectedAt.ts new file mode 100644 index 0000000000..e806a073a5 --- /dev/null +++ b/apps/server/src/persistence/Migrations/022_AuthSessionLastConnectedAt.ts @@ -0,0 +1,17 @@ +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 sessionColumns = yield* sql<{ readonly name: string }>` + PRAGMA table_info(auth_sessions) + `; + + if (!sessionColumns.some((column) => column.name === "last_connected_at")) { + yield* sql` + ALTER TABLE auth_sessions + ADD COLUMN last_connected_at TEXT + `; + } +}); diff --git a/apps/server/src/persistence/NodeSqliteClient.ts b/apps/server/src/persistence/NodeSqliteClient.ts index 78dbe8a1a9..631df9c8b9 100644 --- a/apps/server/src/persistence/NodeSqliteClient.ts +++ b/apps/server/src/persistence/NodeSqliteClient.ts @@ -15,7 +15,7 @@ import { identity } from "effect/Function"; import * as Layer from "effect/Layer"; import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; -import * as ServiceMap from "effect/ServiceMap"; +import * as Context from "effect/Context"; import * as Stream from "effect/Stream"; import * as Reactivity from "effect/unstable/reactivity/Reactivity"; import * as Client from "effect/unstable/sql/SqlClient"; @@ -32,7 +32,7 @@ export type TypeId = "~local/sqlite-node/SqliteClient"; /** * SqliteClient - Effect service tag for the sqlite SQL client. */ -export const SqliteClient = ServiceMap.Service("t3/persistence/NodeSqliteClient"); +export const SqliteClient = Context.Service("t3/persistence/NodeSqliteClient"); export interface SqliteClientConfig { readonly filename: string; @@ -72,160 +72,153 @@ const checkNodeSqliteCompat = () => { return Effect.void; }; -const makeWithDatabase = ( +const makeWithDatabase = Effect.fn("makeWithDatabase")(function* ( options: SqliteClientConfig, openDatabase: () => DatabaseSync, -): Effect.Effect => - Effect.gen(function* () { - yield* checkNodeSqliteCompat(); +): Effect.fn.Return { + yield* checkNodeSqliteCompat(); - const compiler = Statement.makeCompilerSqlite(options.transformQueryNames); - const transformRows = options.transformResultNames - ? Statement.defaultTransforms(options.transformResultNames).array - : undefined; + const compiler = Statement.makeCompilerSqlite(options.transformQueryNames); + const transformRows = options.transformResultNames + ? Statement.defaultTransforms(options.transformResultNames).array + : undefined; - const makeConnection = Effect.gen(function* () { - const scope = yield* Effect.scope; - const db = openDatabase(); - yield* Scope.addFinalizer( - scope, - Effect.sync(() => db.close()), - ); + const makeConnection = Effect.gen(function* () { + const scope = yield* Effect.scope; + const db = openDatabase(); + yield* Scope.addFinalizer( + scope, + Effect.sync(() => db.close()), + ); - const statementReaderCache = new WeakMap(); - const hasRows = (statement: StatementSync): boolean => { - const cached = statementReaderCache.get(statement); - if (cached !== undefined) { - return cached; - } - const value = statement.columns().length > 0; - statementReaderCache.set(statement, value); - return value; - }; + const statementReaderCache = new WeakMap(); + const hasRows = (statement: StatementSync): boolean => { + const cached = statementReaderCache.get(statement); + if (cached !== undefined) { + return cached; + } + const value = statement.columns().length > 0; + statementReaderCache.set(statement, value); + return value; + }; - const prepareCache = yield* Cache.make({ - capacity: options.prepareCacheSize ?? 200, - timeToLive: options.prepareCacheTTL ?? Duration.minutes(10), - lookup: (sql: string) => - Effect.try({ - try: () => db.prepare(sql), - catch: (cause) => - new SqlError({ - reason: classifySqliteError(cause, { - message: "Failed to prepare statement", - operation: "prepare", - }), + const prepareCache = yield* Cache.make({ + capacity: options.prepareCacheSize ?? 200, + timeToLive: options.prepareCacheTTL ?? Duration.minutes(10), + lookup: (sql: string) => + Effect.try({ + try: () => db.prepare(sql), + catch: (cause) => + new SqlError({ + reason: classifySqliteError(cause, { + message: "Failed to prepare statement", + operation: "prepare", }), - }), + }), + }), + }); + + const runStatement = (statement: StatementSync, params: ReadonlyArray, raw: boolean) => + Effect.withFiber, SqlError>((fiber) => { + statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers))); + try { + if (hasRows(statement)) { + return Effect.succeed(statement.all(...(params as any))); + } + const result = statement.run(...(params as any)); + return Effect.succeed(raw ? (result as unknown as ReadonlyArray) : []); + } catch (cause) { + return Effect.fail( + new SqlError({ + reason: classifySqliteError(cause, { + message: "Failed to execute statement", + operation: "execute", + }), + }), + ); + } }); - const runStatement = ( - statement: StatementSync, - params: ReadonlyArray, - raw: boolean, - ) => - Effect.withFiber, SqlError>((fiber) => { - statement.setReadBigInts(Boolean(ServiceMap.get(fiber.services, Client.SafeIntegers))); - try { - if (hasRows(statement)) { - return Effect.succeed(statement.all(...(params as any))); - } - const result = statement.run(...(params as any)); - return Effect.succeed(raw ? (result as unknown as ReadonlyArray) : []); - } catch (cause) { - return Effect.fail( + const run = (sql: string, params: ReadonlyArray, raw = false) => + Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw)); + + const runValues = (sql: string, params: ReadonlyArray) => + Effect.acquireUseRelease( + Cache.get(prepareCache, sql), + (statement) => + Effect.try({ + try: () => { + if (hasRows(statement)) { + statement.setReturnArrays(true); + // Safe to cast to array after we've setReturnArrays(true) + return statement.all(...(params as any)) as unknown as ReadonlyArray< + ReadonlyArray + >; + } + statement.run(...(params as any)); + return []; + }, + catch: (cause) => new SqlError({ reason: classifySqliteError(cause, { message: "Failed to execute statement", operation: "execute", }), }), - ); - } - }); - - const run = (sql: string, params: ReadonlyArray, raw = false) => - Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw)); - - const runValues = (sql: string, params: ReadonlyArray) => - Effect.acquireUseRelease( - Cache.get(prepareCache, sql), - (statement) => - Effect.try({ - try: () => { - if (hasRows(statement)) { - statement.setReturnArrays(true); - // Safe to cast to array after we've setReturnArrays(true) - return statement.all(...(params as any)) as unknown as ReadonlyArray< - ReadonlyArray - >; - } - statement.run(...(params as any)); - return []; - }, - catch: (cause) => - new SqlError({ - reason: classifySqliteError(cause, { - message: "Failed to execute statement", - operation: "execute", - }), - }), - }), - (statement) => - Effect.sync(() => { - if (hasRows(statement)) { - statement.setReturnArrays(false); - } - }), - ); - - return identity({ - execute(sql, params, rowTransform) { - return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params); - }, - executeRaw(sql, params) { - return run(sql, params, true); - }, - executeValues(sql, params) { - return runValues(sql, params); - }, - executeUnprepared(sql, params, rowTransform) { - const effect = runStatement(db.prepare(sql), params ?? [], false); - return rowTransform ? Effect.map(effect, rowTransform) : effect; - }, - executeStream(_sql, _params) { - return Stream.die("executeStream not implemented"); - }, - }); - }); - - const semaphore = yield* Semaphore.make(1); - const connection = yield* makeConnection; - - const acquirer = semaphore.withPermits(1)(Effect.succeed(connection)); - const transactionAcquirer = Effect.uninterruptibleMask((restore) => { - const fiber = Fiber.getCurrent()!; - const scope = ServiceMap.getUnsafe(fiber.services, Scope.Scope); - return Effect.as( - Effect.tap(restore(semaphore.take(1)), () => - Scope.addFinalizer(scope, semaphore.release(1)), - ), - connection, + }), + (statement) => + Effect.sync(() => { + if (hasRows(statement)) { + statement.setReturnArrays(false); + } + }), ); - }); - return yield* Client.make({ - acquirer, - compiler, - transactionAcquirer, - spanAttributes: [ - ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []), - [ATTR_DB_SYSTEM_NAME, "sqlite"], - ], - transformRows, + return identity({ + execute(sql, params, rowTransform) { + return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params); + }, + executeRaw(sql, params) { + return run(sql, params, true); + }, + executeValues(sql, params) { + return runValues(sql, params); + }, + executeUnprepared(sql, params, rowTransform) { + const effect = runStatement(db.prepare(sql), params ?? [], false); + return rowTransform ? Effect.map(effect, rowTransform) : effect; + }, + executeStream(_sql, _params) { + return Stream.die("executeStream not implemented"); + }, }); }); + const semaphore = yield* Semaphore.make(1); + const connection = yield* makeConnection; + + const acquirer = semaphore.withPermits(1)(Effect.succeed(connection)); + const transactionAcquirer = Effect.uninterruptibleMask((restore) => { + const fiber = Fiber.getCurrent()!; + const scope = Context.getUnsafe(fiber.context, Scope.Scope); + return Effect.as( + Effect.tap(restore(semaphore.take(1)), () => Scope.addFinalizer(scope, semaphore.release(1))), + connection, + ); + }); + + return yield* Client.make({ + acquirer, + compiler, + transactionAcquirer, + spanAttributes: [ + ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []), + [ATTR_DB_SYSTEM_NAME, "sqlite"], + ], + transformRows, + }); +}); + const make = ( options: SqliteClientConfig, ): Effect.Effect => @@ -258,27 +251,27 @@ const makeMemory = ( export const layerConfig = ( config: Config.Wrap, ): Layer.Layer => - Layer.effectServices( + Layer.effectContext( Config.unwrap(config) .asEffect() .pipe( Effect.flatMap(make), Effect.map((client) => - ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)), + Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)), ), ), ).pipe(Layer.provide(Reactivity.layer)); export const layer = (config: SqliteClientConfig): Layer.Layer => - Layer.effectServices( + Layer.effectContext( Effect.map(make(config), (client) => - ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)), + Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)), ), ).pipe(Layer.provide(Reactivity.layer)); export const layerMemory = (config: SqliteMemoryClientConfig = {}): Layer.Layer => - Layer.effectServices( + Layer.effectContext( Effect.map(makeMemory(config), (client) => - ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)), + Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)), ), ).pipe(Layer.provide(Reactivity.layer)); diff --git a/apps/server/src/persistence/Services/AuthPairingLinks.ts b/apps/server/src/persistence/Services/AuthPairingLinks.ts new file mode 100644 index 0000000000..d03e67cbb5 --- /dev/null +++ b/apps/server/src/persistence/Services/AuthPairingLinks.ts @@ -0,0 +1,76 @@ +import { Option, Schema, Context } from "effect"; +import type { Effect } from "effect"; + +import type { AuthPairingLinkRepositoryError } from "../Errors.ts"; + +export const AuthPairingLinkRecord = Schema.Struct({ + id: Schema.String, + credential: Schema.String, + method: Schema.Literals(["desktop-bootstrap", "one-time-token"]), + role: Schema.Literals(["owner", "client"]), + subject: Schema.String, + label: Schema.NullOr(Schema.String), + createdAt: Schema.DateTimeUtcFromString, + expiresAt: Schema.DateTimeUtcFromString, + consumedAt: Schema.NullOr(Schema.DateTimeUtcFromString), + revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString), +}); +export type AuthPairingLinkRecord = typeof AuthPairingLinkRecord.Type; + +export const CreateAuthPairingLinkInput = Schema.Struct({ + id: Schema.String, + credential: Schema.String, + method: Schema.Literals(["desktop-bootstrap", "one-time-token"]), + role: Schema.Literals(["owner", "client"]), + subject: Schema.String, + label: Schema.NullOr(Schema.String), + createdAt: Schema.DateTimeUtcFromString, + expiresAt: Schema.DateTimeUtcFromString, +}); +export type CreateAuthPairingLinkInput = typeof CreateAuthPairingLinkInput.Type; + +export const ConsumeAuthPairingLinkInput = Schema.Struct({ + credential: Schema.String, + consumedAt: Schema.DateTimeUtcFromString, + now: Schema.DateTimeUtcFromString, +}); +export type ConsumeAuthPairingLinkInput = typeof ConsumeAuthPairingLinkInput.Type; + +export const ListActiveAuthPairingLinksInput = Schema.Struct({ + now: Schema.DateTimeUtcFromString, +}); +export type ListActiveAuthPairingLinksInput = typeof ListActiveAuthPairingLinksInput.Type; + +export const RevokeAuthPairingLinkInput = Schema.Struct({ + id: Schema.String, + revokedAt: Schema.DateTimeUtcFromString, +}); +export type RevokeAuthPairingLinkInput = typeof RevokeAuthPairingLinkInput.Type; + +export const GetAuthPairingLinkByCredentialInput = Schema.Struct({ + credential: Schema.String, +}); +export type GetAuthPairingLinkByCredentialInput = typeof GetAuthPairingLinkByCredentialInput.Type; + +export interface AuthPairingLinkRepositoryShape { + readonly create: ( + input: CreateAuthPairingLinkInput, + ) => Effect.Effect; + readonly consumeAvailable: ( + input: ConsumeAuthPairingLinkInput, + ) => Effect.Effect, AuthPairingLinkRepositoryError>; + readonly listActive: ( + input: ListActiveAuthPairingLinksInput, + ) => Effect.Effect, AuthPairingLinkRepositoryError>; + readonly revoke: ( + input: RevokeAuthPairingLinkInput, + ) => Effect.Effect; + readonly getByCredential: ( + input: GetAuthPairingLinkByCredentialInput, + ) => Effect.Effect, AuthPairingLinkRepositoryError>; +} + +export class AuthPairingLinkRepository extends Context.Service< + AuthPairingLinkRepository, + AuthPairingLinkRepositoryShape +>()("t3/persistence/Services/AuthPairingLinks/AuthPairingLinkRepository") {} diff --git a/apps/server/src/persistence/Services/AuthSessions.ts b/apps/server/src/persistence/Services/AuthSessions.ts new file mode 100644 index 0000000000..567d3cca5c --- /dev/null +++ b/apps/server/src/persistence/Services/AuthSessions.ts @@ -0,0 +1,93 @@ +import { AuthClientMetadataDeviceType, AuthSessionId } from "@t3tools/contracts"; +import { Option, Schema, Context } from "effect"; +import type { Effect } from "effect"; + +import type { AuthSessionRepositoryError } from "../Errors.ts"; + +export const AuthSessionClientMetadataRecord = Schema.Struct({ + label: Schema.NullOr(Schema.String), + ipAddress: Schema.NullOr(Schema.String), + userAgent: Schema.NullOr(Schema.String), + deviceType: AuthClientMetadataDeviceType, + os: Schema.NullOr(Schema.String), + browser: Schema.NullOr(Schema.String), +}); +export type AuthSessionClientMetadataRecord = typeof AuthSessionClientMetadataRecord.Type; + +export const AuthSessionRecord = Schema.Struct({ + sessionId: AuthSessionId, + subject: Schema.String, + role: Schema.Literals(["owner", "client"]), + method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]), + client: AuthSessionClientMetadataRecord, + issuedAt: Schema.DateTimeUtcFromString, + expiresAt: Schema.DateTimeUtcFromString, + lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString), + revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString), +}); +export type AuthSessionRecord = typeof AuthSessionRecord.Type; + +export const CreateAuthSessionInput = Schema.Struct({ + sessionId: AuthSessionId, + subject: Schema.String, + role: Schema.Literals(["owner", "client"]), + method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]), + client: AuthSessionClientMetadataRecord, + issuedAt: Schema.DateTimeUtcFromString, + expiresAt: Schema.DateTimeUtcFromString, +}); +export type CreateAuthSessionInput = typeof CreateAuthSessionInput.Type; + +export const GetAuthSessionByIdInput = Schema.Struct({ + sessionId: AuthSessionId, +}); +export type GetAuthSessionByIdInput = typeof GetAuthSessionByIdInput.Type; + +export const ListActiveAuthSessionsInput = Schema.Struct({ + now: Schema.DateTimeUtcFromString, +}); +export type ListActiveAuthSessionsInput = typeof ListActiveAuthSessionsInput.Type; + +export const RevokeAuthSessionInput = Schema.Struct({ + sessionId: AuthSessionId, + revokedAt: Schema.DateTimeUtcFromString, +}); +export type RevokeAuthSessionInput = typeof RevokeAuthSessionInput.Type; + +export const RevokeOtherAuthSessionsInput = Schema.Struct({ + currentSessionId: AuthSessionId, + revokedAt: Schema.DateTimeUtcFromString, +}); +export type RevokeOtherAuthSessionsInput = typeof RevokeOtherAuthSessionsInput.Type; + +export const SetAuthSessionLastConnectedAtInput = Schema.Struct({ + sessionId: AuthSessionId, + lastConnectedAt: Schema.DateTimeUtcFromString, +}); +export type SetAuthSessionLastConnectedAtInput = typeof SetAuthSessionLastConnectedAtInput.Type; + +export interface AuthSessionRepositoryShape { + readonly create: ( + input: CreateAuthSessionInput, + ) => Effect.Effect; + readonly getById: ( + input: GetAuthSessionByIdInput, + ) => Effect.Effect, AuthSessionRepositoryError>; + readonly listActive: ( + input: ListActiveAuthSessionsInput, + ) => Effect.Effect, AuthSessionRepositoryError>; + readonly revoke: ( + input: RevokeAuthSessionInput, + ) => Effect.Effect; + readonly revokeAllExcept: ( + input: RevokeOtherAuthSessionsInput, + ) => Effect.Effect, AuthSessionRepositoryError>; + readonly setLastConnectedAt: ( + input: SetAuthSessionLastConnectedAtInput, + ) => Effect.Effect; +} + +export class AuthSessionRepository extends Context.Service< + AuthSessionRepository, + AuthSessionRepositoryShape +>()("t3/persistence/Services/AuthSessions/AuthSessionRepository") {} diff --git a/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts b/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts index 0b8f8e9b52..da8755ae71 100644 --- a/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts +++ b/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts @@ -15,7 +15,7 @@ import { ProjectId, ThreadId, } from "@t3tools/contracts"; -import { Option, Schema, ServiceMap } from "effect"; +import { Option, Schema, Context } from "effect"; import type { Effect } from "effect"; import type { OrchestrationCommandReceiptRepositoryError } from "../Errors.ts"; @@ -63,7 +63,7 @@ export interface OrchestrationCommandReceiptRepositoryShape { /** * OrchestrationCommandReceiptRepository - Service tag for command receipt persistence. */ -export class OrchestrationCommandReceiptRepository extends ServiceMap.Service< +export class OrchestrationCommandReceiptRepository extends Context.Service< OrchestrationCommandReceiptRepository, OrchestrationCommandReceiptRepositoryShape >()("t3/persistence/Services/OrchestrationCommandReceipts/OrchestrationCommandReceiptRepository") {} diff --git a/apps/server/src/persistence/Services/OrchestrationEventStore.ts b/apps/server/src/persistence/Services/OrchestrationEventStore.ts index 24febd8fde..beecdcdc65 100644 --- a/apps/server/src/persistence/Services/OrchestrationEventStore.ts +++ b/apps/server/src/persistence/Services/OrchestrationEventStore.ts @@ -4,13 +4,13 @@ * Owns durable append/replay access to the orchestration event stream. It does * not reduce events into read models or apply command validation rules. * - * Uses Effect `ServiceMap.Service` for dependency injection and exposes typed + * Uses Effect `Context.Service` for dependency injection and exposes typed * persistence/decode errors for event append and replay operations. * * @module OrchestrationEventStore */ import { OrchestrationEvent } from "@t3tools/contracts"; -import { ServiceMap } from "effect"; +import { Context } from "effect"; import type { Effect, Stream } from "effect"; import type { OrchestrationEventStoreError } from "../Errors.ts"; @@ -64,7 +64,7 @@ export interface OrchestrationEventStoreShape { * }) * ``` */ -export class OrchestrationEventStore extends ServiceMap.Service< +export class OrchestrationEventStore extends Context.Service< OrchestrationEventStore, OrchestrationEventStoreShape >()("t3/persistence/Services/OrchestrationEventStore") {} diff --git a/apps/server/src/persistence/Services/ProjectionCheckpoints.ts b/apps/server/src/persistence/Services/ProjectionCheckpoints.ts index 191d0af968..617f964f33 100644 --- a/apps/server/src/persistence/Services/ProjectionCheckpoints.ts +++ b/apps/server/src/persistence/Services/ProjectionCheckpoints.ts @@ -16,7 +16,7 @@ import { ThreadId, TurnId, } from "@t3tools/contracts"; -import { Option, ServiceMap, Schema } from "effect"; +import { Option, Context, Schema } from "effect"; import type { Effect } from "effect"; import type { ProjectionRepositoryError } from "../Errors.ts"; @@ -87,7 +87,7 @@ export interface ProjectionCheckpointRepositoryShape { /** * ProjectionCheckpointRepository - Service tag for checkpoint projection persistence. */ -export class ProjectionCheckpointRepository extends ServiceMap.Service< +export class ProjectionCheckpointRepository extends Context.Service< ProjectionCheckpointRepository, ProjectionCheckpointRepositoryShape >()("t3/persistence/Services/ProjectionCheckpoints/ProjectionCheckpointRepository") {} diff --git a/apps/server/src/persistence/Services/ProjectionPendingApprovals.ts b/apps/server/src/persistence/Services/ProjectionPendingApprovals.ts index 8f4ec5eb4b..82c43c0bb0 100644 --- a/apps/server/src/persistence/Services/ProjectionPendingApprovals.ts +++ b/apps/server/src/persistence/Services/ProjectionPendingApprovals.ts @@ -14,7 +14,7 @@ import { ThreadId, TurnId, } from "@t3tools/contracts"; -import { Option, Schema, ServiceMap } from "effect"; +import { Option, Schema, Context } from "effect"; import type { Effect } from "effect"; import type { ProjectionRepositoryError } from "../Errors.ts"; @@ -85,7 +85,7 @@ export interface ProjectionPendingApprovalRepositoryShape { /** * ProjectionPendingApprovalRepository - Service tag for pending approval persistence. */ -export class ProjectionPendingApprovalRepository extends ServiceMap.Service< +export class ProjectionPendingApprovalRepository extends Context.Service< ProjectionPendingApprovalRepository, ProjectionPendingApprovalRepositoryShape >()("t3/persistence/Services/ProjectionPendingApprovals/ProjectionPendingApprovalRepository") {} diff --git a/apps/server/src/persistence/Services/ProjectionProjects.ts b/apps/server/src/persistence/Services/ProjectionProjects.ts index 996ffe6e7b..0970bb2ead 100644 --- a/apps/server/src/persistence/Services/ProjectionProjects.ts +++ b/apps/server/src/persistence/Services/ProjectionProjects.ts @@ -7,7 +7,7 @@ * @module ProjectionProjectRepository */ import { IsoDateTime, ModelSelection, ProjectId, ProjectScript } from "@t3tools/contracts"; -import { Option, Schema, ServiceMap } from "effect"; +import { Option, Schema, Context } from "effect"; import type { Effect } from "effect"; import type { ProjectionRepositoryError } from "../Errors.ts"; @@ -73,7 +73,7 @@ export interface ProjectionProjectRepositoryShape { /** * ProjectionProjectRepository - Service tag for project projection persistence. */ -export class ProjectionProjectRepository extends ServiceMap.Service< +export class ProjectionProjectRepository extends Context.Service< ProjectionProjectRepository, ProjectionProjectRepositoryShape >()("t3/persistence/Services/ProjectionProjects/ProjectionProjectRepository") {} diff --git a/apps/server/src/persistence/Services/ProjectionState.ts b/apps/server/src/persistence/Services/ProjectionState.ts index e8ef9ceeb0..0b75b817d2 100644 --- a/apps/server/src/persistence/Services/ProjectionState.ts +++ b/apps/server/src/persistence/Services/ProjectionState.ts @@ -7,7 +7,7 @@ * @module ProjectionStateRepository */ import { IsoDateTime, NonNegativeInt } from "@t3tools/contracts"; -import { Option, Schema, ServiceMap } from "effect"; +import { Option, Schema, Context } from "effect"; import type { Effect } from "effect"; import type { ProjectionRepositoryError } from "../Errors.ts"; @@ -58,7 +58,7 @@ export interface ProjectionStateRepositoryShape { /** * ProjectionStateRepository - Service tag for projection cursor persistence. */ -export class ProjectionStateRepository extends ServiceMap.Service< +export class ProjectionStateRepository extends Context.Service< ProjectionStateRepository, ProjectionStateRepositoryShape >()("t3/persistence/Services/ProjectionState/ProjectionStateRepository") {} diff --git a/apps/server/src/persistence/Services/ProjectionThreadActivities.ts b/apps/server/src/persistence/Services/ProjectionThreadActivities.ts index 586ae3eb4a..87daa3c636 100644 --- a/apps/server/src/persistence/Services/ProjectionThreadActivities.ts +++ b/apps/server/src/persistence/Services/ProjectionThreadActivities.ts @@ -14,7 +14,7 @@ import { ThreadId, TurnId, } from "@t3tools/contracts"; -import { Schema, ServiceMap } from "effect"; +import { Schema, Context } from "effect"; import type { Effect } from "effect"; import type { ProjectionRepositoryError } from "../Errors.ts"; @@ -77,7 +77,7 @@ export interface ProjectionThreadActivityRepositoryShape { /** * ProjectionThreadActivityRepository - Service tag for thread activity persistence. */ -export class ProjectionThreadActivityRepository extends ServiceMap.Service< +export class ProjectionThreadActivityRepository extends Context.Service< ProjectionThreadActivityRepository, ProjectionThreadActivityRepositoryShape >()("t3/persistence/Services/ProjectionThreadActivities/ProjectionThreadActivityRepository") {} diff --git a/apps/server/src/persistence/Services/ProjectionThreadMessages.ts b/apps/server/src/persistence/Services/ProjectionThreadMessages.ts index 00b1d399c6..56f8f92dbf 100644 --- a/apps/server/src/persistence/Services/ProjectionThreadMessages.ts +++ b/apps/server/src/persistence/Services/ProjectionThreadMessages.ts @@ -8,13 +8,14 @@ */ import { ChatAttachment, - OrchestrationMessageRole, MessageId, + OrchestrationMessageRole, ThreadId, TurnId, IsoDateTime, } from "@t3tools/contracts"; -import { Schema, ServiceMap } from "effect"; +import { Schema, Context } from "effect"; +import type { Option } from "effect"; import type { Effect } from "effect"; import type { ProjectionRepositoryError } from "../Errors.ts"; @@ -37,6 +38,11 @@ export const ListProjectionThreadMessagesInput = Schema.Struct({ }); export type ListProjectionThreadMessagesInput = typeof ListProjectionThreadMessagesInput.Type; +export const GetProjectionThreadMessageInput = Schema.Struct({ + messageId: MessageId, +}); +export type GetProjectionThreadMessageInput = typeof GetProjectionThreadMessageInput.Type; + export const DeleteProjectionThreadMessagesInput = Schema.Struct({ threadId: ThreadId, }); @@ -55,6 +61,13 @@ export interface ProjectionThreadMessageRepositoryShape { message: ProjectionThreadMessage, ) => Effect.Effect; + /** + * Read a projected thread message by id. + */ + readonly getByMessageId: ( + input: GetProjectionThreadMessageInput, + ) => Effect.Effect, ProjectionRepositoryError>; + /** * List projected thread messages for a thread. * @@ -75,7 +88,7 @@ export interface ProjectionThreadMessageRepositoryShape { /** * ProjectionThreadMessageRepository - Service tag for message projection persistence. */ -export class ProjectionThreadMessageRepository extends ServiceMap.Service< +export class ProjectionThreadMessageRepository extends Context.Service< ProjectionThreadMessageRepository, ProjectionThreadMessageRepositoryShape >()("t3/persistence/Services/ProjectionThreadMessages/ProjectionThreadMessageRepository") {} diff --git a/apps/server/src/persistence/Services/ProjectionThreadProposedPlans.ts b/apps/server/src/persistence/Services/ProjectionThreadProposedPlans.ts index d141a11bb9..a68bedb8c3 100644 --- a/apps/server/src/persistence/Services/ProjectionThreadProposedPlans.ts +++ b/apps/server/src/persistence/Services/ProjectionThreadProposedPlans.ts @@ -5,7 +5,7 @@ import { TrimmedNonEmptyString, TurnId, } from "@t3tools/contracts"; -import { Schema, ServiceMap } from "effect"; +import { Schema, Context } from "effect"; import type { Effect } from "effect"; import type { ProjectionRepositoryError } from "../Errors.ts"; @@ -46,7 +46,7 @@ export interface ProjectionThreadProposedPlanRepositoryShape { ) => Effect.Effect; } -export class ProjectionThreadProposedPlanRepository extends ServiceMap.Service< +export class ProjectionThreadProposedPlanRepository extends Context.Service< ProjectionThreadProposedPlanRepository, ProjectionThreadProposedPlanRepositoryShape >()( diff --git a/apps/server/src/persistence/Services/ProjectionThreadSessions.ts b/apps/server/src/persistence/Services/ProjectionThreadSessions.ts index 537ee10bee..fcd13f068d 100644 --- a/apps/server/src/persistence/Services/ProjectionThreadSessions.ts +++ b/apps/server/src/persistence/Services/ProjectionThreadSessions.ts @@ -13,7 +13,7 @@ import { ThreadId, TurnId, } from "@t3tools/contracts"; -import { Option, Schema, ServiceMap } from "effect"; +import { Option, Schema, Context } from "effect"; import type { Effect } from "effect"; import type { ProjectionRepositoryError } from "../Errors.ts"; @@ -68,7 +68,7 @@ export interface ProjectionThreadSessionRepositoryShape { /** * ProjectionThreadSessionRepository - Service tag for thread-session persistence. */ -export class ProjectionThreadSessionRepository extends ServiceMap.Service< +export class ProjectionThreadSessionRepository extends Context.Service< ProjectionThreadSessionRepository, ProjectionThreadSessionRepositoryShape >()("t3/persistence/Services/ProjectionThreadSessions/ProjectionThreadSessionRepository") {} diff --git a/apps/server/src/persistence/Services/ProjectionThreads.ts b/apps/server/src/persistence/Services/ProjectionThreads.ts index 59505c1253..31ec00a6e5 100644 --- a/apps/server/src/persistence/Services/ProjectionThreads.ts +++ b/apps/server/src/persistence/Services/ProjectionThreads.ts @@ -15,7 +15,7 @@ import { ThreadId, TurnId, } from "@t3tools/contracts"; -import { Option, Schema, ServiceMap } from "effect"; +import { Option, Schema, Context } from "effect"; import type { Effect } from "effect"; import type { ProjectionRepositoryError } from "../Errors.ts"; @@ -90,7 +90,7 @@ export interface ProjectionThreadRepositoryShape { /** * ProjectionThreadRepository - Service tag for thread projection persistence. */ -export class ProjectionThreadRepository extends ServiceMap.Service< +export class ProjectionThreadRepository extends Context.Service< ProjectionThreadRepository, ProjectionThreadRepositoryShape >()("t3/persistence/Services/ProjectionThreads/ProjectionThreadRepository") {} diff --git a/apps/server/src/persistence/Services/ProjectionTurns.ts b/apps/server/src/persistence/Services/ProjectionTurns.ts index 95dab450bf..8e37ae09bd 100644 --- a/apps/server/src/persistence/Services/ProjectionTurns.ts +++ b/apps/server/src/persistence/Services/ProjectionTurns.ts @@ -17,7 +17,7 @@ import { ThreadId, TurnId, } from "@t3tools/contracts"; -import { Option, Schema, ServiceMap } from "effect"; +import { Option, Schema, Context } from "effect"; import type { Effect } from "effect"; import type { ProjectionRepositoryError } from "../Errors.ts"; @@ -162,7 +162,7 @@ export interface ProjectionTurnRepositoryShape { ) => Effect.Effect; } -export class ProjectionTurnRepository extends ServiceMap.Service< +export class ProjectionTurnRepository extends Context.Service< ProjectionTurnRepository, ProjectionTurnRepositoryShape >()("t3/persistence/Services/ProjectionTurns/ProjectionTurnRepository") {} diff --git a/apps/server/src/persistence/Services/ProviderSessionRuntime.ts b/apps/server/src/persistence/Services/ProviderSessionRuntime.ts index 885a9dd5f1..bf8e658e8a 100644 --- a/apps/server/src/persistence/Services/ProviderSessionRuntime.ts +++ b/apps/server/src/persistence/Services/ProviderSessionRuntime.ts @@ -11,7 +11,7 @@ import { RuntimeMode, ThreadId, } from "@t3tools/contracts"; -import { Option, Schema, ServiceMap } from "effect"; +import { Option, Schema, Context } from "effect"; import type { Effect } from "effect"; import type { ProviderSessionRuntimeRepositoryError } from "../Errors.ts"; @@ -75,7 +75,7 @@ export interface ProviderSessionRuntimeRepositoryShape { /** * ProviderSessionRuntimeRepository - Service tag for provider runtime persistence. */ -export class ProviderSessionRuntimeRepository extends ServiceMap.Service< +export class ProviderSessionRuntimeRepository extends Context.Service< ProviderSessionRuntimeRepository, ProviderSessionRuntimeRepositoryShape >()("t3/persistence/Services/ProviderSessionRuntime/ProviderSessionRuntimeRepository") {} diff --git a/apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts new file mode 100644 index 0000000000..6366a768b7 --- /dev/null +++ b/apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts @@ -0,0 +1,166 @@ +import { Effect, Layer, Stream } from "effect"; +import { describe, expect, it, vi } from "vitest"; +import type { OrchestrationReadModel } from "@t3tools/contracts"; + +import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts"; +import { TerminalManager } from "../../terminal/Services/Manager.ts"; +import { ProjectSetupScriptRunner } from "../Services/ProjectSetupScriptRunner.ts"; +import { ProjectSetupScriptRunnerLive } from "./ProjectSetupScriptRunner.ts"; + +const emptySnapshot = ( + scripts: OrchestrationReadModel["projects"][number]["scripts"], +): OrchestrationReadModel => + ({ + snapshotSequence: 1, + updatedAt: "2026-01-01T00:00:00.000Z", + projects: [ + { + id: "project-1", + title: "Project", + workspaceRoot: "/repo/project", + defaultModelSelection: null, + scripts, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + deletedAt: null, + }, + ], + threads: [], + providerSessions: [], + providerStatuses: [], + pendingApprovals: [], + latestTurnByThreadId: {}, + }) as unknown as OrchestrationReadModel; + +describe("ProjectSetupScriptRunner", () => { + it("returns no-script when no setup script exists", async () => { + const open = vi.fn(); + const write = vi.fn(); + const runner = await Effect.runPromise( + Effect.service(ProjectSetupScriptRunner).pipe( + Effect.provide( + ProjectSetupScriptRunnerLive.pipe( + Layer.provideMerge( + Layer.succeed(OrchestrationEngineService, { + getReadModel: () => Effect.succeed(emptySnapshot([])), + readEvents: () => Stream.empty, + dispatch: () => Effect.die(new Error("unused")), + streamDomainEvents: Stream.empty, + }), + ), + Layer.provideMerge( + Layer.succeed(TerminalManager, { + open, + write, + resize: () => Effect.void, + clear: () => Effect.void, + restart: () => Effect.die(new Error("unused")), + close: () => Effect.void, + subscribe: () => Effect.succeed(() => undefined), + }), + ), + ), + ), + ), + ); + + const result = await Effect.runPromise( + runner.runForThread({ + threadId: "thread-1", + projectId: "project-1", + worktreePath: "/repo/worktrees/a", + }), + ); + + expect(result).toEqual({ status: "no-script" }); + expect(open).not.toHaveBeenCalled(); + expect(write).not.toHaveBeenCalled(); + }); + + it("opens the deterministic setup terminal with worktree env and writes the command", async () => { + const open = vi.fn(() => + Effect.succeed({ + threadId: "thread-1", + terminalId: "setup-setup", + cwd: "/repo/worktrees/a", + worktreePath: "/repo/worktrees/a", + status: "running" as const, + pid: 123, + history: "", + exitCode: null, + exitSignal: null, + updatedAt: "2026-01-01T00:00:00.000Z", + }), + ); + const write = vi.fn(() => Effect.void); + const runner = await Effect.runPromise( + Effect.service(ProjectSetupScriptRunner).pipe( + Effect.provide( + ProjectSetupScriptRunnerLive.pipe( + Layer.provideMerge( + Layer.succeed(OrchestrationEngineService, { + getReadModel: () => + Effect.succeed( + emptySnapshot([ + { + id: "setup", + name: "Setup", + command: "bun install", + icon: "configure", + runOnWorktreeCreate: true, + }, + ]), + ), + readEvents: () => Stream.empty, + dispatch: () => Effect.die(new Error("unused")), + streamDomainEvents: Stream.empty, + }), + ), + Layer.provideMerge( + Layer.succeed(TerminalManager, { + open, + write, + resize: () => Effect.void, + clear: () => Effect.void, + restart: () => Effect.die(new Error("unused")), + close: () => Effect.void, + subscribe: () => Effect.succeed(() => undefined), + }), + ), + ), + ), + ), + ); + + const result = await Effect.runPromise( + runner.runForThread({ + threadId: "thread-1", + projectCwd: "/repo/project", + worktreePath: "/repo/worktrees/a", + }), + ); + + expect(result).toEqual({ + status: "started", + scriptId: "setup", + scriptName: "Setup", + terminalId: "setup-setup", + cwd: "/repo/worktrees/a", + }); + expect(open).toHaveBeenCalledWith({ + threadId: "thread-1", + terminalId: "setup-setup", + cwd: "/repo/worktrees/a", + worktreePath: "/repo/worktrees/a", + env: { + T3CODE_PROJECT_ROOT: "/repo/project", + T3CODE_WORKTREE_PATH: "/repo/worktrees/a", + }, + }); + expect(write).toHaveBeenCalledWith({ + threadId: "thread-1", + terminalId: "setup-setup", + data: "bun install\r", + }); + }); +}); diff --git a/apps/server/src/project/Layers/ProjectSetupScriptRunner.ts b/apps/server/src/project/Layers/ProjectSetupScriptRunner.ts new file mode 100644 index 0000000000..3bac8cf0ab --- /dev/null +++ b/apps/server/src/project/Layers/ProjectSetupScriptRunner.ts @@ -0,0 +1,75 @@ +import { projectScriptRuntimeEnv, setupProjectScript } from "@t3tools/shared/projectScripts"; +import { Effect, Layer } from "effect"; + +import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts"; +import { TerminalManager } from "../../terminal/Services/Manager.ts"; +import { + type ProjectSetupScriptRunnerShape, + ProjectSetupScriptRunner, +} from "../Services/ProjectSetupScriptRunner.ts"; + +const makeProjectSetupScriptRunner = Effect.gen(function* () { + const orchestrationEngine = yield* OrchestrationEngineService; + const terminalManager = yield* TerminalManager; + + const runForThread: ProjectSetupScriptRunnerShape["runForThread"] = (input) => + Effect.gen(function* () { + const readModel = yield* orchestrationEngine.getReadModel(); + const project = + (input.projectId + ? readModel.projects.find((entry) => entry.id === input.projectId) + : null) ?? + (input.projectCwd + ? readModel.projects.find((entry) => entry.workspaceRoot === input.projectCwd) + : null) ?? + null; + + if (!project) { + return yield* Effect.fail(new Error("Project was not found for setup script execution.")); + } + + const script = setupProjectScript(project.scripts); + if (!script) { + return { + status: "no-script", + } as const; + } + + const terminalId = input.preferredTerminalId ?? `setup-${script.id}`; + const cwd = input.worktreePath; + const env = projectScriptRuntimeEnv({ + project: { cwd: project.workspaceRoot }, + worktreePath: input.worktreePath, + }); + + yield* terminalManager.open({ + threadId: input.threadId, + terminalId, + cwd, + worktreePath: input.worktreePath, + env, + }); + yield* terminalManager.write({ + threadId: input.threadId, + terminalId, + data: `${script.command}\r`, + }); + + return { + status: "started", + scriptId: script.id, + scriptName: script.name, + terminalId, + cwd, + } as const; + }); + + return { + runForThread, + } satisfies ProjectSetupScriptRunnerShape; +}); + +export const ProjectSetupScriptRunnerLive = Layer.effect( + ProjectSetupScriptRunner, + makeProjectSetupScriptRunner, +); diff --git a/apps/server/src/project/Layers/RepositoryIdentityResolver.test.ts b/apps/server/src/project/Layers/RepositoryIdentityResolver.test.ts new file mode 100644 index 0000000000..57f4464804 --- /dev/null +++ b/apps/server/src/project/Layers/RepositoryIdentityResolver.test.ts @@ -0,0 +1,193 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { Duration, Effect, FileSystem, Layer } from "effect"; +import { TestClock } from "effect/testing"; + +import { runProcess } from "../../processRunner.ts"; +import { RepositoryIdentityResolver } from "../Services/RepositoryIdentityResolver.ts"; +import { + makeRepositoryIdentityResolver, + RepositoryIdentityResolverLive, +} from "./RepositoryIdentityResolver.ts"; + +const git = (cwd: string, args: ReadonlyArray) => + Effect.promise(() => runProcess("git", ["-C", cwd, ...args])); + +const makeRepositoryIdentityResolverTestLayer = (options: { + readonly positiveCacheTtl?: Duration.Input; + readonly negativeCacheTtl?: Duration.Input; +}) => + Layer.effect( + RepositoryIdentityResolver, + makeRepositoryIdentityResolver({ + cacheCapacity: 16, + ...options, + }), + ); + +it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => { + it.effect("normalizes equivalent GitHub remotes into a stable repository identity", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-test-", + }); + + yield* git(cwd, ["init"]); + yield* git(cwd, ["remote", "add", "origin", "git@github.com:T3Tools/t3code.git"]); + + const resolver = yield* RepositoryIdentityResolver; + const identity = yield* resolver.resolve(cwd); + + expect(identity).not.toBeNull(); + expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code"); + expect(identity?.displayName).toBe("t3tools/t3code"); + expect(identity?.provider).toBe("github"); + expect(identity?.owner).toBe("t3tools"); + expect(identity?.name).toBe("t3code"); + }).pipe(Effect.provide(RepositoryIdentityResolverLive)), + ); + + it.effect("returns null for non-git folders and repos without remotes", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const nonGitDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-non-git-", + }); + const gitDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-no-remote-", + }); + + yield* git(gitDir, ["init"]); + + const resolver = yield* RepositoryIdentityResolver; + const nonGitIdentity = yield* resolver.resolve(nonGitDir); + const noRemoteIdentity = yield* resolver.resolve(gitDir); + + expect(nonGitIdentity).toBeNull(); + expect(noRemoteIdentity).toBeNull(); + }).pipe(Effect.provide(RepositoryIdentityResolverLive)), + ); + + it.effect("prefers upstream over origin when both remotes are configured", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-upstream-test-", + }); + + yield* git(cwd, ["init"]); + yield* git(cwd, ["remote", "add", "origin", "git@github.com:julius/t3code.git"]); + yield* git(cwd, ["remote", "add", "upstream", "git@github.com:T3Tools/t3code.git"]); + + const resolver = yield* RepositoryIdentityResolver; + const identity = yield* resolver.resolve(cwd); + + expect(identity).not.toBeNull(); + expect(identity?.locator.remoteName).toBe("upstream"); + expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code"); + expect(identity?.displayName).toBe("t3tools/t3code"); + }).pipe(Effect.provide(RepositoryIdentityResolverLive)), + ); + + it.effect("uses the last remote path segment as the repository name for nested groups", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-nested-group-test-", + }); + + yield* git(cwd, ["init"]); + yield* git(cwd, ["remote", "add", "origin", "git@gitlab.com:T3Tools/platform/t3code.git"]); + + const resolver = yield* RepositoryIdentityResolver; + const identity = yield* resolver.resolve(cwd); + + expect(identity).not.toBeNull(); + expect(identity?.canonicalKey).toBe("gitlab.com/t3tools/platform/t3code"); + expect(identity?.displayName).toBe("t3tools/platform/t3code"); + expect(identity?.owner).toBe("t3tools"); + expect(identity?.name).toBe("t3code"); + }).pipe(Effect.provide(RepositoryIdentityResolverLive)), + ); + + it.effect( + "refreshes cached null identities after the negative TTL when a remote is configured later", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-late-remote-test-", + }); + + yield* git(cwd, ["init"]); + + const resolver = yield* RepositoryIdentityResolver; + const initialIdentity = yield* resolver.resolve(cwd); + expect(initialIdentity).toBeNull(); + + yield* git(cwd, ["remote", "add", "origin", "git@github.com:T3Tools/t3code.git"]); + + const cachedIdentity = yield* resolver.resolve(cwd); + expect(cachedIdentity).toBeNull(); + + yield* TestClock.adjust(Duration.millis(120)); + + const refreshedIdentity = yield* resolver.resolve(cwd); + expect(refreshedIdentity).not.toBeNull(); + expect(refreshedIdentity?.canonicalKey).toBe("github.com/t3tools/t3code"); + expect(refreshedIdentity?.name).toBe("t3code"); + }).pipe( + Effect.provide( + Layer.merge( + TestClock.layer(), + makeRepositoryIdentityResolverTestLayer({ + negativeCacheTtl: Duration.millis(50), + positiveCacheTtl: Duration.seconds(1), + }), + ), + ), + ), + ); + + it.effect("refreshes cached identities after the positive TTL when a remote changes", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-remote-change-test-", + }); + + yield* git(cwd, ["init"]); + yield* git(cwd, ["remote", "add", "origin", "git@github.com:T3Tools/t3code.git"]); + + const resolver = yield* RepositoryIdentityResolver; + const initialIdentity = yield* resolver.resolve(cwd); + expect(initialIdentity).not.toBeNull(); + expect(initialIdentity?.canonicalKey).toBe("github.com/t3tools/t3code"); + + yield* git(cwd, ["remote", "set-url", "origin", "git@github.com:T3Tools/t3code-next.git"]); + + const cachedIdentity = yield* resolver.resolve(cwd); + expect(cachedIdentity).not.toBeNull(); + expect(cachedIdentity?.canonicalKey).toBe("github.com/t3tools/t3code"); + + yield* TestClock.adjust(Duration.millis(180)); + + const refreshedIdentity = yield* resolver.resolve(cwd); + expect(refreshedIdentity).not.toBeNull(); + expect(refreshedIdentity?.canonicalKey).toBe("github.com/t3tools/t3code-next"); + expect(refreshedIdentity?.displayName).toBe("t3tools/t3code-next"); + expect(refreshedIdentity?.name).toBe("t3code-next"); + }).pipe( + Effect.provide( + Layer.merge( + TestClock.layer(), + makeRepositoryIdentityResolverTestLayer({ + negativeCacheTtl: Duration.millis(50), + positiveCacheTtl: Duration.millis(100), + }), + ), + ), + ), + ); +}); diff --git a/apps/server/src/project/Layers/RepositoryIdentityResolver.ts b/apps/server/src/project/Layers/RepositoryIdentityResolver.ts new file mode 100644 index 0000000000..531737ec66 --- /dev/null +++ b/apps/server/src/project/Layers/RepositoryIdentityResolver.ts @@ -0,0 +1,149 @@ +import type { RepositoryIdentity } from "@t3tools/contracts"; +import { Cache, Duration, Effect, Exit, Layer } from "effect"; +import { detectGitHostingProviderFromRemoteUrl, normalizeGitRemoteUrl } from "@t3tools/shared/git"; + +import { runProcess } from "../../processRunner.ts"; +import { + RepositoryIdentityResolver, + type RepositoryIdentityResolverShape, +} from "../Services/RepositoryIdentityResolver.ts"; + +function parseRemoteFetchUrls(stdout: string): Map { + const remotes = new Map(); + for (const line of stdout.split("\n")) { + const trimmed = line.trim(); + if (trimmed.length === 0) continue; + const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed); + if (!match) continue; + const [, remoteName = "", remoteUrl = "", direction = ""] = match; + if (direction !== "fetch" || remoteName.length === 0 || remoteUrl.length === 0) { + continue; + } + remotes.set(remoteName, remoteUrl); + } + return remotes; +} + +function pickPrimaryRemote( + remotes: ReadonlyMap, +): { readonly remoteName: string; readonly remoteUrl: string } | null { + for (const preferredRemoteName of ["upstream", "origin"] as const) { + const remoteUrl = remotes.get(preferredRemoteName); + if (remoteUrl) { + return { remoteName: preferredRemoteName, remoteUrl }; + } + } + + const [remoteName, remoteUrl] = + [...remotes.entries()].toSorted(([left], [right]) => left.localeCompare(right))[0] ?? []; + return remoteName && remoteUrl ? { remoteName, remoteUrl } : null; +} + +function buildRepositoryIdentity(input: { + readonly remoteName: string; + readonly remoteUrl: string; +}): RepositoryIdentity { + const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl); + const hostingProvider = detectGitHostingProviderFromRemoteUrl(input.remoteUrl); + const repositoryPath = canonicalKey.split("/").slice(1).join("/"); + const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0); + const [owner] = repositoryPathSegments; + const repositoryName = repositoryPathSegments.at(-1); + + return { + canonicalKey, + locator: { + source: "git-remote", + remoteName: input.remoteName, + remoteUrl: input.remoteUrl, + }, + ...(repositoryPath ? { displayName: repositoryPath } : {}), + ...(hostingProvider ? { provider: hostingProvider.kind } : {}), + ...(owner ? { owner } : {}), + ...(repositoryName ? { name: repositoryName } : {}), + }; +} + +const DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY = 512; +const DEFAULT_POSITIVE_CACHE_TTL = Duration.minutes(1); +const DEFAULT_NEGATIVE_CACHE_TTL = Duration.seconds(10); + +interface RepositoryIdentityResolverOptions { + readonly cacheCapacity?: number; + readonly positiveCacheTtl?: Duration.Input; + readonly negativeCacheTtl?: Duration.Input; +} + +async function resolveRepositoryIdentityCacheKey(cwd: string): Promise { + let cacheKey = cwd; + + try { + const topLevelResult = await runProcess("git", ["-C", cwd, "rev-parse", "--show-toplevel"], { + allowNonZeroExit: true, + }); + if (topLevelResult.code !== 0) { + return cacheKey; + } + + const candidate = topLevelResult.stdout.trim(); + if (candidate.length > 0) { + cacheKey = candidate; + } + } catch { + return cacheKey; + } + + return cacheKey; +} + +async function resolveRepositoryIdentityFromCacheKey( + cacheKey: string, +): Promise { + try { + const remoteResult = await runProcess("git", ["-C", cacheKey, "remote", "-v"], { + allowNonZeroExit: true, + }); + if (remoteResult.code !== 0) { + return null; + } + + const remote = pickPrimaryRemote(parseRemoteFetchUrls(remoteResult.stdout)); + return remote ? buildRepositoryIdentity(remote) : null; + } catch { + return null; + } +} + +export const makeRepositoryIdentityResolver = Effect.fn("makeRepositoryIdentityResolver")( + function* (options: RepositoryIdentityResolverOptions = {}) { + const repositoryIdentityCache = yield* Cache.makeWith( + (cacheKey) => Effect.promise(() => resolveRepositoryIdentityFromCacheKey(cacheKey)), + { + capacity: options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY, + timeToLive: Exit.match({ + onSuccess: (value) => + value === null + ? (options.negativeCacheTtl ?? DEFAULT_NEGATIVE_CACHE_TTL) + : (options.positiveCacheTtl ?? DEFAULT_POSITIVE_CACHE_TTL), + onFailure: () => Duration.zero, + }), + }, + ); + + const resolve: RepositoryIdentityResolverShape["resolve"] = Effect.fn( + "RepositoryIdentityResolver.resolve", + )(function* (cwd) { + const cacheKey = yield* Effect.promise(() => resolveRepositoryIdentityCacheKey(cwd)); + return yield* Cache.get(repositoryIdentityCache, cacheKey); + }); + + return { + resolve, + } satisfies RepositoryIdentityResolverShape; + }, +); + +export const RepositoryIdentityResolverLive = Layer.effect( + RepositoryIdentityResolver, + makeRepositoryIdentityResolver(), +); diff --git a/apps/server/src/project/Services/ProjectFaviconResolver.ts b/apps/server/src/project/Services/ProjectFaviconResolver.ts index f6a8e22c0d..c05dfe8f1f 100644 --- a/apps/server/src/project/Services/ProjectFaviconResolver.ts +++ b/apps/server/src/project/Services/ProjectFaviconResolver.ts @@ -6,7 +6,7 @@ * * @module ProjectFaviconResolver */ -import { ServiceMap } from "effect"; +import { Context } from "effect"; import type { Effect } from "effect"; /** @@ -24,7 +24,7 @@ export interface ProjectFaviconResolverShape { /** * ProjectFaviconResolver - Service tag for project favicon resolution. */ -export class ProjectFaviconResolver extends ServiceMap.Service< +export class ProjectFaviconResolver extends Context.Service< ProjectFaviconResolver, ProjectFaviconResolverShape >()("t3/project/Services/ProjectFaviconResolver") {} diff --git a/apps/server/src/project/Services/ProjectSetupScriptRunner.ts b/apps/server/src/project/Services/ProjectSetupScriptRunner.ts new file mode 100644 index 0000000000..acba335a6e --- /dev/null +++ b/apps/server/src/project/Services/ProjectSetupScriptRunner.ts @@ -0,0 +1,37 @@ +import { Context } from "effect"; +import type { Effect } from "effect"; + +export interface ProjectSetupScriptRunnerResultNoScript { + readonly status: "no-script"; +} + +export interface ProjectSetupScriptRunnerResultStarted { + readonly status: "started"; + readonly scriptId: string; + readonly scriptName: string; + readonly terminalId: string; + readonly cwd: string; +} + +export type ProjectSetupScriptRunnerResult = + | ProjectSetupScriptRunnerResultNoScript + | ProjectSetupScriptRunnerResultStarted; + +export interface ProjectSetupScriptRunnerInput { + readonly threadId: string; + readonly projectId?: string; + readonly projectCwd?: string; + readonly worktreePath: string; + readonly preferredTerminalId?: string; +} + +export interface ProjectSetupScriptRunnerShape { + readonly runForThread: ( + input: ProjectSetupScriptRunnerInput, + ) => Effect.Effect; +} + +export class ProjectSetupScriptRunner extends Context.Service< + ProjectSetupScriptRunner, + ProjectSetupScriptRunnerShape +>()("t3/project/ProjectSetupScriptRunner") {} diff --git a/apps/server/src/project/Services/RepositoryIdentityResolver.ts b/apps/server/src/project/Services/RepositoryIdentityResolver.ts new file mode 100644 index 0000000000..d3eea84619 --- /dev/null +++ b/apps/server/src/project/Services/RepositoryIdentityResolver.ts @@ -0,0 +1,12 @@ +import type { RepositoryIdentity } from "@t3tools/contracts"; +import { Context } from "effect"; +import type { Effect } from "effect"; + +export interface RepositoryIdentityResolverShape { + readonly resolve: (cwd: string) => Effect.Effect; +} + +export class RepositoryIdentityResolver extends Context.Service< + RepositoryIdentityResolver, + RepositoryIdentityResolverShape +>()("t3/project/Services/RepositoryIdentityResolver") {} diff --git a/apps/server/src/projectFaviconRoute.test.ts b/apps/server/src/projectFaviconRoute.test.ts deleted file mode 100644 index 99b61aedc9..0000000000 --- a/apps/server/src/projectFaviconRoute.test.ts +++ /dev/null @@ -1,189 +0,0 @@ -import fs from "node:fs"; -import http from "node:http"; -import os from "node:os"; -import path from "node:path"; - -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { Effect } from "effect"; -import { afterEach, describe, expect, it } from "vitest"; - -import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts"; -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"); - void Effect.runPromise( - tryHandleProjectFaviconRequest(url, res).pipe( - Effect.provide(ProjectFaviconResolverLive), - Effect.provide(NodeServices.layer), - Effect.flatMap((handled) => - handled - ? Effect.void - : Effect.sync(() => { - res.writeHead(404, { "Content-Type": "text/plain" }); - res.end("Not Found"); - }), - ), - ), - ).catch(() => { - if (!res.headersSent) { - res.writeHead(500, { "Content-Type": "text/plain" }); - res.end("Internal Server Error"); - } - }); - }); - - 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 56a9fc9035..0000000000 --- a/apps/server/src/projectFaviconRoute.ts +++ /dev/null @@ -1,76 +0,0 @@ -import http from "node:http"; -import path from "node:path"; -import { Effect, FileSystem } from "effect"; - -import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver.ts"; - -const FAVICON_MIME_TYPES: Record = { - ".png": "image/png", - ".jpg": "image/jpeg", - ".svg": "image/svg+xml", - ".ico": "image/x-icon", -}; - -const FALLBACK_FAVICON_SVG = ``; - -export const tryHandleProjectFaviconRequest = Effect.fn("tryHandleProjectFaviconRequest")( - function* ( - url: URL, - res: http.ServerResponse, - ): Effect.fn.Return { - const respond = ( - statusCode: number, - headers: Record, - body: string | Uint8Array, - ) => { - res.writeHead(statusCode, headers); - res.end(body); - }; - - if (url.pathname !== "/api/project-favicon") { - return false; - } - - const projectCwd = url.searchParams.get("cwd"); - if (!projectCwd) { - respond(400, { "Content-Type": "text/plain" }, "Missing cwd parameter"); - return true; - } - - const fileSystem = yield* FileSystem.FileSystem; - const faviconResolver = yield* ProjectFaviconResolver; - const resolvedPath = yield* faviconResolver.resolvePath(projectCwd); - - if (!resolvedPath) { - respond( - 200, - { - "Content-Type": "image/svg+xml", - "Cache-Control": "public, max-age=3600", - }, - FALLBACK_FAVICON_SVG, - ); - return true; - } - - const data = yield* fileSystem - .readFile(resolvedPath) - .pipe(Effect.catch(() => Effect.succeed(null))); - if (!data) { - respond(500, { "Content-Type": "text/plain" }, "Read error"); - return true; - } - - const ext = path.extname(resolvedPath).toLowerCase(); - const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream"; - respond( - 200, - { - "Content-Type": contentType, - "Cache-Control": "public, max-age=3600", - }, - data, - ); - return true; - }, -); diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts index d064a8239f..5c45013f8d 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts @@ -14,6 +14,7 @@ import { ApprovalRequestId, ProviderItemId, ProviderRuntimeEvent, + type RuntimeMode, ThreadId, } from "@t3tools/contracts"; import { assert, describe, it } from "@effect/vitest"; @@ -208,6 +209,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; @@ -233,8 +237,8 @@ async function readFirstPromptMessage( return next.value; } -const THREAD_ID = ThreadId.makeUnsafe("thread-claude-1"); -const RESUME_THREAD_ID = ThreadId.makeUnsafe("thread-claude-resume"); +const THREAD_ID = ThreadId.make("thread-claude-1"); +const RESUME_THREAD_ID = ThreadId.make("thread-claude-resume"); describe("ClaudeAdapterLive", () => { it.effect("returns validation error for non-claude provider on startSession", () => { @@ -1100,8 +1104,8 @@ 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 context = yield* Effect.context(); + const runFork = Effect.runForkWith(context); const adapter = yield* ClaudeAdapter; const runtimeEvents: Array = []; @@ -1200,8 +1204,8 @@ describe("ClaudeAdapterLive", () => { ); return Effect.gen(function* () { - const services = yield* Effect.services(); - const runFork = Effect.runForkWith(services); + const context = yield* Effect.context(); + const runFork = Effect.runForkWith(context); const adapter = yield* ClaudeAdapter; @@ -2104,7 +2108,7 @@ describe("ClaudeAdapterLive", () => { return; } assert.deepEqual(requested.value.providerRefs, { - providerItemId: ProviderItemId.makeUnsafe("tool-use-1"), + providerItemId: ProviderItemId.make("tool-use-1"), }); const runtimeRequestId = requested.value.requestId; assert.equal(typeof runtimeRequestId, "string"); @@ -2114,7 +2118,7 @@ describe("ClaudeAdapterLive", () => { yield* adapter.respondToRequest( session.threadId, - ApprovalRequestId.makeUnsafe(runtimeRequestId), + ApprovalRequestId.make(runtimeRequestId), "accept", ); @@ -2130,7 +2134,7 @@ describe("ClaudeAdapterLive", () => { assert.equal(resolved.value.requestId, requested.value.requestId); assert.equal(resolved.value.payload.decision, "accept"); assert.deepEqual(resolved.value.providerRefs, { - providerItemId: ProviderItemId.makeUnsafe("tool-use-1"), + providerItemId: ProviderItemId.make("tool-use-1"), }); const permissionResult = yield* Effect.promise(() => permissionPromise); @@ -2179,7 +2183,7 @@ describe("ClaudeAdapterLive", () => { yield* adapter.respondToRequest( session.threadId, - ApprovalRequestId.makeUnsafe(String(agentRequested.value.requestId)), + ApprovalRequestId.make(String(agentRequested.value.requestId)), "accept", ); yield* Stream.runHead(adapter.streamEvents); @@ -2203,7 +2207,7 @@ describe("ClaudeAdapterLive", () => { yield* adapter.respondToRequest( session.threadId, - ApprovalRequestId.makeUnsafe(String(grepRequested.value.requestId)), + ApprovalRequestId.make(String(grepRequested.value.requestId)), "accept", ); yield* Stream.runHead(adapter.streamEvents); @@ -2493,57 +2497,63 @@ describe("ClaudeAdapterLive", () => { ); }); - it.effect("restores base permission mode on sendTurn when interactionMode is default", () => { - const harness = makeHarness(); - return Effect.gen(function* () { - const adapter = yield* ClaudeAdapter; + it.effect.each<{ runtimeMode: RuntimeMode; expectedBase: PermissionMode }>([ + { runtimeMode: "full-access", expectedBase: "bypassPermissions" }, + { runtimeMode: "approval-required", expectedBase: "default" }, + { runtimeMode: "auto-accept-edits", expectedBase: "acceptEdits" }, + ])( + "restores $expectedBase permission mode after plan turn ($runtimeMode)", + ({ runtimeMode, expectedBase }) => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; - const session = yield* adapter.startSession({ - threadId: THREAD_ID, - provider: "claudeAgent", - runtimeMode: "full-access", - }); + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode, + }); - // First turn in plan mode - yield* adapter.sendTurn({ - threadId: session.threadId, - input: "plan this", - interactionMode: "plan", - attachments: [], - }); + // First turn in plan mode + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "plan this", + interactionMode: "plan", + attachments: [], + }); - // Complete the turn so we can send another - const turnCompletedFiber = yield* Stream.filter( - adapter.streamEvents, - (event) => event.type === "turn.completed", - ).pipe(Stream.runHead, Effect.forkChild); + // Complete the turn so we can send another + const turnCompletedFiber = yield* Stream.filter( + adapter.streamEvents, + (event) => event.type === "turn.completed", + ).pipe(Stream.runHead, Effect.forkChild); - harness.query.emit({ - type: "result", - subtype: "success", - is_error: false, - errors: [], - session_id: "sdk-session-plan-restore", - uuid: "result-plan", - } as unknown as SDKMessage); + harness.query.emit({ + type: "result", + subtype: "success", + is_error: false, + errors: [], + session_id: `sdk-session-${runtimeMode}`, + uuid: `result-${runtimeMode}`, + } as unknown as SDKMessage); - yield* Fiber.join(turnCompletedFiber); + yield* Fiber.join(turnCompletedFiber); - // Second turn back to default - yield* adapter.sendTurn({ - threadId: session.threadId, - input: "now do it", - interactionMode: "default", - attachments: [], - }); + // Second turn back to default + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "now do it", + interactionMode: "default", + attachments: [], + }); - // First call sets "plan", second call restores "bypassPermissions" (the base for full-access) - assert.deepEqual(harness.query.setPermissionModeCalls, ["plan", "bypassPermissions"]); - }).pipe( - Effect.provideService(Random.Random, makeDeterministicRandomService()), - Effect.provide(harness.layer), - ); - }); + assert.deepEqual(harness.query.setPermissionModeCalls, ["plan", expectedBase]); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }, + ); it.effect("does not call setPermissionMode when interactionMode is absent", () => { const harness = makeHarness(); @@ -2619,7 +2629,7 @@ describe("ClaudeAdapterLive", () => { } assert.equal(proposedEvent.value.payload.planMarkdown, "# Ship it\n\n- one\n- two"); assert.deepEqual(proposedEvent.value.providerRefs, { - providerItemId: ProviderItemId.makeUnsafe("tool-exit-1"), + providerItemId: ProviderItemId.make("tool-exit-1"), }); const permissionResult = yield* Effect.promise(() => permissionPromise); @@ -2697,7 +2707,7 @@ describe("ClaudeAdapterLive", () => { } assert.equal(proposedEvent.value.payload.planMarkdown, "# Final plan\n\n- capture it"); assert.deepEqual(proposedEvent.value.providerRefs, { - providerItemId: ProviderItemId.makeUnsafe("tool-exit-2"), + providerItemId: ProviderItemId.make("tool-exit-2"), }); }).pipe( Effect.provideService(Random.Random, makeDeterministicRandomService()), @@ -2788,15 +2798,13 @@ describe("ClaudeAdapterLive", () => { assert.equal(requestedEvent.value.payload.questions.length, 1); assert.equal(requestedEvent.value.payload.questions[0]?.question, "Which framework?"); assert.deepEqual(requestedEvent.value.providerRefs, { - providerItemId: ProviderItemId.makeUnsafe("tool-ask-1"), + providerItemId: ProviderItemId.make("tool-ask-1"), }); // Respond with the user's answers. - yield* adapter.respondToUserInput( - session.threadId, - ApprovalRequestId.makeUnsafe(requestId!), - { "Which framework?": "React" }, - ); + yield* adapter.respondToUserInput(session.threadId, ApprovalRequestId.make(requestId!), { + "Which framework?": "React", + }); // The adapter should emit a user-input.resolved event. const resolvedEvent = yield* Stream.runHead(adapter.streamEvents); @@ -2812,7 +2820,7 @@ describe("ClaudeAdapterLive", () => { "Which framework?": "React", }); assert.deepEqual(resolvedEvent.value.providerRefs, { - providerItemId: ProviderItemId.makeUnsafe("tool-ask-1"), + providerItemId: ProviderItemId.make("tool-ask-1"), }); // The canUseTool promise should resolve with the answers in SDK format. @@ -2879,11 +2887,9 @@ describe("ClaudeAdapterLive", () => { } const requestId = requestedEvent.value.requestId; - yield* adapter.respondToUserInput( - session.threadId, - ApprovalRequestId.makeUnsafe(requestId!), - { "Deploy to which env?": "Staging" }, - ); + yield* adapter.respondToUserInput(session.threadId, ApprovalRequestId.make(requestId!), { + "Deploy to which env?": "Staging", + }); // Drain the resolved event. yield* Stream.runHead(adapter.streamEvents); diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index 6b50bd4fbb..fb32da78c5 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -269,7 +269,7 @@ function isInterruptedResult(result: SDKResultMessage): boolean { } function asRuntimeItemId(value: string): RuntimeItemId { - return RuntimeItemId.makeUnsafe(value); + return RuntimeItemId.make(value); } function maxClaudeContextWindowFromModelUsage(modelUsage: unknown): number | undefined { @@ -353,7 +353,7 @@ function asCanonicalTurnId(value: TurnId): TurnId { } function asRuntimeRequestId(value: ApprovalRequestId): RuntimeRequestId { - return RuntimeRequestId.makeUnsafe(value); + return RuntimeRequestId.make(value); } function readClaudeResumeState(resumeCursor: unknown): ClaudeResumeState | undefined { @@ -371,7 +371,7 @@ function readClaudeResumeState(resumeCursor: unknown): ClaudeResumeState | undef const threadIdCandidate = typeof cursor.threadId === "string" ? cursor.threadId : undefined; const threadId = threadIdCandidate && !isSyntheticClaudeThreadId(threadIdCandidate) - ? ThreadId.makeUnsafe(threadIdCandidate) + ? ThreadId.make(threadIdCandidate) : undefined; const resumeCandidate = typeof cursor.resume === "string" @@ -533,7 +533,7 @@ function buildUserMessage(input: { parent_tool_use_id: null, message: { role: "user", - content: input.sdkContent, + content: input.sdkContent as unknown as SDKUserMessage["message"]["content"], }, } as SDKUserMessage; } @@ -641,7 +641,7 @@ function nativeProviderRefs( ): NonNullable { if (options?.providerItemId) { return { - providerItemId: ProviderItemId.makeUnsafe(options.providerItemId), + providerItemId: ProviderItemId.make(options.providerItemId), }; } return {}; @@ -934,7 +934,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( const serverSettingsService = yield* ServerSettingsService; const nowIso = Effect.map(DateTime.now, DateTime.formatIso); - const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.makeUnsafe(id)); + const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.make(id)); const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso }); const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect => @@ -967,7 +967,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( ? { providerThreadId: message.session_id } : {}), ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), - ...(itemId ? { itemId: ProviderItemId.makeUnsafe(itemId) } : {}), + ...(itemId ? { itemId: ProviderItemId.make(itemId) } : {}), payload: message, }, }, @@ -1822,7 +1822,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( // 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 turnId = TurnId.make(yield* Random.nextUUIDv4); const startedAt = yield* nowIso; context.turnState = { turnId, @@ -2013,7 +2013,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( ...base, type: "task.started", payload: { - taskId: RuntimeTaskId.makeUnsafe(message.task_id), + taskId: RuntimeTaskId.make(message.task_id), description: message.description, ...(message.task_type ? { taskType: message.task_type } : {}), }, @@ -2043,7 +2043,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( ...base, type: "task.progress", payload: { - taskId: RuntimeTaskId.makeUnsafe(message.task_id), + taskId: RuntimeTaskId.make(message.task_id), description: message.description, ...(message.summary ? { summary: message.summary } : {}), ...(message.usage ? { usage: message.usage } : {}), @@ -2075,7 +2075,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( ...base, type: "task.completed", payload: { - taskId: RuntimeTaskId.makeUnsafe(message.task_id), + taskId: RuntimeTaskId.make(message.task_id), status: message.status, ...(message.summary ? { summary: message.summary } : {}), ...(message.usage ? { usage: message.usage } : {}), @@ -2380,9 +2380,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( 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 runtimeContext = yield* Effect.context(); + const runFork = Effect.runForkWith(runtimeContext); + const runPromise = Effect.runPromiseWith(runtimeContext); const promptQueue = yield* Queue.unbounded(); const prompt = Stream.fromQueue(promptQueue).pipe( @@ -2409,7 +2409,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( toolInput: Record, callbackOptions: { readonly signal: AbortSignal; readonly toolUseID?: string }, ) { - const requestId = ApprovalRequestId.makeUnsafe(yield* Random.nextUUIDv4); + const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4); // Parse questions from the SDK's AskUserQuestion input. const rawQuestions = Array.isArray(toolInput.questions) ? toolInput.questions : []; @@ -2562,7 +2562,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( } satisfies PermissionResult; } - const requestId = ApprovalRequestId.makeUnsafe(yield* Random.nextUUIDv4); + const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4); const requestType = classifyRequestType(toolName); const detail = summarizeToolRequest(toolName, toolInput); const decisionDeferred = yield* Deferred.make(); @@ -2693,7 +2693,11 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( ? modelSelection.options.thinking : undefined; const effectiveEffort = getEffectiveClaudeCodeEffort(effort); - const permissionMode = input.runtimeMode === "full-access" ? "bypassPermissions" : undefined; + const runtimeModeToPermission: Record = { + "auto-accept-edits": "acceptEdits", + "full-access": "bypassPermissions", + }; + const permissionMode = runtimeModeToPermission[input.runtimeMode]; const settings = { ...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}), ...(fastMode ? { fastMode: true } : {}), @@ -2881,13 +2885,12 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( }); } else if (input.interactionMode === "default") { yield* Effect.tryPromise({ - try: () => - context.query.setPermissionMode(context.basePermissionMode ?? "bypassPermissions"), + try: () => context.query.setPermissionMode(context.basePermissionMode ?? "default"), catch: (cause) => toRequestError(input.threadId, "turn/setPermissionMode", cause), }); } - const turnId = TurnId.makeUnsafe(yield* Random.nextUUIDv4); + const turnId = TurnId.make(yield* Random.nextUUIDv4); const turnState: ClaudeTurnState = { turnId, startedAt: yield* nowIso, @@ -3054,7 +3057,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( listSessions, hasSession, stopAll, - streamEvents: Stream.fromQueue(runtimeEventQueue), + get streamEvents() { + return Stream.fromQueue(runtimeEventQueue); + }, } satisfies ClaudeAdapterShape; }); diff --git a/apps/server/src/provider/Layers/ClaudeProvider.ts b/apps/server/src/provider/Layers/ClaudeProvider.ts index f2243ef1b0..d00be86d3e 100644 --- a/apps/server/src/provider/Layers/ClaudeProvider.ts +++ b/apps/server/src/provider/Layers/ClaudeProvider.ts @@ -4,12 +4,16 @@ import type { ServerProvider, ServerProviderModel, ServerProviderAuth, + ServerProviderSlashCommand, ServerProviderState, } from "@t3tools/contracts"; import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import { decodeJsonResult } from "@t3tools/shared/schemaJson"; -import { query as claudeQuery } from "@anthropic-ai/claude-agent-sdk"; +import { + query as claudeQuery, + type SlashCommand as ClaudeSlashCommand, +} from "@anthropic-ai/claude-agent-sdk"; import { buildServerProvider, @@ -24,7 +28,16 @@ import { } from "../providerSnapshot"; import { makeManagedServerProvider } from "../makeManagedServerProvider"; import { ClaudeProvider } from "../Services/ClaudeProvider"; -import { ServerSettingsError, ServerSettingsService } from "../../serverSettings"; +import { ServerSettingsService } from "../../serverSettings"; +import { ServerSettingsError } from "@t3tools/contracts"; + +const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = { + reasoningEffortLevels: [], + supportsFastMode: false, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], +}; const PROVIDER = "claudeAgent" as const; const BUILT_IN_MODELS: ReadonlyArray = [ @@ -86,13 +99,8 @@ const BUILT_IN_MODELS: ReadonlyArray = [ export function getClaudeModelCapabilities(model: string | null | undefined): ModelCapabilities { const slug = model?.trim(); return ( - BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ?? { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - } + BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ?? + DEFAULT_CLAUDE_MODEL_CAPABILITIES ); } @@ -272,18 +280,6 @@ function extractClaudeAuthMethodFromOutput(result: CommandResult): string | unde 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) @@ -344,45 +340,78 @@ function claudeAuthMetadata(input: { 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; +function nonEmptyProbeString(value: string): string | undefined { + const candidate = value.trim(); + return candidate ? candidate : undefined; +} + +function parseClaudeInitializationCommands( + commands: ReadonlyArray | undefined, +): ReadonlyArray { + return dedupeSlashCommands( + (commands ?? []).flatMap((command) => { + const name = nonEmptyProbeString(command.name); + if (!name) { + return []; + } + + const description = nonEmptyProbeString(command.description); + const argumentHint = nonEmptyProbeString(command.argumentHint); + + return [ + { + name, + ...(description ? { description } : {}), + ...(argumentHint ? { input: { hint: argumentHint } } : {}), + } satisfies ServerProviderSlashCommand, + ]; + }), + ); +} + +function dedupeSlashCommands( + commands: ReadonlyArray, +): ReadonlyArray { + const commandsByName = new Map(); + + for (const command of commands) { + const name = nonEmptyProbeString(command.name); + if (!name) { + continue; + } + + const key = name.toLowerCase(); + const existing = commandsByName.get(key); + if (!existing) { + commandsByName.set(key, { + ...command, + name, + }); + continue; + } + + commandsByName.set(key, { + ...existing, + ...(existing.description + ? {} + : command.description + ? { description: command.description } + : {}), + ...(existing.input?.hint + ? {} + : command.input?.hint + ? { input: { hint: command.input.hint } } + : {}), + }); + } + + return [...commandsByName.values()]; +} + /** * Probe account information by spawning a lightweight Claude Agent SDK * session and reading the initialization result. @@ -404,13 +433,16 @@ const probeClaudeCapabilities = (binaryPath: string) => { pathToClaudeCodeExecutable: binaryPath, abortController: abort, maxTurns: 0, - settingSources: [], + settingSources: ["user", "project", "local"], allowedTools: [], stderr: () => {}, }, }); const init = await q.initializationResult(); - return { subscriptionType: init.account?.subscriptionType }; + return { + subscriptionType: init.account?.subscriptionType, + slashCommands: parseClaudeInitializationCommands(init.commands), + }; }).pipe( Effect.ensuring( Effect.sync(() => { @@ -426,20 +458,22 @@ const probeClaudeCapabilities = (binaryPath: string) => { ); }; -const runClaudeCommand = (args: ReadonlyArray) => - Effect.gen(function* () { - const claudeSettings = yield* Effect.service(ServerSettingsService).pipe( - Effect.flatMap((service) => service.getSettings), - Effect.map((settings) => settings.providers.claudeAgent), - ); - const command = ChildProcess.make(claudeSettings.binaryPath, [...args], { - shell: process.platform === "win32", - }); - return yield* spawnAndCollect(claudeSettings.binaryPath, command); +const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (args: ReadonlyArray) { + const claudeSettings = yield* Effect.service(ServerSettingsService).pipe( + Effect.flatMap((service) => service.getSettings), + Effect.map((settings) => settings.providers.claudeAgent), + ); + const command = ChildProcess.make(claudeSettings.binaryPath, [...args], { + shell: process.platform === "win32", }); + return yield* spawnAndCollect(claudeSettings.binaryPath, command); +}); export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* ( resolveSubscriptionType?: (binaryPath: string) => Effect.Effect, + resolveSlashCommands?: ( + binaryPath: string, + ) => Effect.Effect | undefined>, ): Effect.fn.Return< ServerProvider, ServerSettingsError, @@ -450,7 +484,12 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( Effect.map((settings) => settings.providers.claudeAgent), ); const checkedAt = new Date().toISOString(); - const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, claudeSettings.customModels); + const models = providerModelsFromSettings( + BUILT_IN_MODELS, + PROVIDER, + claudeSettings.customModels, + DEFAULT_CLAUDE_MODEL_CAPABILITIES, + ); if (!claudeSettings.enabled) { return buildServerProvider({ @@ -530,6 +569,14 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( }); } + const slashCommands = + (resolveSlashCommands + ? yield* resolveSlashCommands(claudeSettings.binaryPath).pipe( + Effect.orElseSucceed(() => undefined), + ) + : undefined) ?? []; + const dedupedSlashCommands = dedupeSlashCommands(slashCommands); + // ── Auth check + subscription detection ──────────────────────────── const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe( @@ -555,8 +602,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( subscriptionType = yield* resolveSubscriptionType(claudeSettings.binaryPath); } - const resolvedModels = adjustModelsForSubscription(models, subscriptionType); - // ── Handle auth results (same logic as before, adjusted models) ── if (Result.isFailure(authProbe)) { @@ -565,7 +610,8 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( provider: PROVIDER, enabled: claudeSettings.enabled, checkedAt, - models: resolvedModels, + models, + slashCommands: dedupedSlashCommands, probe: { installed: true, version: parsedVersion, @@ -584,7 +630,8 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( provider: PROVIDER, enabled: claudeSettings.enabled, checkedAt, - models: resolvedModels, + models, + slashCommands: dedupedSlashCommands, probe: { installed: true, version: parsedVersion, @@ -601,7 +648,8 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( provider: PROVIDER, enabled: claudeSettings.enabled, checkedAt, - models: resolvedModels, + models, + slashCommands: dedupedSlashCommands, probe: { installed: true, version: parsedVersion, @@ -624,12 +672,18 @@ export const ClaudeProviderLive = Layer.effect( const subscriptionProbeCache = yield* Cache.make({ capacity: 1, timeToLive: Duration.minutes(5), - lookup: (binaryPath: string) => - probeClaudeCapabilities(binaryPath).pipe(Effect.map((r) => r?.subscriptionType)), + lookup: (binaryPath: string) => probeClaudeCapabilities(binaryPath), }); - const checkProvider = checkClaudeProviderStatus((binaryPath) => - Cache.get(subscriptionProbeCache, binaryPath), + const checkProvider = checkClaudeProviderStatus( + (binaryPath) => + Cache.get(subscriptionProbeCache, binaryPath).pipe( + Effect.map((probe) => probe?.subscriptionType), + ), + (binaryPath) => + Cache.get(subscriptionProbeCache, binaryPath).pipe( + Effect.map((probe) => probe?.slashCommands), + ), ).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 7ddbdbfc98..c4ee33b776 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.test.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.test.ts @@ -28,10 +28,10 @@ import { CodexAdapter } from "../Services/CodexAdapter.ts"; import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts"; import { makeCodexAdapterLive } from "./CodexAdapter.ts"; -const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value); -const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value); -const asEventId = (value: string): EventId => EventId.makeUnsafe(value); -const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value); +const asThreadId = (value: string): ThreadId => ThreadId.make(value); +const asTurnId = (value: string): TurnId => TurnId.make(value); +const asEventId = (value: string): EventId => EventId.make(value); +const asItemId = (value: string): ProviderItemId => ProviderItemId.make(value); class FakeCodexManager extends CodexAppServerManager { public startSessionImpl = vi.fn( @@ -238,14 +238,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => { .pipe(Effect.result); assert.equal(result._tag, "Failure"); - if (result._tag !== "Failure") { - return; - } - assert.equal(result.failure._tag, "ProviderAdapterSessionNotFoundError"); - if (result.failure._tag !== "ProviderAdapterSessionNotFoundError") { - return; - } assert.equal(result.failure.provider, "codex"); assert.equal(result.failure.threadId, "sess-missing"); assert.equal(result.failure.cause instanceof Error, true); @@ -508,6 +501,42 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { }), ); + it.effect("maps fatal websocket stderr notifications to runtime.error", () => + Effect.gen(function* () { + const adapter = yield* CodexAdapter; + const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); + + lifecycleManager.emit("event", { + id: asEventId("evt-process-stderr-websocket"), + kind: "notification", + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: new Date().toISOString(), + method: "process/stderr", + turnId: asTurnId("turn-1"), + message: + "2026-03-31T18:14:06.833399Z ERROR codex_api::endpoint::responses_websocket: failed to connect to websocket: HTTP error: 503 Service Unavailable, url: wss://chatgpt.com/backend-api/codex/responses", + } satisfies ProviderEvent); + + const firstEvent = yield* Fiber.join(firstEventFiber); + + assert.equal(firstEvent._tag, "Some"); + if (firstEvent._tag !== "Some") { + return; + } + assert.equal(firstEvent.value.type, "runtime.error"); + if (firstEvent.value.type !== "runtime.error") { + return; + } + assert.equal(firstEvent.value.turnId, "turn-1"); + assert.equal(firstEvent.value.payload.class, "provider_error"); + assert.equal( + firstEvent.value.payload.message, + "2026-03-31T18:14:06.833399Z ERROR codex_api::endpoint::responses_websocket: failed to connect to websocket: HTTP error: 503 Service Unavailable, url: wss://chatgpt.com/backend-api/codex/responses", + ); + }), + ); + it.effect("preserves request type when mapping serverRequest/resolved", () => Effect.gen(function* () { const adapter = yield* CodexAdapter; @@ -520,7 +549,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { threadId: asThreadId("thread-1"), createdAt: new Date().toISOString(), method: "serverRequest/resolved", - requestId: ApprovalRequestId.makeUnsafe("req-1"), + requestId: ApprovalRequestId.make("req-1"), payload: { request: { method: "item/commandExecution/requestApproval", @@ -556,7 +585,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { threadId: asThreadId("thread-1"), createdAt: new Date().toISOString(), method: "serverRequest/resolved", - requestId: ApprovalRequestId.makeUnsafe("req-file-read-1"), + requestId: ApprovalRequestId.make("req-file-read-1"), payload: { request: { method: "item/fileRead/requestApproval", @@ -674,7 +703,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { threadId: asThreadId("thread-1"), createdAt: new Date().toISOString(), method: "item/tool/requestUserInput", - requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"), + requestId: ApprovalRequestId.make("req-user-input-1"), payload: { questions: [ { @@ -687,6 +716,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { description: "Allow workspace writes only", }, ], + multiSelect: true, }, ], }, @@ -698,7 +728,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { threadId: asThreadId("thread-1"), createdAt: new Date().toISOString(), method: "item/tool/requestUserInput/answered", - requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"), + requestId: ApprovalRequestId.make("req-user-input-1"), payload: { answers: { sandbox_mode: { @@ -713,6 +743,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { if (events[0]?.type === "user-input.requested") { assert.equal(events[0].requestId, "req-user-input-1"); assert.equal(events[0].payload.questions[0]?.id, "sandbox_mode"); + assert.equal(events[0].payload.questions[0]?.multiSelect, true); } assert.equal(events[1]?.type, "user-input.resolved"); diff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.ts index b9ac4bfc4a..60de91b79a 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.ts @@ -22,7 +22,7 @@ import { TurnId, ProviderSendTurnInput, } from "@t3tools/contracts"; -import { Effect, FileSystem, Layer, Queue, Schema, ServiceMap, Stream } from "effect"; +import { Effect, FileSystem, Layer, Queue, Schema, Context, Stream } from "effect"; import { ProviderAdapterProcessError, @@ -46,23 +46,16 @@ const PROVIDER = "codex" as const; export interface CodexAdapterLiveOptions { readonly manager?: CodexAppServerManager; - readonly makeManager?: (services?: ServiceMap.ServiceMap) => CodexAppServerManager; + readonly makeManager?: (services?: Context.Context) => CodexAppServerManager; readonly nativeEventLogPath?: string; readonly nativeEventLogger?: EventNdjsonLogger; } -function toMessage(cause: unknown, fallback: string): string { - if (cause instanceof Error && cause.message.length > 0) { - return cause.message; - } - return fallback; -} - function toSessionError( threadId: ThreadId, cause: unknown, ): ProviderAdapterSessionNotFoundError | ProviderAdapterSessionClosedError | undefined { - const normalized = toMessage(cause, "").toLowerCase(); + const normalized = cause instanceof Error ? cause.message.toLowerCase() : ""; if (normalized.includes("unknown session") || normalized.includes("unknown provider session")) { return new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, @@ -88,7 +81,7 @@ function toRequestError(threadId: ThreadId, method: string, cause: unknown): Pro return new ProviderAdapterRequestError({ provider: PROVIDER, method, - detail: toMessage(cause, `${method} failed`), + detail: cause instanceof Error ? `${method} failed: ${cause.message}` : `${method} failed`, cause, }); } @@ -112,6 +105,13 @@ function asNumber(value: unknown): number | undefined { return typeof value === "number" && Number.isFinite(value) ? value : undefined; } +const FATAL_CODEX_STDERR_SNIPPETS = ["failed to connect to websocket"]; + +function isFatalCodexProcessStderrMessage(message: string): boolean { + const normalized = message.toLowerCase(); + return FATAL_CODEX_STDERR_SNIPPETS.some((snippet) => normalized.includes(snippet)); +} + function normalizeCodexTokenUsage(value: unknown): ThreadTokenUsageSnapshot | undefined { const usage = asObject(value); const totalUsage = asObject(usage?.total_token_usage ?? usage?.total); @@ -155,11 +155,11 @@ function normalizeCodexTokenUsage(value: unknown): ThreadTokenUsageSnapshot | un } function toTurnId(value: string | undefined): TurnId | undefined { - return value?.trim() ? TurnId.makeUnsafe(value) : undefined; + return value?.trim() ? TurnId.make(value) : undefined; } function toProviderItemId(value: string | undefined): ProviderItemId | undefined { - return value?.trim() ? ProviderItemId.makeUnsafe(value) : undefined; + return value?.trim() ? ProviderItemId.make(value) : undefined; } function toTurnStatus(value: unknown): "completed" | "failed" | "cancelled" | "interrupted" { @@ -375,6 +375,7 @@ function toUserInputQuestions(payload: Record | undefined) { header, question: prompt, options, + multiSelect: question.multiSelect === true, }; }) .filter( @@ -385,6 +386,7 @@ function toUserInputQuestions(payload: Record | undefined) { header: string; question: string; options: Array<{ label: string; description: string }>; + multiSelect: boolean; } => question !== undefined, ); @@ -445,15 +447,15 @@ function extractProposedPlanMarkdown(text: string | undefined): string | undefin } function asRuntimeItemId(itemId: ProviderItemId): RuntimeItemId { - return RuntimeItemId.makeUnsafe(itemId); + return RuntimeItemId.make(itemId); } function asRuntimeRequestId(requestId: string): RuntimeRequestId { - return RuntimeRequestId.makeUnsafe(requestId); + return RuntimeRequestId.make(requestId); } function asRuntimeTaskId(taskId: string): RuntimeTaskId { - return RuntimeTaskId.makeUnsafe(taskId); + return RuntimeTaskId.make(taskId); } function codexEventMessage( @@ -1269,15 +1271,27 @@ function mapToRuntimeEvents( } if (event.method === "process/stderr") { + const message = event.message ?? "Codex process stderr"; + const isFatal = isFatalCodexProcessStderrMessage(message); return [ - { - type: "runtime.warning", - ...runtimeEventBase(event, canonicalThreadId), - payload: { - message: event.message ?? "Codex process stderr", - ...(event.payload !== undefined ? { detail: event.payload } : {}), - }, - }, + isFatal + ? { + type: "runtime.error", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + message, + class: "provider_error" as const, + ...(event.payload !== undefined ? { detail: event.payload } : {}), + }, + } + : { + type: "runtime.warning", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + message, + ...(event.payload !== undefined ? { detail: event.payload } : {}), + }, + }, ]; } @@ -1345,7 +1359,7 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( if (options?.manager) { return options.manager; } - const services = yield* Effect.services(); + const services = yield* Effect.context(); return options?.makeManager?.(services) ?? new CodexAppServerManager(services); }); @@ -1406,7 +1420,7 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( new ProviderAdapterProcessError({ provider: PROVIDER, threadId: input.threadId, - detail: toMessage(cause, "Failed to start Codex adapter session."), + detail: `Failed to start Codex adapter session: ${cause instanceof Error ? cause.message : String(cause)}.`, cause, }), }); @@ -1434,7 +1448,7 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( new ProviderAdapterRequestError({ provider: PROVIDER, method: "turn/start", - detail: toMessage(cause, "Failed to read attachment file."), + detail: `Failed to read attachment file: ${cause.message}.`, cause, }), ), @@ -1564,7 +1578,7 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( }); const registerListener = Effect.fn("registerListener")(function* () { - const services = yield* Effect.services(); + const services = yield* Effect.context(); const listenerEffect = Effect.fn("listener")(function* (event: ProviderEvent) { yield* writeNativeEvent(event); const runtimeEvents = mapToRuntimeEvents(event, event.threadId); @@ -1612,7 +1626,9 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( listSessions, hasSession, stopAll, - streamEvents: Stream.fromQueue(runtimeEventQueue), + get streamEvents() { + return Stream.fromQueue(runtimeEventQueue); + }, } satisfies CodexAdapterShape; }); diff --git a/apps/server/src/provider/Layers/CodexProvider.ts b/apps/server/src/provider/Layers/CodexProvider.ts index 1fe98ea798..421621c969 100644 --- a/apps/server/src/provider/Layers/CodexProvider.ts +++ b/apps/server/src/provider/Layers/CodexProvider.ts @@ -5,6 +5,7 @@ import type { ServerProvider, ServerProviderModel, ServerProviderAuth, + ServerProviderSkill, ServerProviderState, } from "@t3tools/contracts"; import { @@ -44,9 +45,23 @@ import { codexAuthSubType, type CodexAccountSnapshot, } from "../codexAccount"; -import { probeCodexAccount } from "../codexAppServer"; +import { probeCodexDiscovery } from "../codexAppServer"; import { CodexProvider } from "../Services/CodexProvider"; -import { ServerSettingsError, ServerSettingsService } from "../../serverSettings"; +import { ServerSettingsService } from "../../serverSettings"; +import { ServerSettingsError } from "@t3tools/contracts"; + +const DEFAULT_CODEX_MODEL_CAPABILITIES: ModelCapabilities = { + reasoningEffortLevels: [ + { value: "xhigh", label: "Extra High" }, + { value: "high", label: "High", isDefault: true }, + { value: "medium", label: "Medium" }, + { value: "low", label: "Low" }, + ], + supportsFastMode: true, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], +}; const PROVIDER = "codex" as const; const OPENAI_AUTH_PROVIDERS = new Set(["openai"]); @@ -158,13 +173,8 @@ const BUILT_IN_MODELS: ReadonlyArray = [ export function getCodexModelCapabilities(model: string | null | undefined): ModelCapabilities { const slug = model?.trim(); return ( - BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ?? { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - } + BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ?? + DEFAULT_CODEX_MODEL_CAPABILITIES ); } @@ -295,8 +305,9 @@ const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000; const probeCodexCapabilities = (input: { readonly binaryPath: string; readonly homePath?: string; + readonly cwd: string; }) => - Effect.tryPromise((signal) => probeCodexAccount({ ...input, signal })).pipe( + Effect.tryPromise((signal) => probeCodexDiscovery({ ...input, signal })).pipe( Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS), Effect.result, Effect.map((result) => { @@ -305,27 +316,31 @@ const probeCodexCapabilities = (input: { }), ); -const runCodexCommand = (args: ReadonlyArray) => - Effect.gen(function* () { - const settingsService = yield* ServerSettingsService; - const codexSettings = yield* settingsService.getSettings.pipe( - Effect.map((settings) => settings.providers.codex), - ); - const command = ChildProcess.make(codexSettings.binaryPath, [...args], { - shell: process.platform === "win32", - env: { - ...process.env, - ...(codexSettings.homePath ? { CODEX_HOME: codexSettings.homePath } : {}), - }, - }); - return yield* spawnAndCollect(codexSettings.binaryPath, command); +const runCodexCommand = Effect.fn("runCodexCommand")(function* (args: ReadonlyArray) { + const settingsService = yield* ServerSettingsService; + const codexSettings = yield* settingsService.getSettings.pipe( + Effect.map((settings) => settings.providers.codex), + ); + const command = ChildProcess.make(codexSettings.binaryPath, [...args], { + shell: process.platform === "win32", + env: { + ...process.env, + ...(codexSettings.homePath ? { CODEX_HOME: codexSettings.homePath } : {}), + }, }); + return yield* spawnAndCollect(codexSettings.binaryPath, command); +}); export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* ( resolveAccount?: (input: { readonly binaryPath: string; readonly homePath?: string; }) => Effect.Effect, + resolveSkills?: (input: { + readonly binaryPath: string; + readonly homePath?: string; + readonly cwd: string; + }) => Effect.Effect | undefined>, ): Effect.fn.Return< ServerProvider, ServerSettingsError, @@ -339,7 +354,12 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu Effect.map((settings) => settings.providers.codex), ); const checkedAt = new Date().toISOString(); - const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, codexSettings.customModels); + const models = providerModelsFromSettings( + BUILT_IN_MODELS, + PROVIDER, + codexSettings.customModels, + DEFAULT_CODEX_MODEL_CAPABILITIES, + ); if (!codexSettings.enabled) { return buildServerProvider({ @@ -376,7 +396,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu 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)}.`, + : `Failed to execute Codex CLI health check: ${error.message}.`, }, }); } @@ -436,12 +456,22 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu }); } + const skills = + (resolveSkills + ? yield* resolveSkills({ + binaryPath: codexSettings.binaryPath, + homePath: codexSettings.homePath, + cwd: process.cwd(), + }).pipe(Effect.orElseSucceed(() => undefined)) + : undefined) ?? []; + if (yield* hasCustomModelProvider) { return buildServerProvider({ provider: PROVIDER, enabled: codexSettings.enabled, checkedAt, models, + skills, probe: { installed: true, version: parsedVersion, @@ -471,15 +501,13 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu enabled: codexSettings.enabled, checkedAt, models: resolvedModels, + skills, 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.", + message: `Could not verify Codex authentication status: ${error.message}.`, }, }); } @@ -490,6 +518,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu enabled: codexSettings.enabled, checkedAt, models: resolvedModels, + skills, probe: { installed: true, version: parsedVersion, @@ -508,6 +537,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu enabled: codexSettings.enabled, checkedAt, models: resolvedModels, + skills, probe: { installed: true, version: parsedVersion, @@ -533,16 +563,29 @@ export const CodexProviderLive = Layer.effect( capacity: 4, timeToLive: Duration.minutes(5), lookup: (key: string) => { - const [binaryPath, homePath] = JSON.parse(key) as [string, string | undefined]; + const [binaryPath, homePath, cwd] = JSON.parse(key) as [string, string | undefined, string]; return probeCodexCapabilities({ binaryPath, + cwd, ...(homePath ? { homePath } : {}), }); }, }); - const checkProvider = checkCodexProviderStatus((input) => - Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath])), + const getDiscovery = (input: { + readonly binaryPath: string; + readonly homePath?: string; + readonly cwd: string; + }) => + Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath, input.cwd])); + + const checkProvider = checkCodexProviderStatus( + (input) => + getDiscovery({ + ...input, + cwd: process.cwd(), + }).pipe(Effect.map((discovery) => discovery?.account)), + (input) => getDiscovery(input).pipe(Effect.map((discovery) => discovery?.skills)), ).pipe( Effect.provideService(ServerSettingsService, serverSettings), Effect.provideService(FileSystem.FileSystem, fileSystem), diff --git a/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts b/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts index 258b50d6f2..aa7e5a2692 100644 --- a/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts +++ b/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts @@ -42,11 +42,11 @@ describe("EventNdjsonLogger", () => { yield* logger.write( { threadId: "provider-thread-1", id: "evt-1" }, - ThreadId.makeUnsafe("thread-1"), + ThreadId.make("thread-1"), ); yield* logger.write( { type: "turn.completed", threadId: "provider-thread-2", id: "evt-2" }, - ThreadId.makeUnsafe("thread-2"), + ThreadId.make("thread-2"), ); yield* logger.close(); @@ -112,6 +112,49 @@ describe("EventNdjsonLogger", () => { }), ); + it.effect("serializes concurrent first writes for the same segment", () => + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-")); + const basePath = path.join(tempDir, "provider-canonical.ndjson"); + + try { + const logger = yield* makeEventNdjsonLogger(basePath, { + stream: "canonical", + batchWindowMs: 0, + }); + assert.notEqual(logger, undefined); + if (!logger) { + return; + } + + yield* Effect.all( + [ + logger.write({ id: "evt-concurrent-1" }, null), + logger.write({ id: "evt-concurrent-2" }, null), + ], + { concurrency: "unbounded" }, + ); + yield* logger.close(); + + const globalPath = path.join(tempDir, "_global.log"); + assert.equal(fs.existsSync(globalPath), true); + const lines = fs + .readFileSync(globalPath, "utf8") + .trim() + .split("\n") + .map((line) => parseLogLine(line)); + + assert.equal(lines.length, 2); + assert.deepEqual(lines.map((line) => line.payload).toSorted(), [ + '{"id":"evt-concurrent-1"}', + '{"id":"evt-concurrent-2"}', + ]); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ); + it.effect("rotates per-thread files when max size is exceeded", () => Effect.gen(function* () { const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-")); @@ -135,7 +178,7 @@ describe("EventNdjsonLogger", () => { id: `evt-${index}`, payload: "x".repeat(40), }, - ThreadId.makeUnsafe("thread-rotate"), + ThreadId.make("thread-rotate"), ); } yield* logger.close(); diff --git a/apps/server/src/provider/Layers/EventNdjsonLogger.ts b/apps/server/src/provider/Layers/EventNdjsonLogger.ts index 28b7ecf611..2a512efe66 100644 --- a/apps/server/src/provider/Layers/EventNdjsonLogger.ts +++ b/apps/server/src/provider/Layers/EventNdjsonLogger.ts @@ -10,7 +10,7 @@ import path from "node:path"; import type { ThreadId } from "@t3tools/contracts"; import { RotatingFileSink } from "@t3tools/shared/logging"; -import { Effect, Exit, Logger, Scope } from "effect"; +import { Effect, Exit, Logger, Scope, SynchronizedRef } from "effect"; import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts"; @@ -40,6 +40,11 @@ interface ThreadWriter { close: () => Effect.Effect; } +interface LoggerState { + readonly threadWriters: Map; + readonly failedSegments: Set; +} + function logWarning(message: string, context: Record): Effect.Effect { return Effect.logWarning(message, context).pipe(Effect.annotateLogs({ scope: LOG_SCOPE })); } @@ -74,184 +79,213 @@ function resolveStreamLabel(stream: EventNdjsonStream): string { } } -function toLogMessage(event: unknown): Effect.Effect { - return Effect.gen(function* () { - const serialized = yield* Effect.sync(() => { - try { - return { ok: true as const, value: JSON.stringify(event) }; - } catch (error) { - return { ok: false as const, error }; - } - }); - - if (!serialized.ok) { - yield* logWarning("failed to serialize provider event log record", { - error: serialized.error, - }); - return undefined; +const toLogMessage = Effect.fn("toLogMessage")(function* ( + event: unknown, +): Effect.fn.Return { + const serialized = yield* Effect.sync(() => { + try { + return { ok: true as const, value: JSON.stringify(event) }; + } catch (error) { + return { ok: false as const, error }; } - - if (typeof serialized.value !== "string") { - return undefined; - } - - return serialized.value; }); -} -function makeThreadWriter(input: { + if (!serialized.ok) { + yield* logWarning("failed to serialize provider event log record", { + error: serialized.error, + }); + return undefined; + } + + if (typeof serialized.value !== "string") { + return undefined; + } + + return serialized.value; +}); + +const makeThreadWriter = Effect.fn("makeThreadWriter")(function* (input: { readonly filePath: string; readonly maxBytes: number; readonly maxFiles: number; readonly batchWindowMs: number; readonly streamLabel: string; -}): Effect.Effect { - return Effect.gen(function* () { - const sinkResult = yield* Effect.sync(() => { - try { - return { - ok: true as const, - sink: new RotatingFileSink({ - filePath: input.filePath, - maxBytes: input.maxBytes, - maxFiles: input.maxFiles, - throwOnError: true, - }), - }; - } catch (error) { - return { ok: false as const, error }; - } - }); - - if (!sinkResult.ok) { - yield* logWarning("failed to initialize provider thread log file", { - filePath: input.filePath, - error: sinkResult.error, - }); - return undefined; - } - - const sink = sinkResult.sink; - const scope = yield* Scope.make(); - const lineLogger = makeLineLogger(input.streamLabel); - const batchedLogger = yield* Logger.batched(lineLogger, { - window: input.batchWindowMs, - flush: (messages) => - Effect.gen(function* () { - const flushResult = yield* Effect.sync(() => { - try { - for (const message of messages) { - sink.write(message); - } - return { ok: true as const }; - } catch (error) { - return { ok: false as const, error }; - } - }); - - if (!flushResult.ok) { - yield* logWarning("provider event log batch flush failed", { - filePath: input.filePath, - error: flushResult.error, - }); - } +}): Effect.fn.Return { + const sinkResult = yield* Effect.sync(() => { + try { + return { + ok: true as const, + sink: new RotatingFileSink({ + filePath: input.filePath, + maxBytes: input.maxBytes, + maxFiles: input.maxFiles, + throwOnError: true, }), - }).pipe(Effect.provideService(Scope.Scope, scope)); - - const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false }); - - return { - writeMessage(message: string) { - return Effect.log(message).pipe(Effect.provide(loggerLayer)); - }, - close() { - return Scope.close(scope, Exit.void); - }, - } satisfies ThreadWriter; + }; + } catch (error) { + return { ok: false as const, error }; + } }); -} -export function makeEventNdjsonLogger( + if (!sinkResult.ok) { + yield* logWarning("failed to initialize provider thread log file", { + filePath: input.filePath, + error: sinkResult.error, + }); + return undefined; + } + + const sink = sinkResult.sink; + const scope = yield* Scope.make(); + const lineLogger = makeLineLogger(input.streamLabel); + const batchedLogger = yield* Logger.batched(lineLogger, { + window: input.batchWindowMs, + flush: Effect.fn("makeThreadWriter.flush")(function* (messages) { + const flushResult = yield* Effect.sync(() => { + try { + for (const message of messages) { + sink.write(message); + } + return { ok: true as const }; + } catch (error) { + return { ok: false as const, error }; + } + }); + + if (!flushResult.ok) { + yield* logWarning("provider event log batch flush failed", { + filePath: input.filePath, + error: flushResult.error, + }); + } + }), + }).pipe(Effect.provideService(Scope.Scope, scope)); + + const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false }); + + return { + writeMessage(message: string) { + return Effect.log(message).pipe(Effect.provide(loggerLayer)); + }, + close() { + return Scope.close(scope, Exit.void); + }, + } satisfies ThreadWriter; +}); + +export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function* ( filePath: string, options: EventNdjsonLoggerOptions, -): Effect.Effect { - return Effect.gen(function* () { - const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES; - const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES; - const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS; - const streamLabel = resolveStreamLabel(options.stream); +): Effect.fn.Return { + const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES; + const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES; + const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS; + const streamLabel = resolveStreamLabel(options.stream); - const directoryReady = yield* Effect.sync(() => { - try { - fs.mkdirSync(path.dirname(filePath), { recursive: true }); - return true; - } catch (error) { - return { ok: false as const, error }; - } + const directoryReady = yield* Effect.sync(() => { + try { + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + return true; + } catch (error) { + return { ok: false as const, error }; + } + }); + if (directoryReady !== true) { + yield* logWarning("failed to create provider event log directory", { + filePath, + error: directoryReady.error, }); - if (directoryReady !== true) { - yield* logWarning("failed to create provider event log directory", { - filePath, - error: directoryReady.error, - }); - return undefined; + return undefined; + } + + const stateRef = yield* SynchronizedRef.make({ + threadWriters: new Map(), + failedSegments: new Set(), + }); + + const resolveThreadWriter = Effect.fn("resolveThreadWriter")(function* ( + threadSegment: string, + ): Effect.fn.Return { + return yield* SynchronizedRef.modifyEffect(stateRef, (state) => { + if (state.failedSegments.has(threadSegment)) { + return Effect.succeed([undefined, state] as const); + } + + const existing = state.threadWriters.get(threadSegment); + if (existing) { + return Effect.succeed([existing, state] as const); + } + + return makeThreadWriter({ + filePath: path.join(path.dirname(filePath), `${threadSegment}.log`), + maxBytes, + maxFiles, + batchWindowMs, + streamLabel, + }).pipe( + Effect.map((writer) => { + if (!writer) { + const nextFailedSegments = new Set(state.failedSegments); + nextFailedSegments.add(threadSegment); + return [ + undefined, + { + ...state, + failedSegments: nextFailedSegments, + }, + ] as const; + } + + const nextThreadWriters = new Map(state.threadWriters); + nextThreadWriters.set(threadSegment, writer); + return [ + writer, + { + ...state, + threadWriters: nextThreadWriters, + }, + ] as const; + }), + ); + }); + }); + + const write = Effect.fn("write")(function* (event: unknown, threadId: ThreadId | null) { + const threadSegment = resolveThreadSegment(threadId); + const message = yield* toLogMessage(event); + if (!message) { + return; } - const threadWriters = new Map(); - const failedSegments = new Set(); + const writer = yield* resolveThreadWriter(threadSegment); + if (!writer) { + return; + } - const resolveThreadWriter = (threadSegment: string): Effect.Effect => - Effect.gen(function* () { - if (failedSegments.has(threadSegment)) { - return undefined; - } - const existing = threadWriters.get(threadSegment); - if (existing) { - return existing; - } - - const writer = yield* makeThreadWriter({ - filePath: path.join(path.dirname(filePath), `${threadSegment}.log`), - maxBytes, - maxFiles, - batchWindowMs, - streamLabel, - }); - if (!writer) { - failedSegments.add(threadSegment); - return undefined; - } - - threadWriters.set(threadSegment, writer); - return writer; - }); - - return { - filePath, - write(event: unknown, threadId: ThreadId | null) { - return Effect.gen(function* () { - const threadSegment = resolveThreadSegment(threadId); - const message = yield* toLogMessage(event); - if (!message) { - return; - } - - const writer = yield* resolveThreadWriter(threadSegment); - if (!writer) { - return; - } - - yield* writer.writeMessage(message); - }); - }, - close() { - return Effect.gen(function* () { - for (const writer of threadWriters.values()) { - yield* writer.close(); - } - threadWriters.clear(); - }); - }, - } satisfies EventNdjsonLogger; + yield* writer.writeMessage(message); }); -} + + const close = Effect.fn("close")(function* () { + yield* SynchronizedRef.modifyEffect(stateRef, (state) => + Effect.gen(function* () { + for (const writer of state.threadWriters.values()) { + yield* writer.close(); + } + + return [ + undefined, + { + threadWriters: new Map(), + failedSegments: new Set(), + }, + ] as const; + }), + ); + }); + + return { + filePath, + write, + close, + } satisfies EventNdjsonLogger; +}); diff --git a/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts b/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts index 23ef8d1b9b..b6c987c64c 100644 --- a/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts +++ b/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts @@ -22,30 +22,31 @@ export interface ProviderAdapterRegistryLiveOptions { readonly adapters?: ReadonlyArray>; } -const makeProviderAdapterRegistry = (options?: ProviderAdapterRegistryLiveOptions) => - Effect.gen(function* () { - const adapters = - options?.adapters !== undefined - ? options.adapters - : [yield* CodexAdapter, yield* ClaudeAdapter]; - const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter])); +const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* ( + options?: ProviderAdapterRegistryLiveOptions, +) { + const adapters = + options?.adapters !== undefined + ? options.adapters + : [yield* CodexAdapter, yield* ClaudeAdapter]; + const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter])); - const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => { - const adapter = byProvider.get(provider); - if (!adapter) { - return Effect.fail(new ProviderUnsupportedError({ provider })); - } - return Effect.succeed(adapter); - }; + const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => { + const adapter = byProvider.get(provider); + if (!adapter) { + return Effect.fail(new ProviderUnsupportedError({ provider })); + } + return Effect.succeed(adapter); + }; - const listProviders: ProviderAdapterRegistryShape["listProviders"] = () => - Effect.sync(() => Array.from(byProvider.keys())); + const listProviders: ProviderAdapterRegistryShape["listProviders"] = () => + Effect.sync(() => Array.from(byProvider.keys())); - return { - getByProvider, - listProviders, - } satisfies ProviderAdapterRegistryShape; - }); + return { + getByProvider, + listProviders, + } satisfies ProviderAdapterRegistryShape; +}); export const ProviderAdapterRegistryLive = Layer.effect( ProviderAdapterRegistry, diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index 116c008d67..9c12048e45 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -44,6 +44,7 @@ function mockHandle(result: { stdout: string; stderr: string; code: number }) { exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code)), isRunning: Effect.succeed(false), kill: () => Effect.void, + unref: Effect.succeed(Effect.void), stdin: Sink.drain, stdout: Stream.make(encoder.encode(result.stdout)), stderr: Stream.make(encoder.encode(result.stderr)), @@ -115,7 +116,9 @@ function makeMutableServerSettingsService( yield* PubSub.publish(changes, next); return next; }), - streamChanges: Stream.fromPubSub(changes), + get streamChanges() { + return Stream.fromPubSub(changes); + }, } satisfies ServerSettingsShape; }); } @@ -218,6 +221,49 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( ), ); + it.effect("includes probed codex skills in the provider snapshot", () => + Effect.gen(function* () { + yield* withTempCodexHome(); + const status = yield* checkCodexProviderStatus( + () => + Effect.succeed({ + type: "chatgpt" as const, + planType: "pro" as const, + sparkEnabled: true, + }), + () => + Effect.succeed([ + { + name: "github:gh-fix-ci", + path: "/Users/test/.codex/skills/gh-fix-ci/SKILL.md", + enabled: true, + displayName: "CI Debug", + shortDescription: "Debug failing GitHub Actions checks", + }, + ]), + ); + + assert.deepStrictEqual(status.skills, [ + { + name: "github:gh-fix-ci", + path: "/Users/test/.codex/skills/gh-fix-ci/SKILL.md", + enabled: true, + displayName: "CI Debug", + shortDescription: "Debug failing GitHub Actions checks", + }, + ]); + }).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(); @@ -496,6 +542,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( checkedAt: "2026-03-25T00:00:00.000Z", version: "1.0.0", models: [], + slashCommands: [], + skills: [], }, { provider: "claudeAgent", @@ -506,6 +554,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( checkedAt: "2026-03-25T00:00:00.000Z", version: "1.0.0", models: [], + slashCommands: [], + skills: [], }, ] as const satisfies ReadonlyArray; @@ -884,6 +934,85 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( ), ); + it.effect("includes probed claude slash commands in the provider snapshot", () => + Effect.gen(function* () { + const status = yield* checkClaudeProviderStatus( + () => Effect.succeed("maxplan"), + () => + Effect.succeed([ + { + name: "review", + description: "Review a pull request", + input: { hint: "pr-or-branch" }, + }, + ]), + ); + + assert.deepStrictEqual(status.slashCommands, [ + { + name: "review", + description: "Review a pull request", + input: { hint: "pr-or-branch" }, + }, + ]); + }).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("deduplicates probed claude slash commands by name", () => + Effect.gen(function* () { + const status = yield* checkClaudeProviderStatus( + () => Effect.succeed("maxplan"), + () => + Effect.succeed([ + { + name: "ui", + description: "Explore and refine UI", + }, + { + name: "ui", + input: { hint: "component-or-screen" }, + }, + ]), + ); + + assert.deepStrictEqual(status.slashCommands, [ + { + name: "ui", + description: "Explore and refine UI", + input: { hint: "component-or-screen" }, + }, + ]); + }).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(); diff --git a/apps/server/src/provider/Layers/ProviderRegistry.ts b/apps/server/src/provider/Layers/ProviderRegistry.ts index 1e66ce8ff5..fb2f33c293 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.ts @@ -40,18 +40,19 @@ export const ProviderRegistryLive = Layer.effect( yield* loadProviders(codexProvider, claudeProvider), ); - const syncProviders = (options?: { readonly publish?: boolean }) => - Effect.gen(function* () { - const previousProviders = yield* Ref.get(providersRef); - const providers = yield* loadProviders(codexProvider, claudeProvider); - yield* Ref.set(providersRef, providers); + const syncProviders = Effect.fn("syncProviders")(function* (options?: { + readonly publish?: boolean; + }) { + const previousProviders = yield* Ref.get(providersRef); + const providers = yield* loadProviders(codexProvider, claudeProvider); + yield* Ref.set(providersRef, providers); - if (options?.publish !== false && haveProvidersChanged(previousProviders, providers)) { - yield* PubSub.publish(changesPubSub, providers); - } + if (options?.publish !== false && haveProvidersChanged(previousProviders, providers)) { + yield* PubSub.publish(changesPubSub, providers); + } - return providers; - }); + return providers; + }); yield* Stream.runForEach(codexProvider.streamChanges, () => syncProviders()).pipe( Effect.forkScoped, @@ -60,28 +61,30 @@ export const ProviderRegistryLive = Layer.effect( Effect.forkScoped, ); + const refresh = Effect.fn("refresh")(function* (provider?: ProviderKind) { + switch (provider) { + case "codex": + yield* codexProvider.refresh; + break; + case "claudeAgent": + yield* claudeProvider.refresh; + break; + default: + yield* Effect.all([codexProvider.refresh, claudeProvider.refresh], { + concurrency: "unbounded", + }); + break; + } + return yield* syncProviders(); + }); + return { getProviders: syncProviders({ publish: false }).pipe( Effect.tapError(Effect.logError), Effect.orElseSucceed(() => []), ), refresh: (provider?: ProviderKind) => - Effect.gen(function* () { - switch (provider) { - case "codex": - yield* codexProvider.refresh; - break; - case "claudeAgent": - yield* claudeProvider.refresh; - break; - default: - yield* Effect.all([codexProvider.refresh, claudeProvider.refresh], { - concurrency: "unbounded", - }); - break; - } - return yield* syncProviders(); - }).pipe( + refresh(provider).pipe( Effect.tapError(Effect.logError), Effect.orElseSucceed(() => []), ), diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts index 651a611649..56f9f8d65c 100644 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -20,7 +20,7 @@ import { import { it, assert, vi } from "@effect/vitest"; import { assertFailure } from "@effect/vitest/utils"; -import { Effect, Fiber, Layer, Option, PubSub, Ref, Stream } from "effect"; +import { Effect, Fiber, Layer, Metric, Option, PubSub, Ref, Stream } from "effect"; import * as SqlClient from "effect/unstable/sql/SqlClient"; import { @@ -47,10 +47,10 @@ import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts"; const defaultServerSettingsLayer = ServerSettingsService.layerTest(); -const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.makeUnsafe(value); -const asEventId = (value: string): EventId => EventId.makeUnsafe(value); -const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value); -const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value); +const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value); +const asEventId = (value: string): EventId => EventId.make(value); +const asThreadId = (value: string): ThreadId => ThreadId.make(value); +const asTurnId = (value: string): TurnId => TurnId.make(value); type LegacyProviderRuntimeEvent = { readonly type: string; @@ -102,7 +102,7 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") { return Effect.succeed({ threadId: input.threadId, - turnId: TurnId.makeUnsafe(`turn-${String(input.threadId)}`), + turnId: TurnId.make(`turn-${String(input.threadId)}`), }); }, ); @@ -191,7 +191,9 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") { readThread, rollbackThread, stopAll, - streamEvents: Stream.fromPubSub(runtimeEventPubSub), + get streamEvents() { + return Stream.fromPubSub(runtimeEventPubSub); + }, }; const emit = (event: LegacyProviderRuntimeEvent): void => { @@ -230,6 +232,17 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") { const sleep = (ms: number) => Effect.promise(() => new Promise((resolve) => setTimeout(resolve, ms))); +const hasMetricSnapshot = ( + snapshots: ReadonlyArray, + id: string, + attributes: Readonly>, +) => + snapshots.some( + (snapshot) => + snapshot.id === id && + Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value), + ); + function makeProviderServiceLayer() { const codex = makeFakeCodexAdapter(); const claude = makeFakeCodexAdapter("claudeAgent"); @@ -345,7 +358,7 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", ( const directory = yield* ProviderSessionDirectory; yield* directory.upsert({ provider: "codex", - threadId: ThreadId.makeUnsafe("thread-stale"), + threadId: ThreadId.make("thread-stale"), }); }).pipe(Effect.provide(directoryLayer)); @@ -1060,6 +1073,120 @@ fanout.layer("ProviderServiceLive fanout", (it) => { ); }), ); + + it.effect("records provider metrics with the routed provider label", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + + const session = yield* provider.startSession(asThreadId("thread-metrics"), { + provider: "claudeAgent", + threadId: asThreadId("thread-metrics"), + cwd: "/tmp/project", + runtimeMode: "full-access", + }); + + yield* provider.interruptTurn({ threadId: session.threadId }); + yield* provider.respondToRequest({ + threadId: session.threadId, + requestId: asRequestId("req-metrics-1"), + decision: "accept", + }); + yield* provider.respondToUserInput({ + threadId: session.threadId, + requestId: asRequestId("req-metrics-2"), + answers: { + sandbox_mode: "workspace-write", + }, + }); + yield* provider.rollbackConversation({ + threadId: session.threadId, + numTurns: 1, + }); + yield* provider.stopSession({ threadId: session.threadId }); + + const snapshots = yield* Metric.snapshot; + + assert.equal( + hasMetricSnapshot(snapshots, "t3_provider_turns_total", { + provider: "claudeAgent", + operation: "interrupt", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_provider_turns_total", { + provider: "claudeAgent", + operation: "approval-response", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_provider_turns_total", { + provider: "claudeAgent", + operation: "user-input-response", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_provider_turns_total", { + provider: "claudeAgent", + operation: "rollback", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_provider_sessions_total", { + provider: "claudeAgent", + operation: "stop", + outcome: "success", + }), + true, + ); + }), + ); + + it.effect( + "records sendTurn metrics with the resolved provider when modelSelection is omitted", + () => + Effect.gen(function* () { + const provider = yield* ProviderService; + + const session = yield* provider.startSession(asThreadId("thread-send-metrics"), { + provider: "claudeAgent", + threadId: asThreadId("thread-send-metrics"), + cwd: "/tmp/project-send-metrics", + runtimeMode: "full-access", + }); + + yield* provider.sendTurn({ + threadId: session.threadId, + input: "hello", + attachments: [], + }); + + const snapshots = yield* Metric.snapshot; + + assert.equal( + hasMetricSnapshot(snapshots, "t3_provider_turns_total", { + provider: "claudeAgent", + operation: "send", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_provider_turn_duration", { + provider: "claudeAgent", + operation: "send", + }), + true, + ); + }), + ); }); const validation = makeProviderServiceLayer(); diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index 0137152e83..85fe9fbc32 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -22,8 +22,18 @@ import { type ProviderRuntimeEvent, type ProviderSession, } from "@t3tools/contracts"; -import { Effect, Layer, Option, PubSub, Queue, Schema, SchemaIssue, Stream } from "effect"; +import { Effect, Layer, Option, PubSub, Schema, SchemaIssue, Stream } from "effect"; +import { + increment, + providerMetricAttributes, + providerRuntimeEventsTotal, + providerSessionsTotal, + providerTurnDuration, + providerTurnsTotal, + providerTurnMetricAttributes, + withMetrics, +} from "../../observability/Metrics.ts"; import { ProviderValidationError } from "../Errors.ts"; import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts"; import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts"; @@ -131,169 +141,182 @@ function readPersistedCwd( return trimmed.length > 0 ? trimmed : undefined; } -const makeProviderService = (options?: ProviderServiceLiveOptions) => - Effect.gen(function* () { - const analytics = yield* Effect.service(AnalyticsService); - const serverSettings = yield* ServerSettingsService; - const canonicalEventLogger = - options?.canonicalEventLogger ?? - (options?.canonicalEventLogPath !== undefined - ? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, { - stream: "canonical", - }) - : undefined); +const makeProviderService = Effect.fn("makeProviderService")(function* ( + options?: ProviderServiceLiveOptions, +) { + const analytics = yield* Effect.service(AnalyticsService); + const serverSettings = yield* ServerSettingsService; + const canonicalEventLogger = + options?.canonicalEventLogger ?? + (options?.canonicalEventLogPath !== undefined + ? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, { + stream: "canonical", + }) + : undefined); - const registry = yield* ProviderAdapterRegistry; - const directory = yield* ProviderSessionDirectory; - const runtimeEventQueue = yield* Queue.unbounded(); - const runtimeEventPubSub = yield* PubSub.unbounded(); + const registry = yield* ProviderAdapterRegistry; + const directory = yield* ProviderSessionDirectory; + const runtimeEventPubSub = yield* PubSub.unbounded(); - const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect => - Effect.succeed(event).pipe( - Effect.tap((canonicalEvent) => - canonicalEventLogger ? canonicalEventLogger.write(canonicalEvent, null) : Effect.void, - ), - Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)), - Effect.asVoid, + const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect => + Effect.succeed(event).pipe( + Effect.tap((canonicalEvent) => + canonicalEventLogger ? canonicalEventLogger.write(canonicalEvent, null) : Effect.void, + ), + Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)), + Effect.asVoid, + ); + + const upsertSessionBinding = ( + session: ProviderSession, + threadId: ThreadId, + extra?: { + readonly modelSelection?: unknown; + readonly lastRuntimeEvent?: string; + readonly lastRuntimeEventAt?: string; + }, + ) => + directory.upsert({ + threadId, + provider: session.provider, + runtimeMode: session.runtimeMode, + status: toRuntimeStatus(session), + ...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}), + runtimePayload: toRuntimePayloadFromSession(session, extra), + }); + + const providers = yield* registry.listProviders(); + const adapters = yield* Effect.forEach(providers, (provider) => registry.getByProvider(provider)); + const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect => + increment(providerRuntimeEventsTotal, { + provider: event.provider, + eventType: event.type, + }).pipe(Effect.andThen(publishRuntimeEvent(event))); + + yield* Effect.forEach(adapters, (adapter) => + Stream.runForEach(adapter.streamEvents, processRuntimeEvent).pipe(Effect.forkScoped), + ).pipe(Effect.asVoid); + + const recoverSessionForThread = Effect.fn("recoverSessionForThread")(function* (input: { + readonly binding: ProviderRuntimeBinding; + readonly operation: string; + }) { + yield* Effect.annotateCurrentSpan({ + "provider.operation": "recover-session", + "provider.kind": input.binding.provider, + "provider.thread_id": input.binding.threadId, + }); + return yield* Effect.gen(function* () { + const adapter = yield* registry.getByProvider(input.binding.provider); + const hasResumeCursor = + input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined; + const hasActiveSession = yield* adapter.hasSession(input.binding.threadId); + if (hasActiveSession) { + const activeSessions = yield* adapter.listSessions(); + const existing = activeSessions.find( + (session) => session.threadId === input.binding.threadId, + ); + if (existing) { + yield* upsertSessionBinding(existing, input.binding.threadId); + yield* analytics.record("provider.session.recovered", { + provider: existing.provider, + strategy: "adopt-existing", + hasResumeCursor: existing.resumeCursor !== undefined, + }); + return { adapter, session: existing } as const; + } + } + + if (!hasResumeCursor) { + return yield* toValidationError( + input.operation, + `Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`, + ); + } + + const persistedCwd = readPersistedCwd(input.binding.runtimePayload); + const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload); + + const resumed = yield* adapter.startSession({ + threadId: input.binding.threadId, + provider: input.binding.provider, + ...(persistedCwd ? { cwd: persistedCwd } : {}), + ...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}), + ...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}), + runtimeMode: input.binding.runtimeMode ?? "full-access", + }); + if (resumed.provider !== adapter.provider) { + return yield* toValidationError( + input.operation, + `Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`, + ); + } + + yield* upsertSessionBinding(resumed, input.binding.threadId); + yield* analytics.record("provider.session.recovered", { + provider: resumed.provider, + strategy: "resume-thread", + hasResumeCursor: resumed.resumeCursor !== undefined, + }); + return { adapter, session: resumed } as const; + }).pipe( + withMetrics({ + counter: providerSessionsTotal, + attributes: providerMetricAttributes(input.binding.provider, { + operation: "recover", + }), + }), + ); + }); + + const resolveRoutableSession = Effect.fn("resolveRoutableSession")(function* (input: { + readonly threadId: ThreadId; + readonly operation: string; + readonly allowRecovery: boolean; + }) { + const bindingOption = yield* directory.getBinding(input.threadId); + const binding = Option.getOrUndefined(bindingOption); + if (!binding) { + return yield* toValidationError( + input.operation, + `Cannot route thread '${input.threadId}' because no persisted provider binding exists.`, ); + } + const adapter = yield* registry.getByProvider(binding.provider); - const upsertSessionBinding = ( - session: ProviderSession, - threadId: ThreadId, - extra?: { - readonly modelSelection?: unknown; - readonly lastRuntimeEvent?: string; - readonly lastRuntimeEventAt?: string; - }, - ) => - directory.upsert({ + const hasRequestedSession = yield* adapter.hasSession(input.threadId); + if (hasRequestedSession) { + return { adapter, threadId: input.threadId, isActive: true } as const; + } + + if (!input.allowRecovery) { + return { adapter, threadId: input.threadId, isActive: false } as const; + } + + const recovered = yield* recoverSessionForThread({ binding, operation: input.operation }); + return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const; + }); + + const startSession: ProviderServiceShape["startSession"] = Effect.fn("startSession")( + function* (threadId, rawInput) { + const parsed = yield* decodeInputOrValidationError({ + operation: "ProviderService.startSession", + schema: ProviderSessionStartInput, + payload: rawInput, + }); + + const input = { + ...parsed, threadId, - provider: session.provider, - runtimeMode: session.runtimeMode, - status: toRuntimeStatus(session), - ...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}), - runtimePayload: toRuntimePayloadFromSession(session, extra), + provider: parsed.provider ?? "codex", + }; + yield* Effect.annotateCurrentSpan({ + "provider.operation": "start-session", + "provider.kind": input.provider, + "provider.thread_id": threadId, + "provider.runtime_mode": input.runtimeMode, }); - - const providers = yield* registry.listProviders(); - const adapters = yield* Effect.forEach(providers, (provider) => - registry.getByProvider(provider), - ); - const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect => - publishRuntimeEvent(event); - - const worker = Effect.forever( - Queue.take(runtimeEventQueue).pipe(Effect.flatMap(processRuntimeEvent)), - ); - yield* Effect.forkScoped(worker); - - yield* Effect.forEach(adapters, (adapter) => - Stream.runForEach(adapter.streamEvents, (event) => - Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid), - ).pipe(Effect.forkScoped), - ).pipe(Effect.asVoid); - - const recoverSessionForThread = (input: { - readonly binding: ProviderRuntimeBinding; - readonly operation: string; - }) => - Effect.gen(function* () { - const adapter = yield* registry.getByProvider(input.binding.provider); - const hasResumeCursor = - input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined; - const hasActiveSession = yield* adapter.hasSession(input.binding.threadId); - if (hasActiveSession) { - const activeSessions = yield* adapter.listSessions(); - const existing = activeSessions.find( - (session) => session.threadId === input.binding.threadId, - ); - if (existing) { - yield* upsertSessionBinding(existing, input.binding.threadId); - yield* analytics.record("provider.session.recovered", { - provider: existing.provider, - strategy: "adopt-existing", - hasResumeCursor: existing.resumeCursor !== undefined, - }); - return { adapter, session: existing } as const; - } - } - - if (!hasResumeCursor) { - return yield* toValidationError( - input.operation, - `Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`, - ); - } - - const persistedCwd = readPersistedCwd(input.binding.runtimePayload); - const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload); - - const resumed = yield* adapter.startSession({ - threadId: input.binding.threadId, - provider: input.binding.provider, - ...(persistedCwd ? { cwd: persistedCwd } : {}), - ...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}), - ...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}), - runtimeMode: input.binding.runtimeMode ?? "full-access", - }); - if (resumed.provider !== adapter.provider) { - return yield* toValidationError( - input.operation, - `Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`, - ); - } - - yield* upsertSessionBinding(resumed, input.binding.threadId); - yield* analytics.record("provider.session.recovered", { - provider: resumed.provider, - strategy: "resume-thread", - hasResumeCursor: resumed.resumeCursor !== undefined, - }); - return { adapter, session: resumed } as const; - }); - - const resolveRoutableSession = (input: { - readonly threadId: ThreadId; - readonly operation: string; - readonly allowRecovery: boolean; - }) => - Effect.gen(function* () { - const bindingOption = yield* directory.getBinding(input.threadId); - const binding = Option.getOrUndefined(bindingOption); - if (!binding) { - return yield* toValidationError( - input.operation, - `Cannot route thread '${input.threadId}' because no persisted provider binding exists.`, - ); - } - const adapter = yield* registry.getByProvider(binding.provider); - - const hasRequestedSession = yield* adapter.hasSession(input.threadId); - if (hasRequestedSession) { - return { adapter, threadId: input.threadId, isActive: true } as const; - } - - if (!input.allowRecovery) { - return { adapter, threadId: input.threadId, isActive: false } as const; - } - - const recovered = yield* recoverSessionForThread({ binding, operation: input.operation }); - return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const; - }); - - const startSession: ProviderServiceShape["startSession"] = (threadId, rawInput) => - Effect.gen(function* () { - const parsed = yield* decodeInputOrValidationError({ - operation: "ProviderService.startSession", - schema: ProviderSessionStartInput, - payload: rawInput, - }); - - const input = { - ...parsed, - threadId, - provider: parsed.provider ?? "codex", - }; + return yield* Effect.gen(function* () { const settings = yield* serverSettings.getSettings.pipe( Effect.mapError((error) => toValidationError( @@ -342,118 +365,220 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) => }); return session; + }).pipe( + withMetrics({ + counter: providerSessionsTotal, + attributes: providerMetricAttributes(input.provider, { + operation: "start", + }), + }), + ); + }, + ); + + const sendTurn: ProviderServiceShape["sendTurn"] = Effect.fn("sendTurn")(function* (rawInput) { + const parsed = yield* decodeInputOrValidationError({ + operation: "ProviderService.sendTurn", + schema: ProviderSendTurnInput, + payload: rawInput, + }); + + const input = { + ...parsed, + attachments: parsed.attachments ?? [], + }; + if (!input.input && input.attachments.length === 0) { + return yield* toValidationError( + "ProviderService.sendTurn", + "Either input text or at least one attachment is required", + ); + } + yield* Effect.annotateCurrentSpan({ + "provider.operation": "send-turn", + "provider.thread_id": input.threadId, + "provider.interaction_mode": input.interactionMode, + "provider.attachment_count": input.attachments.length, + }); + let metricProvider = "unknown"; + let metricModel = input.modelSelection?.model; + return yield* Effect.gen(function* () { + const routed = yield* resolveRoutableSession({ + threadId: input.threadId, + operation: "ProviderService.sendTurn", + allowRecovery: true, }); - - const sendTurn: ProviderServiceShape["sendTurn"] = (rawInput) => - Effect.gen(function* () { - const parsed = yield* decodeInputOrValidationError({ - operation: "ProviderService.sendTurn", - schema: ProviderSendTurnInput, - payload: rawInput, - }); - - const input = { - ...parsed, - attachments: parsed.attachments ?? [], - }; - if (!input.input && input.attachments.length === 0) { - return yield* toValidationError( - "ProviderService.sendTurn", - "Either input text or at least one attachment is required", - ); - } - const routed = yield* resolveRoutableSession({ - threadId: input.threadId, - operation: "ProviderService.sendTurn", - allowRecovery: true, - }); - const turn = yield* routed.adapter.sendTurn(input); - yield* directory.upsert({ - threadId: input.threadId, - provider: routed.adapter.provider, - status: "running", - ...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}), - runtimePayload: { - ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}), - activeTurnId: turn.turnId, - lastRuntimeEvent: "provider.sendTurn", - lastRuntimeEventAt: new Date().toISOString(), - }, - }); - yield* analytics.record("provider.turn.sent", { - provider: routed.adapter.provider, - model: input.modelSelection?.model, - interactionMode: input.interactionMode, - attachmentCount: input.attachments.length, - hasInput: typeof input.input === "string" && input.input.trim().length > 0, - }); - return turn; + metricProvider = routed.adapter.provider; + metricModel = input.modelSelection?.model; + yield* Effect.annotateCurrentSpan({ + "provider.kind": routed.adapter.provider, + ...(input.modelSelection?.model ? { "provider.model": input.modelSelection.model } : {}), }); + const turn = yield* routed.adapter.sendTurn(input); + yield* directory.upsert({ + threadId: input.threadId, + provider: routed.adapter.provider, + status: "running", + ...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}), + runtimePayload: { + ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}), + activeTurnId: turn.turnId, + lastRuntimeEvent: "provider.sendTurn", + lastRuntimeEventAt: new Date().toISOString(), + }, + }); + yield* analytics.record("provider.turn.sent", { + provider: routed.adapter.provider, + model: input.modelSelection?.model, + interactionMode: input.interactionMode, + attachmentCount: input.attachments.length, + hasInput: typeof input.input === "string" && input.input.trim().length > 0, + }); + return turn; + }).pipe( + withMetrics({ + counter: providerTurnsTotal, + timer: providerTurnDuration, + attributes: () => + providerTurnMetricAttributes({ + provider: metricProvider, + model: metricModel, + extra: { + operation: "send", + }, + }), + }), + ); + }); - const interruptTurn: ProviderServiceShape["interruptTurn"] = (rawInput) => - Effect.gen(function* () { - const input = yield* decodeInputOrValidationError({ - operation: "ProviderService.interruptTurn", - schema: ProviderInterruptTurnInput, - payload: rawInput, - }); + const interruptTurn: ProviderServiceShape["interruptTurn"] = Effect.fn("interruptTurn")( + function* (rawInput) { + const input = yield* decodeInputOrValidationError({ + operation: "ProviderService.interruptTurn", + schema: ProviderInterruptTurnInput, + payload: rawInput, + }); + let metricProvider = "unknown"; + return yield* Effect.gen(function* () { const routed = yield* resolveRoutableSession({ threadId: input.threadId, operation: "ProviderService.interruptTurn", allowRecovery: true, }); + metricProvider = routed.adapter.provider; + yield* Effect.annotateCurrentSpan({ + "provider.operation": "interrupt-turn", + "provider.kind": routed.adapter.provider, + "provider.thread_id": input.threadId, + "provider.turn_id": input.turnId, + }); yield* routed.adapter.interruptTurn(routed.threadId, input.turnId); yield* analytics.record("provider.turn.interrupted", { provider: routed.adapter.provider, }); - }); + }).pipe( + withMetrics({ + counter: providerTurnsTotal, + outcomeAttributes: () => + providerMetricAttributes(metricProvider, { + operation: "interrupt", + }), + }), + ); + }, + ); - const respondToRequest: ProviderServiceShape["respondToRequest"] = (rawInput) => - Effect.gen(function* () { - const input = yield* decodeInputOrValidationError({ - operation: "ProviderService.respondToRequest", - schema: ProviderRespondToRequestInput, - payload: rawInput, - }); + const respondToRequest: ProviderServiceShape["respondToRequest"] = Effect.fn("respondToRequest")( + function* (rawInput) { + const input = yield* decodeInputOrValidationError({ + operation: "ProviderService.respondToRequest", + schema: ProviderRespondToRequestInput, + payload: rawInput, + }); + let metricProvider = "unknown"; + return yield* Effect.gen(function* () { const routed = yield* resolveRoutableSession({ threadId: input.threadId, operation: "ProviderService.respondToRequest", allowRecovery: true, }); + metricProvider = routed.adapter.provider; + yield* Effect.annotateCurrentSpan({ + "provider.operation": "respond-to-request", + "provider.kind": routed.adapter.provider, + "provider.thread_id": input.threadId, + "provider.request_id": input.requestId, + }); yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision); yield* analytics.record("provider.request.responded", { provider: routed.adapter.provider, decision: input.decision, }); - }); + }).pipe( + withMetrics({ + counter: providerTurnsTotal, + outcomeAttributes: () => + providerMetricAttributes(metricProvider, { + operation: "approval-response", + }), + }), + ); + }, + ); - const respondToUserInput: ProviderServiceShape["respondToUserInput"] = (rawInput) => - Effect.gen(function* () { - const input = yield* decodeInputOrValidationError({ - operation: "ProviderService.respondToUserInput", - schema: ProviderRespondToUserInputInput, - payload: rawInput, - }); - const routed = yield* resolveRoutableSession({ - threadId: input.threadId, - operation: "ProviderService.respondToUserInput", - allowRecovery: true, - }); - yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers); + const respondToUserInput: ProviderServiceShape["respondToUserInput"] = Effect.fn( + "respondToUserInput", + )(function* (rawInput) { + const input = yield* decodeInputOrValidationError({ + operation: "ProviderService.respondToUserInput", + schema: ProviderRespondToUserInputInput, + payload: rawInput, + }); + let metricProvider = "unknown"; + return yield* Effect.gen(function* () { + const routed = yield* resolveRoutableSession({ + threadId: input.threadId, + operation: "ProviderService.respondToUserInput", + allowRecovery: true, }); + metricProvider = routed.adapter.provider; + yield* Effect.annotateCurrentSpan({ + "provider.operation": "respond-to-user-input", + "provider.kind": routed.adapter.provider, + "provider.thread_id": input.threadId, + "provider.request_id": input.requestId, + }); + yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers); + }).pipe( + withMetrics({ + counter: providerTurnsTotal, + outcomeAttributes: () => + providerMetricAttributes(metricProvider, { + operation: "user-input-response", + }), + }), + ); + }); - const stopSession: ProviderServiceShape["stopSession"] = (rawInput) => - Effect.gen(function* () { - const input = yield* decodeInputOrValidationError({ - operation: "ProviderService.stopSession", - schema: ProviderStopSessionInput, - payload: rawInput, - }); + const stopSession: ProviderServiceShape["stopSession"] = Effect.fn("stopSession")( + function* (rawInput) { + const input = yield* decodeInputOrValidationError({ + operation: "ProviderService.stopSession", + schema: ProviderStopSessionInput, + payload: rawInput, + }); + let metricProvider = "unknown"; + return yield* Effect.gen(function* () { const routed = yield* resolveRoutableSession({ threadId: input.threadId, operation: "ProviderService.stopSession", allowRecovery: false, }); + metricProvider = routed.adapter.provider; + yield* Effect.annotateCurrentSpan({ + "provider.operation": "stop-session", + "provider.kind": routed.adapter.provider, + "provider.thread_id": input.threadId, + }); if (routed.isActive) { yield* routed.adapter.stopSession(routed.threadId); } @@ -461,142 +586,169 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) => yield* analytics.record("provider.session.stopped", { provider: routed.adapter.provider, }); - }); + }).pipe( + withMetrics({ + counter: providerSessionsTotal, + outcomeAttributes: () => + providerMetricAttributes(metricProvider, { + operation: "stop", + }), + }), + ); + }, + ); - const listSessions: ProviderServiceShape["listSessions"] = () => - Effect.gen(function* () { - const sessionsByProvider = yield* Effect.forEach(adapters, (adapter) => - adapter.listSessions(), - ); - const activeSessions = sessionsByProvider.flatMap((sessions) => sessions); - const persistedBindings = yield* directory.listThreadIds().pipe( - Effect.flatMap((threadIds) => - Effect.forEach( - threadIds, - (threadId) => - directory - .getBinding(threadId) - .pipe(Effect.orElseSucceed(() => Option.none())), - { concurrency: "unbounded" }, - ), + const listSessions: ProviderServiceShape["listSessions"] = Effect.fn("listSessions")( + function* () { + const sessionsByProvider = yield* Effect.forEach(adapters, (adapter) => + adapter.listSessions(), + ); + const activeSessions = sessionsByProvider.flatMap((sessions) => sessions); + const persistedBindings = yield* directory.listThreadIds().pipe( + Effect.flatMap((threadIds) => + Effect.forEach( + threadIds, + (threadId) => + directory + .getBinding(threadId) + .pipe(Effect.orElseSucceed(() => Option.none())), + { concurrency: "unbounded" }, ), - Effect.orElseSucceed(() => [] as Array>), - ); - const bindingsByThreadId = new Map(); - for (const bindingOption of persistedBindings) { - const binding = Option.getOrUndefined(bindingOption); - if (binding) { - bindingsByThreadId.set(binding.threadId, binding); - } + ), + Effect.orElseSucceed(() => [] as Array>), + ); + const bindingsByThreadId = new Map(); + for (const bindingOption of persistedBindings) { + const binding = Option.getOrUndefined(bindingOption); + if (binding) { + bindingsByThreadId.set(binding.threadId, binding); + } + } + + return activeSessions.map((session) => { + const binding = bindingsByThreadId.get(session.threadId); + if (!binding) { + return session; } - return activeSessions.map((session) => { - const binding = bindingsByThreadId.get(session.threadId); - if (!binding) { - return session; - } - - const overrides: { - resumeCursor?: ProviderSession["resumeCursor"]; - runtimeMode?: ProviderSession["runtimeMode"]; - } = {}; - if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) { - overrides.resumeCursor = binding.resumeCursor; - } - if (binding.runtimeMode !== undefined) { - overrides.runtimeMode = binding.runtimeMode; - } - return Object.assign({}, session, overrides); - }); - }); - - const getCapabilities: ProviderServiceShape["getCapabilities"] = (provider) => - registry.getByProvider(provider).pipe(Effect.map((adapter) => adapter.capabilities)); - - const rollbackConversation: ProviderServiceShape["rollbackConversation"] = (rawInput) => - Effect.gen(function* () { - const input = yield* decodeInputOrValidationError({ - operation: "ProviderService.rollbackConversation", - schema: ProviderRollbackConversationInput, - payload: rawInput, - }); - if (input.numTurns === 0) { - return; + const overrides: { + resumeCursor?: ProviderSession["resumeCursor"]; + runtimeMode?: ProviderSession["runtimeMode"]; + } = {}; + if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) { + overrides.resumeCursor = binding.resumeCursor; } - const routed = yield* resolveRoutableSession({ - threadId: input.threadId, - operation: "ProviderService.rollbackConversation", - allowRecovery: true, - }); - yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns); - yield* analytics.record("provider.conversation.rolled_back", { - provider: routed.adapter.provider, - turns: input.numTurns, - }); + if (binding.runtimeMode !== undefined) { + overrides.runtimeMode = binding.runtimeMode; + } + return Object.assign({}, session, overrides); }); + }, + ); - const runStopAll = () => - Effect.gen(function* () { - const threadIds = yield* directory.listThreadIds(); - const activeSessions = yield* Effect.forEach(adapters, (adapter) => - adapter.listSessions(), - ).pipe( - Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)), - ); - yield* Effect.forEach(activeSessions, (session) => - upsertSessionBinding(session, session.threadId, { - lastRuntimeEvent: "provider.stopAll", - lastRuntimeEventAt: new Date().toISOString(), + const getCapabilities: ProviderServiceShape["getCapabilities"] = (provider) => + registry.getByProvider(provider).pipe(Effect.map((adapter) => adapter.capabilities)); + + const rollbackConversation: ProviderServiceShape["rollbackConversation"] = Effect.fn( + "rollbackConversation", + )(function* (rawInput) { + const input = yield* decodeInputOrValidationError({ + operation: "ProviderService.rollbackConversation", + schema: ProviderRollbackConversationInput, + payload: rawInput, + }); + if (input.numTurns === 0) { + return; + } + let metricProvider = "unknown"; + return yield* Effect.gen(function* () { + const routed = yield* resolveRoutableSession({ + threadId: input.threadId, + operation: "ProviderService.rollbackConversation", + allowRecovery: true, + }); + metricProvider = routed.adapter.provider; + yield* Effect.annotateCurrentSpan({ + "provider.operation": "rollback-conversation", + "provider.kind": routed.adapter.provider, + "provider.thread_id": input.threadId, + "provider.rollback_turns": input.numTurns, + }); + yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns); + yield* analytics.record("provider.conversation.rolled_back", { + provider: routed.adapter.provider, + turns: input.numTurns, + }); + }).pipe( + withMetrics({ + counter: providerTurnsTotal, + outcomeAttributes: () => + providerMetricAttributes(metricProvider, { + operation: "rollback", }), - ).pipe(Effect.asVoid); - yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid); - yield* Effect.forEach(threadIds, (threadId) => - directory.getProvider(threadId).pipe( - Effect.flatMap((provider) => - directory.upsert({ - threadId, - provider, - status: "stopped", - runtimePayload: { - activeTurnId: null, - lastRuntimeEvent: "provider.stopAll", - lastRuntimeEventAt: new Date().toISOString(), - }, - }), - ), - ), - ).pipe(Effect.asVoid); - yield* analytics.record("provider.sessions.stopped_all", { - sessionCount: threadIds.length, - }); - yield* analytics.flush; - }); - - yield* Effect.addFinalizer(() => - Effect.catch(runStopAll(), (cause) => - Effect.logWarning("failed to stop provider service", { cause }), - ), + }), ); - - return { - startSession, - sendTurn, - interruptTurn, - respondToRequest, - respondToUserInput, - stopSession, - listSessions, - getCapabilities, - rollbackConversation, - // Each access creates a fresh PubSub subscription so that multiple - // consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each - // independently receive all runtime events. - get streamEvents(): ProviderServiceShape["streamEvents"] { - return Stream.fromPubSub(runtimeEventPubSub); - }, - } satisfies ProviderServiceShape; }); + const runStopAll = Effect.fn("runStopAll")(function* () { + const threadIds = yield* directory.listThreadIds(); + const activeSessions = yield* Effect.forEach(adapters, (adapter) => + adapter.listSessions(), + ).pipe(Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions))); + yield* Effect.forEach(activeSessions, (session) => + upsertSessionBinding(session, session.threadId, { + lastRuntimeEvent: "provider.stopAll", + lastRuntimeEventAt: new Date().toISOString(), + }), + ).pipe(Effect.asVoid); + yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid); + yield* Effect.forEach(threadIds, (threadId) => + directory.getProvider(threadId).pipe( + Effect.flatMap((provider) => + directory.upsert({ + threadId, + provider, + status: "stopped", + runtimePayload: { + activeTurnId: null, + lastRuntimeEvent: "provider.stopAll", + lastRuntimeEventAt: new Date().toISOString(), + }, + }), + ), + ), + ).pipe(Effect.asVoid); + yield* analytics.record("provider.sessions.stopped_all", { + sessionCount: threadIds.length, + }); + yield* analytics.flush; + }); + + yield* Effect.addFinalizer(() => + Effect.catch(runStopAll(), (cause) => + Effect.logWarning("failed to stop provider service", { cause }), + ), + ); + + return { + startSession, + sendTurn, + interruptTurn, + respondToRequest, + respondToUserInput, + stopSession, + listSessions, + getCapabilities, + rollbackConversation, + // Each access creates a fresh PubSub subscription so that multiple + // consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each + // independently receive all runtime events. + get streamEvents(): ProviderServiceShape["streamEvents"] { + return Stream.fromPubSub(runtimeEventPubSub); + }, + } satisfies ProviderServiceShape; +}); + export const ProviderServiceLive = Layer.effect(ProviderService, makeProviderService()); export function makeProviderServiceLive(options?: ProviderServiceLiveOptions) { diff --git a/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts b/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts index d23b247f21..3ffd6941ad 100644 --- a/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts +++ b/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts @@ -36,7 +36,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL const directory = yield* ProviderSessionDirectory; const runtimeRepository = yield* ProviderSessionRuntimeRepository; - const initialThreadId = ThreadId.makeUnsafe("thread-1"); + const initialThreadId = ThreadId.make("thread-1"); yield* directory.upsert({ provider: "codex", @@ -54,7 +54,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL assert.equal(resolvedBinding.value.threadId, initialThreadId); } - const nextThreadId = ThreadId.makeUnsafe("thread-2"); + const nextThreadId = ThreadId.make("thread-2"); yield* directory.upsert({ provider: "codex", @@ -93,7 +93,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL const directory = yield* ProviderSessionDirectory; const runtimeRepository = yield* ProviderSessionRuntimeRepository; - const threadId = ThreadId.makeUnsafe("thread-runtime"); + const threadId = ThreadId.make("thread-runtime"); yield* directory.upsert({ provider: "codex", @@ -137,7 +137,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL Effect.gen(function* () { const directory = yield* ProviderSessionDirectory; const runtimeRepository = yield* ProviderSessionRuntimeRepository; - const threadId = ThreadId.makeUnsafe("thread-provider-change"); + const threadId = ThreadId.make("thread-provider-change"); yield* runtimeRepository.upsert({ threadId, @@ -169,7 +169,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL const dbPath = path.join(tempDir, "orchestration.sqlite"); const directoryLayer = makeDirectoryLayer(makeSqlitePersistenceLive(dbPath)); - const threadId = ThreadId.makeUnsafe("thread-restart"); + const threadId = ThreadId.make("thread-restart"); yield* Effect.gen(function* () { const directory = yield* ProviderSessionDirectory; diff --git a/apps/server/src/provider/Services/ClaudeAdapter.ts b/apps/server/src/provider/Services/ClaudeAdapter.ts index 3a3f616ea5..e8c33bd8e4 100644 --- a/apps/server/src/provider/Services/ClaudeAdapter.ts +++ b/apps/server/src/provider/Services/ClaudeAdapter.ts @@ -5,12 +5,12 @@ * provider runtime events. It does not perform cross-provider routing, shared * event fan-out, or checkpoint orchestration. * - * Uses Effect `ServiceMap.Service` for dependency injection and returns the + * Uses Effect `Context.Service` for dependency injection and returns the * shared provider-adapter error channel with `provider: "claudeAgent"` context. * * @module ClaudeAdapter */ -import { ServiceMap } from "effect"; +import { Context } from "effect"; import type { ProviderAdapterError } from "../Errors.ts"; import type { ProviderAdapterShape } from "./ProviderAdapter.ts"; @@ -25,6 +25,6 @@ export interface ClaudeAdapterShape extends ProviderAdapterShape()( +export class ClaudeAdapter extends Context.Service()( "t3/provider/Services/ClaudeAdapter", ) {} diff --git a/apps/server/src/provider/Services/ClaudeProvider.ts b/apps/server/src/provider/Services/ClaudeProvider.ts index 18ee8a4f6d..7f90c549c6 100644 --- a/apps/server/src/provider/Services/ClaudeProvider.ts +++ b/apps/server/src/provider/Services/ClaudeProvider.ts @@ -1,9 +1,9 @@ -import { ServiceMap } from "effect"; +import { Context } from "effect"; import type { ServerProviderShape } from "./ServerProvider"; export interface ClaudeProviderShape extends ServerProviderShape {} -export class ClaudeProvider extends ServiceMap.Service()( +export class ClaudeProvider extends Context.Service()( "t3/provider/Services/ClaudeProvider", ) {} diff --git a/apps/server/src/provider/Services/CodexAdapter.ts b/apps/server/src/provider/Services/CodexAdapter.ts index c9f944bb96..e7a5508c9c 100644 --- a/apps/server/src/provider/Services/CodexAdapter.ts +++ b/apps/server/src/provider/Services/CodexAdapter.ts @@ -5,12 +5,12 @@ * Codex provider events. It does not perform cross-provider routing, shared * event fan-out, or checkpoint orchestration. * - * Uses Effect `ServiceMap.Service` for dependency injection and returns the + * Uses Effect `Context.Service` for dependency injection and returns the * shared provider-adapter error channel with `provider: "codex"` context. * * @module CodexAdapter */ -import { ServiceMap } from "effect"; +import { Context } from "effect"; import type { ProviderAdapterError } from "../Errors.ts"; import type { ProviderAdapterShape } from "./ProviderAdapter.ts"; @@ -25,6 +25,6 @@ export interface CodexAdapterShape extends ProviderAdapterShape()( +export class CodexAdapter extends Context.Service()( "t3/provider/Services/CodexAdapter", ) {} diff --git a/apps/server/src/provider/Services/CodexProvider.ts b/apps/server/src/provider/Services/CodexProvider.ts index 2e9b57c89b..6820d4cb4f 100644 --- a/apps/server/src/provider/Services/CodexProvider.ts +++ b/apps/server/src/provider/Services/CodexProvider.ts @@ -1,9 +1,9 @@ -import { ServiceMap } from "effect"; +import { Context } from "effect"; import type { ServerProviderShape } from "./ServerProvider"; export interface CodexProviderShape extends ServerProviderShape {} -export class CodexProvider extends ServiceMap.Service()( +export class CodexProvider extends Context.Service()( "t3/provider/Services/CodexProvider", ) {} diff --git a/apps/server/src/provider/Services/ProviderAdapterRegistry.ts b/apps/server/src/provider/Services/ProviderAdapterRegistry.ts index 490c4d3d14..b8e9d4b21c 100644 --- a/apps/server/src/provider/Services/ProviderAdapterRegistry.ts +++ b/apps/server/src/provider/Services/ProviderAdapterRegistry.ts @@ -8,7 +8,7 @@ * @module ProviderAdapterRegistry */ import type { ProviderKind } from "@t3tools/contracts"; -import { ServiceMap } from "effect"; +import { Context } from "effect"; import type { Effect } from "effect"; import type { ProviderAdapterError, ProviderUnsupportedError } from "../Errors.ts"; @@ -34,7 +34,7 @@ export interface ProviderAdapterRegistryShape { /** * ProviderAdapterRegistry - Service tag for provider adapter lookup. */ -export class ProviderAdapterRegistry extends ServiceMap.Service< +export class ProviderAdapterRegistry extends Context.Service< ProviderAdapterRegistry, ProviderAdapterRegistryShape >()("t3/provider/Services/ProviderAdapterRegistry") {} diff --git a/apps/server/src/provider/Services/ProviderRegistry.ts b/apps/server/src/provider/Services/ProviderRegistry.ts index 80710691c1..2e04fa253b 100644 --- a/apps/server/src/provider/Services/ProviderRegistry.ts +++ b/apps/server/src/provider/Services/ProviderRegistry.ts @@ -7,7 +7,7 @@ * @module ProviderRegistry */ import type { ProviderKind, ServerProvider } from "@t3tools/contracts"; -import { ServiceMap } from "effect"; +import { Context } from "effect"; import type { Effect, Stream } from "effect"; export interface ProviderRegistryShape { @@ -27,6 +27,6 @@ export interface ProviderRegistryShape { readonly streamChanges: Stream.Stream>; } -export class ProviderRegistry extends ServiceMap.Service()( +export class ProviderRegistry extends Context.Service()( "t3/provider/Services/ProviderRegistry", ) {} diff --git a/apps/server/src/provider/Services/ProviderService.ts b/apps/server/src/provider/Services/ProviderService.ts index ebfe8c8ab1..1e461fcd1c 100644 --- a/apps/server/src/provider/Services/ProviderService.ts +++ b/apps/server/src/provider/Services/ProviderService.ts @@ -6,7 +6,7 @@ * session-scoped calls via `ProviderSessionDirectory`, and exposes one unified * provider event stream to callers. * - * Uses Effect `ServiceMap.Service` for dependency injection and returns typed + * Uses Effect `Context.Service` for dependency injection and returns typed * domain errors for validation, session, codex, and checkpoint workflows. * * @module ProviderService @@ -24,7 +24,7 @@ import type { ThreadId, ProviderTurnStartResult, } from "@t3tools/contracts"; -import { ServiceMap } from "effect"; +import { Context } from "effect"; import type { Effect, Stream } from "effect"; import type { ProviderServiceError } from "../Errors.ts"; @@ -110,6 +110,6 @@ export interface ProviderServiceShape { /** * ProviderService - Service tag for provider orchestration. */ -export class ProviderService extends ServiceMap.Service()( +export class ProviderService extends Context.Service()( "t3/provider/Services/ProviderService", ) {} diff --git a/apps/server/src/provider/Services/ProviderSessionDirectory.ts b/apps/server/src/provider/Services/ProviderSessionDirectory.ts index 3a374976b0..aa0483620b 100644 --- a/apps/server/src/provider/Services/ProviderSessionDirectory.ts +++ b/apps/server/src/provider/Services/ProviderSessionDirectory.ts @@ -4,7 +4,7 @@ import type { RuntimeMode, ThreadId, } from "@t3tools/contracts"; -import { Option, ServiceMap } from "effect"; +import { Option, Context } from "effect"; import type { Effect } from "effect"; import type { @@ -51,7 +51,7 @@ export interface ProviderSessionDirectoryShape { >; } -export class ProviderSessionDirectory extends ServiceMap.Service< +export class ProviderSessionDirectory extends Context.Service< ProviderSessionDirectory, ProviderSessionDirectoryShape >()("t3/provider/Services/ProviderSessionDirectory") {} diff --git a/apps/server/src/provider/codexAppServer.ts b/apps/server/src/provider/codexAppServer.ts index 57cac3b89b..7b3c9eeb79 100644 --- a/apps/server/src/provider/codexAppServer.ts +++ b/apps/server/src/provider/codexAppServer.ts @@ -1,7 +1,7 @@ -import { spawn } from "node:child_process"; +import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process"; import readline from "node:readline"; +import type { ServerProviderSkill } from "@t3tools/contracts"; import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount"; -import { killChildProcessTree } from "../process/killTree"; interface JsonRpcProbeResponse { readonly id?: unknown; @@ -11,10 +11,74 @@ interface JsonRpcProbeResponse { }; } +export interface CodexDiscoverySnapshot { + readonly account: CodexAccountSnapshot; + readonly skills: ReadonlyArray; +} + function readErrorMessage(response: JsonRpcProbeResponse): string | undefined { return typeof response.error?.message === "string" ? response.error.message : undefined; } +function readObject(value: unknown): Record | undefined { + return value && typeof value === "object" ? (value as Record) : undefined; +} + +function readArray(value: unknown): ReadonlyArray | undefined { + return Array.isArray(value) ? value : undefined; +} + +function readString(value: unknown): string | undefined { + return typeof value === "string" ? value : undefined; +} + +function nonEmptyTrimmed(value: unknown): string | undefined { + const candidate = readString(value)?.trim(); + return candidate ? candidate : undefined; +} + +function parseCodexSkillsResult(result: unknown, cwd: string): ReadonlyArray { + const resultRecord = readObject(result); + const dataBuckets = readArray(resultRecord?.data) ?? []; + const matchingBucket = dataBuckets.find( + (value) => nonEmptyTrimmed(readObject(value)?.cwd) === cwd, + ); + const rawSkills = + readArray(readObject(matchingBucket)?.skills) ?? readArray(resultRecord?.skills) ?? []; + + return rawSkills.flatMap((value) => { + const skill = readObject(value); + const display = readObject(skill?.interface); + const name = nonEmptyTrimmed(skill?.name); + const path = nonEmptyTrimmed(skill?.path); + if (!name || !path) { + return []; + } + + return [ + { + name, + path, + enabled: skill?.enabled !== false, + ...(nonEmptyTrimmed(skill?.description) + ? { description: nonEmptyTrimmed(skill?.description) } + : {}), + ...(nonEmptyTrimmed(skill?.scope) ? { scope: nonEmptyTrimmed(skill?.scope) } : {}), + ...(nonEmptyTrimmed(display?.displayName) + ? { displayName: nonEmptyTrimmed(display?.displayName) } + : {}), + ...(nonEmptyTrimmed(skill?.shortDescription) || nonEmptyTrimmed(display?.shortDescription) + ? { + shortDescription: + nonEmptyTrimmed(skill?.shortDescription) ?? + nonEmptyTrimmed(display?.shortDescription), + } + : {}), + } satisfies ServerProviderSkill, + ]; + }); +} + export function buildCodexInitializeParams() { return { clientInfo: { @@ -28,11 +92,25 @@ export function buildCodexInitializeParams() { } as const; } -export async function probeCodexAccount(input: { +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 probeCodexDiscovery(input: { readonly binaryPath: string; readonly homePath?: string; + readonly cwd: string; readonly signal?: AbortSignal; -}): Promise { +}): Promise { return await new Promise((resolve, reject) => { const child = spawn(input.binaryPath, ["app-server"], { env: { @@ -45,13 +123,15 @@ export async function probeCodexAccount(input: { const output = readline.createInterface({ input: child.stdout }); let completed = false; + let account: CodexAccountSnapshot | undefined; + let skills: ReadonlyArray | undefined; const cleanup = () => { output.removeAllListeners(); output.close(); child.removeAllListeners(); if (!child.killed) { - killChildProcessTree(child); + killCodexChildProcess(child); } }; @@ -67,15 +147,25 @@ export async function probeCodexAccount(input: { reject( error instanceof Error ? error - : new Error(`Codex account probe failed: ${String(error)}.`), + : new Error(`Codex discovery probe failed: ${String(error)}.`), ), ); + const maybeResolve = () => { + if (account && skills !== undefined) { + const resolvedAccount = account; + const resolvedSkills = skills; + finish(() => resolve({ account: resolvedAccount, skills: resolvedSkills })); + } + }; + if (input.signal?.aborted) { - fail(new Error("Codex account probe aborted.")); + fail(new Error("Codex discovery probe aborted.")); return; } - input.signal?.addEventListener("abort", () => fail(new Error("Codex account probe aborted."))); + input.signal?.addEventListener("abort", () => + fail(new Error("Codex discovery probe aborted.")), + ); const writeMessage = (message: unknown) => { if (!child.stdin.writable) { @@ -91,7 +181,7 @@ export async function probeCodexAccount(input: { try { parsed = JSON.parse(line); } catch { - fail(new Error("Received invalid JSON from codex app-server during account probe.")); + fail(new Error("Received invalid JSON from codex app-server during discovery probe.")); return; } @@ -108,18 +198,27 @@ export async function probeCodexAccount(input: { } writeMessage({ method: "initialized" }); - writeMessage({ id: 2, method: "account/read", params: {} }); + writeMessage({ id: 2, method: "skills/list", params: { cwds: [input.cwd] } }); + writeMessage({ id: 3, method: "account/read", params: {} }); return; } if (response.id === 2) { + const errorMessage = readErrorMessage(response); + skills = errorMessage ? [] : parseCodexSkillsResult(response.result, input.cwd); + maybeResolve(); + return; + } + + if (response.id === 3) { const errorMessage = readErrorMessage(response); if (errorMessage) { fail(new Error(`account/read failed: ${errorMessage}`)); return; } - finish(() => resolve(readCodexAccountSnapshot(response.result))); + account = readCodexAccountSnapshot(response.result); + maybeResolve(); } }); diff --git a/apps/server/src/provider/makeManagedServerProvider.ts b/apps/server/src/provider/makeManagedServerProvider.ts index e519e82af5..59aeac1ab5 100644 --- a/apps/server/src/provider/makeManagedServerProvider.ts +++ b/apps/server/src/provider/makeManagedServerProvider.ts @@ -3,70 +3,72 @@ 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: { +export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(function* < + Settings, +>(input: { readonly getSettings: Effect.Effect; readonly streamSettings: Stream.Stream; readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean; readonly checkProvider: Effect.Effect; readonly refreshInterval?: Duration.Input; -}): Effect.Effect { - return Effect.gen(function* () { - const refreshSemaphore = yield* Semaphore.make(1); - const changesPubSub = yield* Effect.acquireRelease( - PubSub.unbounded(), - PubSub.shutdown, - ); - const initialSettings = yield* input.getSettings; - const initialSnapshot = yield* input.checkProvider; - const snapshotRef = yield* Ref.make(initialSnapshot); - const settingsRef = yield* Ref.make(initialSettings); +}): Effect.fn.Return { + const refreshSemaphore = yield* Semaphore.make(1); + const changesPubSub = yield* Effect.acquireRelease( + PubSub.unbounded(), + PubSub.shutdown, + ); + const initialSettings = yield* input.getSettings; + const initialSnapshot = yield* input.checkProvider; + const snapshotRef = yield* Ref.make(initialSnapshot); + const settingsRef = yield* Ref.make(initialSettings); - const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) => - refreshSemaphore.withPermits(1)( - Effect.gen(function* () { - const forceRefresh = options?.forceRefresh === true; - const previousSettings = yield* Ref.get(settingsRef); - if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) { - yield* Ref.set(settingsRef, nextSettings); - return yield* Ref.get(snapshotRef); - } + const applySnapshotBase = Effect.fn("applySnapshot")(function* ( + nextSettings: Settings, + options?: { readonly forceRefresh?: boolean }, + ) { + const forceRefresh = options?.forceRefresh === true; + const previousSettings = yield* Ref.get(settingsRef); + if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) { + yield* Ref.set(settingsRef, nextSettings); + return yield* Ref.get(snapshotRef); + } - const nextSnapshot = yield* input.checkProvider; - yield* Ref.set(settingsRef, nextSettings); - yield* Ref.set(snapshotRef, nextSnapshot); - yield* PubSub.publish(changesPubSub, nextSnapshot); - return nextSnapshot; - }), - ); - - const refreshSnapshot = Effect.gen(function* () { - const nextSettings = yield* input.getSettings; - return yield* applySnapshot(nextSettings, { forceRefresh: true }); - }); - - yield* Stream.runForEach(input.streamSettings, (nextSettings) => - Effect.asVoid(applySnapshot(nextSettings)), - ).pipe(Effect.forkScoped); - - yield* Effect.forever( - Effect.sleep(input.refreshInterval ?? "60 seconds").pipe( - Effect.flatMap(() => refreshSnapshot), - Effect.ignoreCause({ log: true }), - ), - ).pipe(Effect.forkScoped); - - return { - getSnapshot: input.getSettings.pipe( - Effect.flatMap(applySnapshot), - Effect.tapError(Effect.logError), - Effect.orDie, - ), - refresh: refreshSnapshot.pipe(Effect.tapError(Effect.logError), Effect.orDie), - get streamChanges() { - return Stream.fromPubSub(changesPubSub); - }, - } satisfies ServerProviderShape; + const nextSnapshot = yield* input.checkProvider; + yield* Ref.set(settingsRef, nextSettings); + yield* Ref.set(snapshotRef, nextSnapshot); + yield* PubSub.publish(changesPubSub, nextSnapshot); + return nextSnapshot; }); -} + const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) => + refreshSemaphore.withPermits(1)(applySnapshotBase(nextSettings, options)); + + const refreshSnapshot = Effect.fn("refreshSnapshot")(function* () { + const nextSettings = yield* input.getSettings; + return yield* applySnapshot(nextSettings, { forceRefresh: true }); + }); + + yield* Stream.runForEach(input.streamSettings, (nextSettings) => + Effect.asVoid(applySnapshot(nextSettings)), + ).pipe(Effect.forkScoped); + + yield* Effect.forever( + Effect.sleep(input.refreshInterval ?? "60 seconds").pipe( + Effect.flatMap(() => refreshSnapshot()), + Effect.ignoreCause({ log: true }), + ), + ).pipe(Effect.forkScoped); + + return { + getSnapshot: input.getSettings.pipe( + Effect.flatMap(applySnapshot), + Effect.tapError(Effect.logError), + Effect.orDie, + ), + refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie), + get streamChanges() { + return Stream.fromPubSub(changesPubSub); + }, + } satisfies ServerProviderShape; +}); diff --git a/apps/server/src/provider/providerSnapshot.ts b/apps/server/src/provider/providerSnapshot.ts index 3a6a0b7a93..849d9f0bd3 100644 --- a/apps/server/src/provider/providerSnapshot.ts +++ b/apps/server/src/provider/providerSnapshot.ts @@ -1,6 +1,9 @@ import type { + ModelCapabilities, ServerProvider, ServerProviderAuth, + ServerProviderSkill, + ServerProviderSlashCommand, ServerProviderModel, ServerProviderState, } from "@t3tools/contracts"; @@ -31,8 +34,7 @@ export function nonEmptyTrimmed(value: string | undefined): string | undefined { return trimmed.length > 0 ? trimmed : undefined; } -export function isCommandMissingCause(error: unknown): boolean { - if (!(error instanceof Error)) return false; +export function isCommandMissingCause(error: Error): boolean { const lower = error.message.toLowerCase(); return lower.includes("enoent") || lower.includes("notfound"); } @@ -102,6 +104,7 @@ export function providerModelsFromSettings( builtInModels: ReadonlyArray, provider: ServerProvider["provider"], customModels: ReadonlyArray, + customModelCapabilities: ModelCapabilities, ): ReadonlyArray { const resolvedBuiltInModels = [...builtInModels]; const seen = new Set(resolvedBuiltInModels.map((model) => model.slug)); @@ -117,7 +120,7 @@ export function providerModelsFromSettings( slug: normalized, name: normalized, isCustom: true, - capabilities: null, + capabilities: customModelCapabilities, }); } @@ -129,6 +132,8 @@ export function buildServerProvider(input: { enabled: boolean; checkedAt: string; models: ReadonlyArray; + slashCommands?: ReadonlyArray; + skills?: ReadonlyArray; probe: ProviderProbeResult; }): ServerProvider { return { @@ -141,6 +146,8 @@ export function buildServerProvider(input: { checkedAt: input.checkedAt, ...(input.probe.message ? { message: input.probe.message } : {}), models: input.models, + slashCommands: [...(input.slashCommands ?? [])], + skills: [...(input.skills ?? [])], }; } diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts new file mode 100644 index 0000000000..fbbab1c84a --- /dev/null +++ b/apps/server/src/server.test.ts @@ -0,0 +1,3660 @@ +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, + EnvironmentId, + EventId, + GitCommandError, + KeybindingRule, + MessageId, + OpenError, + TerminalNotRunningError, + type OrchestrationCommand, + 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 { + Deferred, + Duration, + Effect, + FileSystem, + Layer, + ManagedRuntime, + Path, + Stream, +} from "effect"; +import { + FetchHttpClient, + HttpBody, + HttpClient, + HttpRouter, + HttpServer, +} from "effect/unstable/http"; +import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability"; +import { RpcClient, RpcSerialization } from "effect/unstable/rpc"; +import * as Socket from "effect/unstable/socket/Socket"; +import { vi } from "vitest"; + +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 { GitStatusBroadcasterLive } from "./git/Layers/GitStatusBroadcaster.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 { OrchestrationListenerCallbackError } from "./orchestration/Errors.ts"; +import { + ProjectionSnapshotQuery, + type ProjectionSnapshotQueryShape, +} from "./orchestration/Services/ProjectionSnapshotQuery.ts"; +import { PersistenceSqlError } from "./persistence/Errors.ts"; +import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.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 { + BrowserTraceCollector, + type BrowserTraceCollectorShape, +} from "./observability/Services/BrowserTraceCollector.ts"; +import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts"; +import { + ProjectSetupScriptRunner, + type ProjectSetupScriptRunnerShape, +} from "./project/Services/ProjectSetupScriptRunner.ts"; +import { + RepositoryIdentityResolver, + type RepositoryIdentityResolverShape, +} from "./project/Services/RepositoryIdentityResolver.ts"; +import { + ServerEnvironment, + type ServerEnvironmentShape, +} from "./environment/Services/ServerEnvironment.ts"; +import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts"; +import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts"; +import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts"; +import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts"; +import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts"; + +const defaultProjectId = ProjectId.make("project-default"); +const defaultThreadId = ThreadId.make("thread-default"); +const defaultDesktopBootstrapToken = "test-desktop-bootstrap-token"; +const defaultModelSelection = { + provider: "codex", + model: "gpt-5-codex", +} as const; +const testEnvironmentDescriptor = { + environmentId: EnvironmentId.make("environment-test"), + label: "Test environment", + platform: { + os: "darwin" as const, + arch: "arm64" as const, + }, + serverVersion: "0.0.0-test", + capabilities: { + repositoryIdentity: true, + }, +}; +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 browserOtlpTracingLayer = Layer.mergeAll( + FetchHttpClient.layer, + OtlpSerialization.layerJson, + Layer.succeed(HttpClient.TracerDisabledWhen, () => true), +); + +const authTestLayer = ServerAuthLive.pipe( + Layer.provide(SqlitePersistenceMemory), + Layer.provide(ServerSecretStoreLive), +); + +const makeBrowserOtlpPayload = (spanName: string) => + Effect.gen(function* () { + const collector = yield* Effect.acquireRelease( + Effect.promise(async () => { + const NodeHttp = await import("node:http"); + + return await new Promise<{ + readonly close: () => Promise; + readonly firstRequest: Promise<{ + readonly body: string; + readonly contentType: string | null; + }>; + readonly url: string; + }>((resolve, reject) => { + let resolveFirstRequest: + | ((request: { readonly body: string; readonly contentType: string | null }) => void) + | undefined; + const firstRequest = new Promise<{ + readonly body: string; + readonly contentType: string | null; + }>((resolveRequest) => { + resolveFirstRequest = resolveRequest; + }); + + const server = NodeHttp.createServer((request, response) => { + const chunks: Buffer[] = []; + request.on("data", (chunk) => { + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + }); + request.on("end", () => { + resolveFirstRequest?.({ + body: Buffer.concat(chunks).toString("utf8"), + contentType: request.headers["content-type"] ?? null, + }); + resolveFirstRequest = undefined; + response.statusCode = 204; + response.end(); + }); + }); + + server.on("error", reject); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + if (!address || typeof address === "string") { + reject(new Error("Expected TCP collector address")); + return; + } + + resolve({ + url: `http://127.0.0.1:${address.port}/v1/traces`, + firstRequest, + close: () => + new Promise((resolveClose, rejectClose) => { + server.close((error) => { + if (error) { + rejectClose(error); + return; + } + resolveClose(); + }); + }), + }); + }); + }); + }), + ({ close }) => Effect.promise(close), + ); + + const runtime = ManagedRuntime.make( + OtlpTracer.layer({ + url: collector.url, + exportInterval: "10 millis", + resource: { + serviceName: "t3-web", + attributes: { + "service.runtime": "t3-web", + "service.mode": "browser", + "service.version": "test", + }, + }, + }).pipe(Layer.provide(browserOtlpTracingLayer)), + ); + + try { + yield* Effect.promise(() => runtime.runPromise(Effect.void.pipe(Effect.withSpan(spanName)))); + } finally { + yield* Effect.promise(() => runtime.dispose()); + } + + const request = yield* Effect.promise(() => + Promise.race([ + collector.firstRequest, + new Promise((_, reject) => { + setTimeout(() => reject(new Error("Timed out waiting for OTLP trace export")), 1_000); + }), + ]), + ); + + return JSON.parse(request.body) as OtlpTracer.TraceData; + }); + +const buildAppUnderTest = (options?: { + config?: Partial; + layers?: { + keybindings?: Partial; + providerRegistry?: Partial; + serverSettings?: Partial; + open?: Partial; + gitCore?: Partial; + gitManager?: Partial; + projectSetupScriptRunner?: Partial; + terminalManager?: Partial; + orchestrationEngine?: Partial; + projectionSnapshotQuery?: Partial; + checkpointDiffQuery?: Partial; + browserTraceCollector?: Partial; + serverLifecycleEvents?: Partial; + serverRuntimeStartup?: Partial; + serverEnvironment?: Partial; + repositoryIdentityResolver?: 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: ServerConfigShape = { + logLevel: "Info", + traceMinLevel: "Info", + traceTimingEnabled: true, + traceBatchWindowMs: 200, + traceMaxBytes: 10 * 1024 * 1024, + traceMaxFiles: 10, + otlpTracesUrl: undefined, + otlpMetricsUrl: undefined, + otlpExportIntervalMs: 10_000, + otlpServiceName: "t3-server", + mode: "desktop", + port: 0, + host: "127.0.0.1", + cwd: process.cwd(), + baseDir, + ...derivedPaths, + staticDir: undefined, + devUrl, + noBrowser: true, + startupPresentation: "browser", + desktopBootstrapToken: defaultDesktopBootstrapToken, + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: false, + ...options?.config, + }; + const layerConfig = Layer.succeed(ServerConfig, config); + const gitManagerLayer = Layer.mock(GitManager)({ + ...options?.layers?.gitManager, + }); + const gitStatusBroadcasterLayer = GitStatusBroadcasterLive.pipe(Layer.provide(gitManagerLayer)); + + const servedRoutesLayer = HttpRouter.serve(makeRoutesLayer, { + disableListenLog: true, + disableLogger: true, + }).pipe( + Layer.provide( + Layer.mock(Keybindings)({ + loadConfigState: Effect.succeed({ + keybindings: [], + issues: [], + }), + 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(gitManagerLayer), + Layer.provideMerge(gitStatusBroadcasterLayer), + Layer.provide( + Layer.mock(ProjectSetupScriptRunner)({ + runForThread: () => Effect.succeed({ status: "no-script" as const }), + ...options?.layers?.projectSetupScriptRunner, + }), + ), + 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, + }), + ), + ); + + const appLayer = servedRoutesLayer.pipe( + Layer.provide( + Layer.mock(BrowserTraceCollector)({ + record: () => Effect.void, + ...options?.layers?.browserTraceCollector, + }), + ), + 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( + Layer.mock(ServerEnvironment)({ + getEnvironmentId: Effect.succeed(testEnvironmentDescriptor.environmentId), + getDescriptor: Effect.succeed(testEnvironmentDescriptor), + ...options?.layers?.serverEnvironment, + }), + ), + Layer.provide( + Layer.mock(RepositoryIdentityResolver)({ + resolve: () => Effect.succeed(null), + ...options?.layers?.repositoryIdentityResolver, + }), + ), + Layer.provideMerge(authTestLayer), + Layer.provide(workspaceAndProjectServicesLayer), + Layer.provideMerge(FetchHttpClient.layer), + Layer.provide(layerConfig), + ); + + yield* Layer.build(appLayer); + return config; + }); + +const parseSessionCookieFromWsUrl = ( + wsUrl: string, +): { readonly cookie: string | null; readonly url: string } => { + const next = new URL(wsUrl); + const cookie = next.hash.startsWith("#cookie=") + ? decodeURIComponent(next.hash.slice("#cookie=".length)) + : null; + next.hash = ""; + return { + cookie, + url: next.toString(), + }; +}; + +const wsRpcProtocolLayer = (wsUrl: string) => { + const { cookie, url } = parseSessionCookieFromWsUrl(wsUrl); + const webSocketConstructorLayer = Layer.succeed( + Socket.WebSocketConstructor, + (socketUrl, protocols) => + new NodeSocket.NodeWS.WebSocket( + socketUrl, + protocols, + cookie ? { headers: { cookie } } : undefined, + ) as unknown as globalThis.WebSocket, + ); + + return RpcClient.layerProtocolSocket().pipe( + Layer.provide(Socket.layerWebSocket(url).pipe(Layer.provide(webSocketConstructorLayer))), + 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 appendSessionCookieToWsUrl = (url: string, sessionCookieHeader: string) => { + const isAbsoluteUrl = /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(url); + const next = new URL(url, "http://localhost"); + next.hash = `cookie=${encodeURIComponent(sessionCookieHeader)}`; + return isAbsoluteUrl ? next.toString() : `${next.pathname}${next.search}${next.hash}`; +}; + +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 bootstrapBrowserSession = ( + credential = defaultDesktopBootstrapToken, + options?: { + readonly headers?: Record; + }, +) => + Effect.gen(function* () { + const bootstrapUrl = yield* getHttpServerUrl("/api/auth/bootstrap"); + const response = yield* Effect.promise(() => + fetch(bootstrapUrl, { + method: "POST", + headers: { + "content-type": "application/json", + ...options?.headers, + }, + body: JSON.stringify({ + credential, + }), + }), + ); + const body = (yield* Effect.promise(() => response.json())) as { + readonly authenticated: boolean; + readonly sessionMethod: string; + readonly expiresAt: string; + }; + return { + response, + body, + cookie: response.headers.get("set-cookie"), + }; + }); + +const bootstrapBearerSession = (credential = defaultDesktopBootstrapToken) => + Effect.gen(function* () { + const bootstrapUrl = yield* getHttpServerUrl("/api/auth/bootstrap/bearer"); + const response = yield* Effect.promise(() => + fetch(bootstrapUrl, { + method: "POST", + headers: { + "content-type": "application/json", + }, + body: JSON.stringify({ + credential, + }), + }), + ); + const body = (yield* Effect.promise(() => response.json())) as { + readonly authenticated: boolean; + readonly sessionMethod: string; + readonly expiresAt: string; + readonly sessionToken?: string; + readonly error?: string; + }; + return { + response, + body, + }; + }); + +const getAuthenticatedSessionCookieHeader = (credential = defaultDesktopBootstrapToken) => + Effect.gen(function* () { + const { response, cookie } = yield* bootstrapBrowserSession(credential); + if (!response.ok) { + return yield* Effect.fail( + new Error(`Expected bootstrap session response to succeed, got ${response.status}`), + ); + } + + if (!cookie) { + return yield* Effect.fail(new Error("Expected bootstrap session response to set a cookie.")); + } + + return cookie.split(";")[0] ?? cookie; + }); + +const getAuthenticatedBearerSessionToken = (credential = defaultDesktopBootstrapToken) => + Effect.gen(function* () { + const { response, body } = yield* bootstrapBearerSession(credential); + if (!response.ok) { + return yield* Effect.fail( + new Error(`Expected bearer bootstrap response to succeed, got ${response.status}`), + ); + } + + if (!body.sessionToken) { + return yield* Effect.fail( + new Error("Expected bearer bootstrap response to include a session token."), + ); + } + + return body.sessionToken; + }); + +const extractSessionTokenFromSetCookie = (cookieHeader: string): string => { + const [nameValue] = cookieHeader.split(";", 1); + const token = nameValue?.split("=", 2)[1]; + if (!token) { + throw new Error("Expected session cookie header to contain a token value."); + } + return token; +}; + +const splitHeaderTokens = (value: string | null) => + (value ?? "") + .split(",") + .map((token) => token.trim()) + .filter((token) => token.length > 0) + .toSorted(); + +const getWsServerUrl = ( + pathname = "", + options?: { authenticated?: boolean; credential?: string }, +) => + Effect.gen(function* () { + const server = yield* HttpServer.HttpServer; + const address = server.address as HttpServer.TcpAddress; + const baseUrl = `ws://127.0.0.1:${address.port}${pathname}`; + if (options?.authenticated === false) { + return baseUrl; + } + return appendSessionCookieToWsUrl( + baseUrl, + yield* getAuthenticatedSessionCookieHeader(options?.credential), + ); + }); + +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?token=test-token"); + 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/foo/bar?token=test-token", + ); + }).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)}`, + { + headers: { + cookie: yield* getAuthenticatedSessionCookieHeader(), + }, + }, + ); + + 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)}`, + { + headers: { + cookie: yield* getAuthenticatedSessionCookieHeader(), + }, + }, + ); + + assert.equal(response.status, 200); + assert.include(yield* response.text, 'data-fallback="project-favicon"'); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("serves the public environment descriptor without requiring auth", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const url = yield* getHttpServerUrl("/.well-known/t3/environment"); + const response = yield* Effect.promise(() => fetch(url)); + const body = (yield* Effect.promise(() => + response.json(), + )) as typeof testEnvironmentDescriptor; + + assert.equal(response.status, 200); + assert.deepEqual(body, testEnvironmentDescriptor); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("reports unauthenticated session state without requiring auth", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const url = yield* getHttpServerUrl("/api/auth/session"); + const response = yield* Effect.promise(() => fetch(url)); + const body = (yield* Effect.promise(() => response.json())) as { + readonly authenticated: boolean; + readonly auth: { + readonly policy: string; + readonly bootstrapMethods: ReadonlyArray; + readonly sessionMethods: ReadonlyArray; + readonly sessionCookieName: string; + }; + }; + + assert.equal(response.status, 200); + assert.equal(body.authenticated, false); + assert.equal(body.auth.policy, "desktop-managed-local"); + assert.deepEqual(body.auth.bootstrapMethods, ["desktop-bootstrap"]); + assert.deepEqual(body.auth.sessionMethods, [ + "browser-session-cookie", + "bearer-session-token", + ]); + assert.isTrue(body.auth.sessionCookieName.startsWith("t3_session_")); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("bootstraps a browser session and authenticates the session endpoint via cookie", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const { + response: bootstrapResponse, + body: bootstrapBody, + cookie: setCookie, + } = yield* bootstrapBrowserSession(); + + assert.equal(bootstrapResponse.status, 200); + assert.equal(bootstrapBody.authenticated, true); + assert.equal(bootstrapBody.sessionMethod, "browser-session-cookie"); + assert.isUndefined((bootstrapBody as { readonly sessionToken?: string }).sessionToken); + assert.isDefined(setCookie); + + const sessionUrl = yield* getHttpServerUrl("/api/auth/session"); + const sessionResponse = yield* Effect.promise(() => + fetch(sessionUrl, { + headers: { + cookie: setCookie?.split(";")[0] ?? "", + }, + }), + ); + const sessionBody = (yield* Effect.promise(() => sessionResponse.json())) as { + readonly authenticated: boolean; + readonly sessionMethod?: string; + }; + + assert.equal(sessionResponse.status, 200); + assert.equal(sessionBody.authenticated, true); + assert.equal(sessionBody.sessionMethod, "browser-session-cookie"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "bootstraps a bearer session and authenticates the session endpoint via authorization header", + () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const { response: bootstrapResponse, body: bootstrapBody } = + yield* bootstrapBearerSession(); + + assert.equal(bootstrapResponse.status, 200); + assert.equal(bootstrapBody.authenticated, true); + assert.equal(bootstrapBody.sessionMethod, "bearer-session-token"); + assert.equal(typeof bootstrapBody.sessionToken, "string"); + assert.isTrue((bootstrapBody.sessionToken?.length ?? 0) > 0); + + const sessionUrl = yield* getHttpServerUrl("/api/auth/session"); + const sessionResponse = yield* Effect.promise(() => + fetch(sessionUrl, { + headers: { + authorization: `Bearer ${bootstrapBody.sessionToken ?? ""}`, + }, + }), + ); + const sessionBody = (yield* Effect.promise(() => sessionResponse.json())) as { + readonly authenticated: boolean; + readonly sessionMethod?: string; + }; + + assert.equal(sessionResponse.status, 200); + assert.equal(sessionBody.authenticated, true); + assert.equal(sessionBody.sessionMethod, "bearer-session-token"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("issues short-lived websocket tokens for authenticated bearer sessions", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const bearerToken = yield* getAuthenticatedBearerSessionToken(); + const wsTokenUrl = yield* getHttpServerUrl("/api/auth/ws-token"); + const wsTokenResponse = yield* Effect.promise(() => + fetch(wsTokenUrl, { + method: "POST", + headers: { + authorization: `Bearer ${bearerToken}`, + }, + }), + ); + const wsTokenBody = (yield* Effect.promise(() => wsTokenResponse.json())) as { + readonly token: string; + readonly expiresAt: string; + }; + + assert.equal(wsTokenResponse.status, 200); + assert.equal(typeof wsTokenBody.token, "string"); + assert.isTrue(wsTokenBody.token.length > 0); + assert.equal(typeof wsTokenBody.expiresAt, "string"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "responds to remote auth websocket-token preflight requests with authorization CORS headers", + () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const wsTokenUrl = yield* getHttpServerUrl("/api/auth/ws-token"); + const response = yield* Effect.promise(() => + fetch(wsTokenUrl, { + method: "OPTIONS", + headers: { + origin: "http://192.168.86.35:3773", + "access-control-request-method": "POST", + "access-control-request-headers": "authorization", + }, + }), + ); + + assert.equal(response.status, 204); + assert.equal(response.headers.get("access-control-allow-origin"), "*"); + assert.deepEqual(splitHeaderTokens(response.headers.get("access-control-allow-methods")), [ + "GET", + "OPTIONS", + "POST", + ]); + assert.deepEqual(splitHeaderTokens(response.headers.get("access-control-allow-headers")), [ + "authorization", + "b3", + "content-type", + "traceparent", + ]); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("includes CORS headers on remote websocket-token auth failures", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const wsTokenUrl = yield* getHttpServerUrl("/api/auth/ws-token"); + const response = yield* Effect.promise(() => + fetch(wsTokenUrl, { + method: "POST", + headers: { + origin: "http://192.168.86.35:3773", + }, + }), + ); + const body = (yield* Effect.promise(() => response.json())) as { + readonly error?: string; + }; + + assert.equal(response.status, 401); + assert.equal(response.headers.get("access-control-allow-origin"), "*"); + assert.equal(body.error, "Authentication required."); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("issues authenticated one-time pairing credentials for additional clients", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const response = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { + cookie: yield* getAuthenticatedSessionCookieHeader(), + }, + }); + const body = (yield* response.json) as { + readonly credential: string; + readonly expiresAt: string; + }; + + assert.equal(response.status, 200); + assert.equal(typeof body.credential, "string"); + assert.isTrue(body.credential.length > 0); + assert.equal(typeof body.expiresAt, "string"); + + const bootstrapResult = yield* bootstrapBrowserSession(body.credential); + assert.equal(bootstrapResult.response.status, 200); + + const reusedResult = yield* bootstrapBrowserSession(body.credential); + assert.equal(reusedResult.response.status, 401); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects unauthenticated pairing credential requests", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const response = yield* HttpClient.post("/api/auth/pairing-token"); + assert.equal(response.status, 401); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("lists and revokes pairing links for owner sessions", () => + Effect.gen(function* () { + yield* buildAppUnderTest({ + config: { + host: "0.0.0.0", + }, + }); + + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const createdResponse = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { + cookie: ownerCookie, + }, + }); + const createdBody = (yield* createdResponse.json) as { + readonly id: string; + readonly credential: string; + }; + + const listResponse = yield* HttpClient.get("/api/auth/pairing-links", { + headers: { + cookie: ownerCookie, + }, + }); + const listedLinks = (yield* listResponse.json) as ReadonlyArray<{ + readonly id: string; + readonly credential: string; + }>; + + const revokeUrl = yield* getHttpServerUrl("/api/auth/pairing-links/revoke"); + const revokeResponse = yield* Effect.promise(() => + fetch(revokeUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: JSON.stringify({ id: createdBody.id }), + }), + ); + const revokedBootstrap = yield* bootstrapBrowserSession(createdBody.credential); + + assert.equal(createdResponse.status, 200); + assert.equal(listResponse.status, 200); + assert.isTrue(listedLinks.some((entry) => entry.id === createdBody.id)); + assert.equal(revokeResponse.status, 200); + assert.equal(revokedBootstrap.response.status, 401); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects pairing credential requests from non-owner paired sessions", () => + Effect.gen(function* () { + yield* buildAppUnderTest({ + config: { + host: "0.0.0.0", + }, + }); + + const ownerResponse = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { + cookie: yield* getAuthenticatedSessionCookieHeader(), + }, + }); + const ownerBody = (yield* ownerResponse.json) as { + readonly credential: string; + }; + assert.equal(ownerResponse.status, 200); + + const pairedSessionCookie = yield* getAuthenticatedSessionCookieHeader(ownerBody.credential); + const pairedResponse = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { + cookie: pairedSessionCookie, + }, + }); + const pairedBody = (yield* pairedResponse.json) as { + readonly error: string; + }; + + assert.equal(pairedResponse.status, 403); + assert.equal(pairedBody.error, "Only owner sessions can create pairing credentials."); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("lists paired clients and revokes other sessions while keeping the owner", () => + Effect.gen(function* () { + yield* buildAppUnderTest({ + config: { + host: "0.0.0.0", + }, + }); + + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const pairingTokenUrl = yield* getHttpServerUrl("/api/auth/pairing-token"); + const ownerPairingResponse = yield* Effect.promise(() => + fetch(pairingTokenUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: JSON.stringify({ + label: "Julius iPhone", + }), + }), + ); + const ownerPairingBody = (yield* Effect.promise(() => ownerPairingResponse.json())) as { + readonly credential: string; + readonly label?: string; + }; + assert.equal(ownerPairingResponse.status, 200); + const pairedSessionBootstrap = yield* bootstrapBrowserSession(ownerPairingBody.credential, { + headers: { + "user-agent": + "Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Mobile/15E148 Safari/604.1", + }, + }); + const pairedSessionCookie = pairedSessionBootstrap.cookie?.split(";")[0]; + assert.isDefined(pairedSessionCookie); + + const pairedSessionCookieHeader = pairedSessionCookie ?? ""; + const listClientsUrl = yield* getHttpServerUrl("/api/auth/clients"); + const listBeforeResponse = yield* Effect.promise(() => + fetch(listClientsUrl, { + headers: { + cookie: ownerCookie, + }, + }), + ); + const clientsBefore = (yield* Effect.promise(() => + listBeforeResponse.json(), + )) as ReadonlyArray<{ + readonly sessionId: string; + readonly current: boolean; + readonly client: { + readonly label?: string; + readonly deviceType: string; + readonly ipAddress?: string; + readonly os?: string; + readonly browser?: string; + }; + }>; + const pairedClientBefore = clientsBefore.find((entry) => !entry.current); + const pairedSessionId = clientsBefore.find((entry) => !entry.current)?.sessionId; + + const revokeOthersResponse = yield* HttpClient.post("/api/auth/clients/revoke-others", { + headers: { + cookie: ownerCookie, + }, + }); + const revokeOthersBody = (yield* revokeOthersResponse.json) as { + readonly revokedCount: number; + }; + + const listAfterResponse = yield* HttpClient.get("/api/auth/clients", { + headers: { + cookie: ownerCookie, + }, + }); + const clientsAfter = (yield* listAfterResponse.json) as ReadonlyArray<{ + readonly sessionId: string; + readonly current: boolean; + }>; + + const pairedClientPairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { + cookie: pairedSessionCookieHeader, + }, + }); + const pairedClientPairingBody = (yield* pairedClientPairingResponse.json) as { + readonly error: string; + }; + + assert.equal(listBeforeResponse.status, 200); + assert.equal(ownerPairingBody.label, "Julius iPhone"); + assert.lengthOf(clientsBefore, 2); + assert.isDefined(pairedSessionId); + assert.isDefined(pairedClientBefore); + assert.deepInclude(pairedClientBefore?.client, { + label: "Julius iPhone", + deviceType: "mobile", + os: "iOS", + browser: "Safari", + ipAddress: "127.0.0.1", + }); + assert.equal(revokeOthersResponse.status, 200); + assert.equal(revokeOthersBody.revokedCount, 1); + assert.equal(listAfterResponse.status, 200); + assert.lengthOf(clientsAfter, 1); + assert.equal(clientsAfter[0]?.current, true); + assert.equal(pairedClientPairingResponse.status, 401); + assert.equal(pairedClientPairingBody.error, "Unauthorized request."); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("revokes an individual paired client session", () => + Effect.gen(function* () { + yield* buildAppUnderTest({ + config: { + host: "0.0.0.0", + }, + }); + + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const pairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { + cookie: ownerCookie, + }, + }); + const pairingBody = (yield* pairingResponse.json) as { + readonly credential: string; + }; + const pairedSessionCookie = yield* getAuthenticatedSessionCookieHeader( + pairingBody.credential, + ); + + const clientsResponse = yield* HttpClient.get("/api/auth/clients", { + headers: { + cookie: ownerCookie, + }, + }); + const clients = (yield* clientsResponse.json) as ReadonlyArray<{ + readonly sessionId: string; + readonly current: boolean; + }>; + const pairedSessionId = clients.find((entry) => !entry.current)?.sessionId; + assert.isDefined(pairedSessionId); + + const revokeUrl = yield* getHttpServerUrl("/api/auth/clients/revoke"); + const revokeResponse = yield* Effect.promise(() => + fetch(revokeUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: JSON.stringify({ sessionId: pairedSessionId }), + }), + ); + const pairedClientPairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { + cookie: pairedSessionCookie, + }, + }); + + assert.equal(revokeResponse.status, 200); + assert.equal(pairedClientPairingResponse.status, 401); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects reusing the same bootstrap credential after it has been exchanged", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const first = yield* bootstrapBrowserSession(); + const second = yield* bootstrapBrowserSession(); + + assert.equal(first.response.status, 200); + assert.equal(second.response.status, 401); + assert.equal( + (second.body as { readonly error?: string }).error, + "Invalid bootstrap credential.", + ); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "does not accept session tokens via query parameters on authenticated HTTP routes", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const projectDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-router-project-favicon-query-token-", + }); + + yield* buildAppUnderTest(); + + const { cookie } = yield* bootstrapBrowserSession(); + assert.isDefined(cookie); + const sessionToken = extractSessionTokenFromSetCookie(cookie ?? ""); + + const response = yield* HttpClient.get( + `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}&token=${encodeURIComponent(sessionToken)}`, + ); + + assert.equal(response.status, 401); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("accepts websocket rpc handshake with a bootstrapped browser session cookie", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const { response: bootstrapResponse, cookie } = yield* bootstrapBrowserSession(); + + assert.equal(bootstrapResponse.status, 200); + assert.isDefined(cookie); + + const wsUrl = appendSessionCookieToWsUrl( + yield* getWsServerUrl("/ws", { authenticated: false }), + cookie?.split(";")[0] ?? "", + ); + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverGetConfig]({})), + ); + + assert.equal(response.environment.environmentId, testEnvironmentDescriptor.environmentId); + assert.equal(response.auth.policy, "desktop-managed-local"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "rejects websocket rpc handshake when a session token is only provided via query string", + () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const { cookie } = yield* bootstrapBrowserSession(); + assert.isDefined(cookie); + const sessionToken = extractSessionTokenFromSetCookie(cookie ?? ""); + const wsUrl = `${yield* getWsServerUrl("/ws", { authenticated: false })}?token=${encodeURIComponent(sessionToken)}`; + + const error = yield* Effect.flip( + Effect.scoped(withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverGetConfig]({}))), + ); + + assert.equal(error._tag, "RpcClientError"); + assertInclude(String(error), "SocketOpenError"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "accepts websocket rpc handshake with a dedicated websocket token in the query string", + () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const bearerToken = yield* getAuthenticatedBearerSessionToken(); + const wsTokenUrl = yield* getHttpServerUrl("/api/auth/ws-token"); + const wsTokenResponse = yield* Effect.promise(() => + fetch(wsTokenUrl, { + method: "POST", + headers: { + authorization: `Bearer ${bearerToken}`, + }, + }), + ); + const wsTokenBody = (yield* Effect.promise(() => wsTokenResponse.json())) as { + readonly token: string; + }; + const wsUrl = `${yield* getWsServerUrl("/ws", { authenticated: false })}?wsToken=${encodeURIComponent(wsTokenBody.token)}`; + + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverGetConfig]({})), + ); + + assert.equal(response.environment.environmentId, testEnvironmentDescriptor.environmentId); + assert.equal(response.auth.policy, "desktop-managed-local"); + }).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}`, { + headers: { + cookie: yield* getAuthenticatedSessionCookieHeader(), + }, + }); + 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", + { + headers: { + cookie: yield* getAuthenticatedSessionCookieHeader(), + }, + }, + ); + assert.equal(response.status, 200); + assert.equal(yield* response.text, "attachment-encoded-ok"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("proxies browser OTLP trace exports through the server", () => + Effect.gen(function* () { + const upstreamRequests: Array<{ + readonly body: string; + readonly contentType: string | null; + }> = []; + const localTraceRecords: Array = []; + const payload = { + resourceSpans: [ + { + resource: { + attributes: [ + { + key: "service.name", + value: { stringValue: "t3-web" }, + }, + ], + }, + scopeSpans: [ + { + scope: { + name: "effect", + version: "4.0.0-beta.43", + }, + spans: [ + { + traceId: "11111111111111111111111111111111", + spanId: "2222222222222222", + parentSpanId: "3333333333333333", + name: "RpcClient.server.getSettings", + kind: 3, + startTimeUnixNano: "1000000", + endTimeUnixNano: "2000000", + attributes: [ + { + key: "rpc.method", + value: { stringValue: "server.getSettings" }, + }, + ], + events: [ + { + name: "http.request", + timeUnixNano: "1500000", + attributes: [ + { + key: "http.status_code", + value: { intValue: "200" }, + }, + ], + }, + ], + links: [], + status: { + code: "STATUS_CODE_OK", + }, + flags: 1, + }, + ], + }, + ], + }, + ], + }; + + const collector = yield* Effect.acquireRelease( + Effect.promise(async () => { + const NodeHttp = await import("node:http"); + + return await new Promise<{ + readonly close: () => Promise; + readonly url: string; + }>((resolve, reject) => { + const server = NodeHttp.createServer((request, response) => { + const chunks: Buffer[] = []; + request.on("data", (chunk) => { + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + }); + request.on("end", () => { + upstreamRequests.push({ + body: Buffer.concat(chunks).toString("utf8"), + contentType: request.headers["content-type"] ?? null, + }); + response.statusCode = 204; + response.end(); + }); + }); + + server.on("error", reject); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + if (!address || typeof address === "string") { + reject(new Error("Expected TCP collector address")); + return; + } + + resolve({ + url: `http://127.0.0.1:${address.port}/v1/traces`, + close: () => + new Promise((resolveClose, rejectClose) => { + server.close((error) => { + if (error) { + rejectClose(error); + return; + } + resolveClose(); + }); + }), + }); + }); + }); + }), + ({ close }) => Effect.promise(close), + ); + + yield* buildAppUnderTest({ + config: { + otlpTracesUrl: collector.url, + }, + layers: { + browserTraceCollector: { + record: (records) => + Effect.sync(() => { + localTraceRecords.push(...records); + }), + }, + }, + }); + + const response = yield* HttpClient.post("/api/observability/v1/traces", { + headers: { + cookie: yield* getAuthenticatedSessionCookieHeader(), + "content-type": "application/json", + origin: "http://localhost:5733", + }, + body: HttpBody.text(JSON.stringify(payload), "application/json"), + }); + + assert.equal(response.status, 204); + assert.equal(response.headers["access-control-allow-origin"], "*"); + assert.deepEqual(localTraceRecords, [ + { + type: "otlp-span", + name: "RpcClient.server.getSettings", + traceId: "11111111111111111111111111111111", + spanId: "2222222222222222", + parentSpanId: "3333333333333333", + sampled: true, + kind: "client", + startTimeUnixNano: "1000000", + endTimeUnixNano: "2000000", + durationMs: 1, + attributes: { + "rpc.method": "server.getSettings", + }, + resourceAttributes: { + "service.name": "t3-web", + }, + scope: { + name: "effect", + version: "4.0.0-beta.43", + attributes: {}, + }, + events: [ + { + name: "http.request", + timeUnixNano: "1500000", + attributes: { + "http.status_code": "200", + }, + }, + ], + links: [], + status: { + code: "STATUS_CODE_OK", + }, + }, + ]); + assert.deepEqual(upstreamRequests, [ + { + body: JSON.stringify(payload), + contentType: "application/json", + }, + ]); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("responds to browser OTLP trace preflight requests with CORS headers", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const url = yield* getHttpServerUrl("/api/observability/v1/traces"); + const response = yield* Effect.promise(() => + fetch(url, { + method: "OPTIONS", + headers: { + origin: "http://localhost:5733", + "access-control-request-method": "POST", + "access-control-request-headers": "content-type", + }, + }), + ); + + assert.equal(response.status, 204); + assert.equal(response.headers.get("access-control-allow-origin"), "*"); + assert.deepEqual(splitHeaderTokens(response.headers.get("access-control-allow-methods")), [ + "GET", + "OPTIONS", + "POST", + ]); + assert.deepEqual(splitHeaderTokens(response.headers.get("access-control-allow-headers")), [ + "authorization", + "b3", + "content-type", + "traceparent", + ]); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "stores browser OTLP trace exports locally when no upstream collector is configured", + () => + Effect.gen(function* () { + const localTraceRecords: Array = []; + const payload = yield* makeBrowserOtlpPayload("client.test"); + const resourceSpan = payload.resourceSpans[0]; + const scopeSpan = resourceSpan?.scopeSpans[0]; + const span = scopeSpan?.spans[0]; + + assert.notEqual(resourceSpan, undefined); + assert.notEqual(scopeSpan, undefined); + assert.notEqual(span, undefined); + if (!resourceSpan || !scopeSpan || !span) { + return; + } + + yield* buildAppUnderTest({ + layers: { + browserTraceCollector: { + record: (records) => + Effect.sync(() => { + localTraceRecords.push(...records); + }), + }, + }, + }); + + const response = yield* HttpClient.post("/api/observability/v1/traces", { + headers: { + cookie: yield* getAuthenticatedSessionCookieHeader(), + "content-type": "application/json", + }, + body: HttpBody.text(JSON.stringify(payload), "application/json"), + }); + + assert.equal(response.status, 204); + assert.equal(localTraceRecords.length, 1); + const record = localTraceRecords[0] as { + readonly type: string; + readonly name: string; + readonly traceId: string; + readonly spanId: string; + readonly kind: string; + readonly attributes: Readonly>; + readonly events: ReadonlyArray; + readonly links: ReadonlyArray; + readonly scope: { + readonly name?: string; + readonly attributes: Readonly>; + }; + readonly resourceAttributes: Readonly>; + readonly status?: { + readonly code?: string; + }; + }; + + assert.equal(record.type, "otlp-span"); + assert.equal(record.name, span.name); + assert.equal(record.traceId, span.traceId); + assert.equal(record.spanId, span.spanId); + assert.equal(record.kind, "internal"); + assert.deepEqual(record.attributes, {}); + assert.deepEqual(record.events, []); + assert.deepEqual(record.links, []); + assert.equal(record.scope.name, scopeSpan.scope.name); + assert.deepEqual(record.scope.attributes, {}); + assert.equal(record.resourceAttributes["service.name"], "t3-web"); + assert.equal(record.status?.code, String(span.status.code)); + }).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", + { + headers: { + cookie: yield* getAuthenticatedSessionCookieHeader(), + }, + }, + ); + 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 session authentication 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(); + + const wsUrl = yield* getWsServerUrl("/ws", { authenticated: false }); + 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("routes websocket rpc subscribeServerConfig streams snapshot then update", () => + Effect.gen(function* () { + const providers = [] as const; + const changeEvent = { + keybindings: [], + issues: [], + } as const; + + yield* buildAppUnderTest({ + config: { + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + }, + 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.equal(first.config.observability.logsDirectoryPath.endsWith("/logs"), true); + assert.equal(first.config.observability.localTracingEnabled, true); + assert.equal(first.config.observability.otlpTracesUrl, "http://localhost:4318/v1/traces"); + assert.equal(first.config.observability.otlpTracesEnabled, true); + assert.equal(first.config.observability.otlpMetricsUrl, "http://localhost:4318/v1/metrics"); + assert.equal(first.config.observability.otlpMetricsEnabled, true); + 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: { + environment: testEnvironmentDescriptor, + 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(), environment: testEnvironmentDescriptor }, + }); + + 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: { + invalidateLocalStatus: () => Effect.void, + invalidateRemoteStatus: () => Effect.void, + invalidateStatus: () => Effect.void, + localStatus: () => + Effect.succeed({ + isRepo: true, + hasOriginRemote: true, + isDefaultBranch: true, + branch: "main", + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + }), + remoteStatus: () => + Effect.succeed({ + hasUpstream: true, + aheadCount: 0, + behindCount: 0, + pr: null, + }), + status: () => + Effect.succeed({ + isRepo: true, + hasOriginRemote: true, + isDefaultBranch: true, + 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 }, + toast: { + title: "Committed abc123", + description: "feat: demo", + cta: { + kind: "run_action" as const, + label: "Push", + action: { + kind: "push" 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, + nextCursor: null, + totalCount: 1, + }), + createWorktree: () => + Effect.succeed({ + worktree: { path: "/tmp/wt", branch: "feature/demo" }, + }), + removeWorktree: () => Effect.void, + createBranch: (input) => Effect.succeed({ branch: input.branch }), + checkoutBranch: (input) => Effect.succeed({ branch: input.branch }), + initRepo: () => Effect.void, + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + + const pull = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitPull]({ cwd: "/tmp/repo" })), + ); + assert.equal(pull.status, "pulled"); + + const refreshedStatus = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitRefreshStatus]({ cwd: "/tmp/repo" }), + ), + ); + assert.equal(refreshedStatus.isRepo, true); + + 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", + }); + let invalidationCalls = 0; + let statusCalls = 0; + yield* buildAppUnderTest({ + layers: { + gitCore: { + pullCurrentBranch: () => Effect.fail(gitError), + }, + gitManager: { + invalidateLocalStatus: () => + Effect.sync(() => { + invalidationCalls += 1; + }), + invalidateRemoteStatus: () => + Effect.sync(() => { + invalidationCalls += 1; + }), + invalidateStatus: () => + Effect.sync(() => { + invalidationCalls += 1; + }), + localStatus: () => + Effect.succeed({ + isRepo: true, + hasOriginRemote: true, + isDefaultBranch: true, + branch: "main", + hasWorkingTreeChanges: true, + workingTree: { files: [], insertions: 0, deletions: 0 }, + }), + remoteStatus: () => + Effect.sync(() => { + statusCalls += 1; + return { + hasUpstream: true, + aheadCount: 0, + behindCount: 0, + pr: null, + }; + }), + status: () => + Effect.sync(() => { + statusCalls += 1; + return { + isRepo: true, + hasOriginRemote: true, + isDefaultBranch: true, + branch: "main", + hasWorkingTreeChanges: true, + workingTree: { files: [], insertions: 0, deletions: 0 }, + hasUpstream: true, + aheadCount: 0, + behindCount: 0, + pr: null, + }; + }), + }, + }, + }); + + 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); + assert.equal(invalidationCalls, 0); + assert.equal(statusCalls, 0); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc git.runStackedAction errors after refreshing git status", () => + Effect.gen(function* () { + const gitError = new GitCommandError({ + operation: "commit", + command: "git commit", + cwd: "/tmp/repo", + detail: "nothing to commit", + }); + let invalidationCalls = 0; + let statusCalls = 0; + yield* buildAppUnderTest({ + layers: { + gitManager: { + invalidateLocalStatus: () => + Effect.sync(() => { + invalidationCalls += 1; + }), + invalidateRemoteStatus: () => + Effect.sync(() => { + invalidationCalls += 1; + }), + invalidateStatus: () => + Effect.sync(() => { + invalidationCalls += 1; + }), + localStatus: () => + Effect.succeed({ + isRepo: true, + hasOriginRemote: true, + isDefaultBranch: false, + branch: "feature/demo", + hasWorkingTreeChanges: true, + workingTree: { files: [], insertions: 0, deletions: 0 }, + }), + remoteStatus: () => + Effect.sync(() => { + statusCalls += 1; + return { + hasUpstream: true, + aheadCount: 0, + behindCount: 0, + pr: null, + }; + }), + status: () => + Effect.sync(() => { + statusCalls += 1; + return { + isRepo: true, + hasOriginRemote: true, + isDefaultBranch: false, + branch: "feature/demo", + hasWorkingTreeChanges: true, + workingTree: { files: [], insertions: 0, deletions: 0 }, + hasUpstream: true, + aheadCount: 0, + behindCount: 0, + pr: null, + }; + }), + runStackedAction: () => Effect.fail(gitError), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const result = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitRunStackedAction]({ + actionId: "action-1", + cwd: "/tmp/repo", + action: "commit", + }).pipe(Stream.runCollect, Effect.result), + ), + ); + + assertFailure(result, gitError); + assert.equal(invalidationCalls, 0); + assert.equal(statusCalls, 0); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("completes websocket rpc git.pull before background git status refresh finishes", () => + Effect.gen(function* () { + yield* buildAppUnderTest({ + layers: { + gitCore: { + pullCurrentBranch: () => + Effect.succeed({ + status: "pulled" as const, + branch: "main", + upstreamBranch: "origin/main", + }), + }, + gitManager: { + invalidateLocalStatus: () => Effect.void, + invalidateRemoteStatus: () => Effect.void, + localStatus: () => + Effect.succeed({ + isRepo: true, + hasOriginRemote: true, + isDefaultBranch: true, + branch: "main", + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + }), + remoteStatus: () => + Effect.sleep(Duration.seconds(2)).pipe( + Effect.as({ + hasUpstream: true, + aheadCount: 0, + behindCount: 0, + pr: null, + }), + ), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const startedAt = Date.now(); + const result = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitPull]({ cwd: "/tmp/repo" })), + ); + const elapsedMs = Date.now() - startedAt; + + assert.equal(result.status, "pulled"); + assertTrue(elapsedMs < 1_000); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "completes websocket rpc git.runStackedAction before background git status refresh finishes", + () => + Effect.gen(function* () { + yield* buildAppUnderTest({ + layers: { + gitManager: { + invalidateLocalStatus: () => Effect.void, + invalidateRemoteStatus: () => Effect.void, + localStatus: () => + Effect.succeed({ + isRepo: true, + hasOriginRemote: true, + isDefaultBranch: false, + branch: "feature/demo", + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + }), + remoteStatus: () => + Effect.sleep(Duration.seconds(2)).pipe( + Effect.as({ + hasUpstream: true, + aheadCount: 0, + behindCount: 0, + pr: null, + }), + ), + runStackedAction: () => + Effect.succeed({ + 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 }, + toast: { + title: "Committed abc123", + description: "feat: demo", + cta: { + kind: "run_action" as const, + label: "Push", + action: { + kind: "push" as const, + }, + }, + }, + }), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const startedAt = Date.now(); + yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitRunStackedAction]({ + actionId: "action-1", + cwd: "/tmp/repo", + action: "commit", + }).pipe(Stream.runCollect), + ), + ); + const elapsedMs = Date.now() - startedAt; + + assertTrue(elapsedMs < 1_000); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "starts a background local git status refresh after a successful git.runStackedAction", + () => + Effect.gen(function* () { + const localRefreshStarted = yield* Deferred.make(); + + yield* buildAppUnderTest({ + layers: { + gitManager: { + invalidateLocalStatus: () => Effect.void, + invalidateRemoteStatus: () => Effect.void, + localStatus: () => + Deferred.succeed(localRefreshStarted, undefined).pipe( + Effect.ignore, + Effect.andThen( + Effect.succeed({ + isRepo: true, + hasOriginRemote: true, + isDefaultBranch: false, + branch: "feature/demo", + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + }), + ), + ), + remoteStatus: () => + Effect.sleep(Duration.seconds(2)).pipe( + Effect.as({ + hasUpstream: true, + aheadCount: 0, + behindCount: 0, + pr: null, + }), + ), + runStackedAction: () => + Effect.succeed({ + 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 }, + toast: { + title: "Committed abc123", + description: "feat: demo", + cta: { + kind: "run_action" as const, + label: "Push", + action: { + kind: "push" as const, + }, + }, + }, + }), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitRunStackedAction]({ + actionId: "action-1", + cwd: "/tmp/repo", + action: "commit", + }).pipe(Stream.runCollect), + ), + ); + + yield* Deferred.await(localRefreshStarted); + }).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.make("project-a"), + title: "Project A", + workspaceRoot: "/tmp/project-a", + defaultModelSelection, + scripts: [], + createdAt: now, + updatedAt: now, + deletedAt: null, + }, + ], + threads: [ + { + id: ThreadId.make("thread-1"), + projectId: ProjectId.make("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.make("thread-1"), + fromTurnCount: 0, + toTurnCount: 1, + diff: "turn-diff", + }), + getFullThreadDiff: () => + Effect.succeed({ + threadId: ThreadId.make("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.make("cmd-1"), + threadId: ThreadId.make("thread-1"), + createdAt: now, + }), + ), + ); + assert.equal(dispatchResult.sequence, 7); + + const turnDiffResult = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.getTurnDiff]({ + threadId: ThreadId.make("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.make("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("enriches replayed project events with repository identity metadata", () => + Effect.gen(function* () { + const repositoryIdentity = { + canonicalKey: "github.com/t3tools/t3code", + locator: { + source: "git-remote" as const, + remoteName: "origin", + remoteUrl: "git@github.com:T3Tools/t3code.git", + }, + displayName: "T3Tools/t3code", + provider: "github", + owner: "T3Tools", + name: "t3code", + }; + + yield* buildAppUnderTest({ + layers: { + orchestrationEngine: { + readEvents: (_fromSequenceExclusive) => + Stream.make({ + sequence: 1, + eventId: EventId.make("event-1"), + aggregateKind: "project", + aggregateId: defaultProjectId, + occurredAt: "2026-04-05T00:00:00.000Z", + commandId: null, + causationEventId: null, + correlationId: null, + metadata: {}, + type: "project.created", + payload: { + projectId: defaultProjectId, + title: "Default Project", + workspaceRoot: "/tmp/default-project", + defaultModelSelection, + scripts: [], + createdAt: "2026-04-05T00:00:00.000Z", + updatedAt: "2026-04-05T00:00:00.000Z", + }, + } satisfies Extract), + }, + repositoryIdentityResolver: { + resolve: () => Effect.succeed(repositoryIdentity), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const replayResult = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.replayEvents]({ + fromSequenceExclusive: 0, + }), + ), + ); + + const replayedEvent = replayResult[0]; + assert.equal(replayedEvent?.type, "project.created"); + assert.deepEqual( + replayedEvent && replayedEvent.type === "project.created" + ? replayedEvent.payload.repositoryIdentity + : null, + repositoryIdentity, + ); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("closes thread terminals after a successful archive command", () => + Effect.gen(function* () { + const threadId = ThreadId.make("thread-archive"); + const closeInputs: Array[0]> = []; + + yield* buildAppUnderTest({ + layers: { + terminalManager: { + close: (input) => + Effect.sync(() => { + closeInputs.push(input); + }), + }, + orchestrationEngine: { + dispatch: () => Effect.succeed({ sequence: 8 }), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const dispatchResult = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ + type: "thread.archive", + commandId: CommandId.make("cmd-thread-archive"), + threadId, + }), + ), + ); + + assert.equal(dispatchResult.sequence, 8); + assert.deepEqual(closeInputs, [{ threadId }]); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "bootstraps first-send worktree turns on the server before dispatching turn start", + () => + Effect.gen(function* () { + const dispatchedCommands: Array = []; + const createWorktree = vi.fn((_: Parameters[0]) => + Effect.succeed({ + worktree: { + branch: "t3code/bootstrap-branch", + path: "/tmp/bootstrap-worktree", + }, + }), + ); + const runForThread = vi.fn( + (_: Parameters[0]) => + Effect.succeed({ + status: "started" as const, + scriptId: "setup", + scriptName: "Setup", + terminalId: "setup-setup", + cwd: "/tmp/bootstrap-worktree", + }), + ); + + yield* buildAppUnderTest({ + layers: { + gitCore: { + createWorktree, + }, + orchestrationEngine: { + dispatch: (command) => + Effect.sync(() => { + dispatchedCommands.push(command); + return { sequence: dispatchedCommands.length }; + }), + readEvents: () => Stream.empty, + }, + projectSetupScriptRunner: { + runForThread, + }, + }, + }); + + const createdAt = new Date().toISOString(); + const wsUrl = yield* getWsServerUrl("/ws"); + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-bootstrap-turn-start"), + threadId: ThreadId.make("thread-bootstrap"), + message: { + messageId: MessageId.make("msg-bootstrap"), + role: "user", + text: "hello", + attachments: [], + }, + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + bootstrap: { + createThread: { + projectId: defaultProjectId, + title: "Bootstrap Thread", + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + createdAt, + }, + prepareWorktree: { + projectCwd: "/tmp/project", + baseBranch: "main", + branch: "t3code/bootstrap-branch", + }, + runSetupScript: true, + }, + createdAt, + }), + ), + ); + + assert.equal(response.sequence, 5); + assert.deepEqual( + dispatchedCommands.map((command) => command.type), + [ + "thread.create", + "thread.meta.update", + "thread.activity.append", + "thread.activity.append", + "thread.turn.start", + ], + ); + assert.deepEqual(createWorktree.mock.calls[0]?.[0], { + cwd: "/tmp/project", + branch: "main", + newBranch: "t3code/bootstrap-branch", + path: null, + }); + assert.deepEqual(runForThread.mock.calls[0]?.[0], { + threadId: ThreadId.make("thread-bootstrap"), + projectId: defaultProjectId, + projectCwd: "/tmp/project", + worktreePath: "/tmp/bootstrap-worktree", + }); + + const setupActivities = dispatchedCommands.filter( + (command): command is Extract => + command.type === "thread.activity.append", + ); + assert.deepEqual( + setupActivities.map((command) => command.activity.kind), + ["setup-script.requested", "setup-script.started"], + ); + const finalCommand = dispatchedCommands[4]; + assertTrue(finalCommand?.type === "thread.turn.start"); + if (finalCommand?.type === "thread.turn.start") { + assert.equal(finalCommand.bootstrap, undefined); + } + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("records setup-script failures without aborting bootstrap turn start", () => + Effect.gen(function* () { + const dispatchedCommands: Array = []; + const createWorktree = vi.fn((_: Parameters[0]) => + Effect.succeed({ + worktree: { + branch: "t3code/bootstrap-branch", + path: "/tmp/bootstrap-worktree", + }, + }), + ); + const runForThread = vi.fn( + (_: Parameters[0]) => + Effect.fail(new Error("pty unavailable")), + ); + + yield* buildAppUnderTest({ + layers: { + gitCore: { + createWorktree, + }, + orchestrationEngine: { + dispatch: (command) => + Effect.sync(() => { + dispatchedCommands.push(command); + return { sequence: dispatchedCommands.length }; + }), + readEvents: () => Stream.empty, + }, + projectSetupScriptRunner: { + runForThread, + }, + }, + }); + + const createdAt = new Date().toISOString(); + const wsUrl = yield* getWsServerUrl("/ws"); + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-bootstrap-turn-start-setup-failure"), + threadId: ThreadId.make("thread-bootstrap-setup-failure"), + message: { + messageId: MessageId.make("msg-bootstrap-setup-failure"), + role: "user", + text: "hello", + attachments: [], + }, + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + bootstrap: { + createThread: { + projectId: defaultProjectId, + title: "Bootstrap Thread", + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + createdAt, + }, + prepareWorktree: { + projectCwd: "/tmp/project", + baseBranch: "main", + branch: "t3code/bootstrap-branch", + }, + runSetupScript: true, + }, + createdAt, + }), + ), + ); + + assert.equal(response.sequence, 4); + assert.deepEqual( + dispatchedCommands.map((command) => command.type), + ["thread.create", "thread.meta.update", "thread.activity.append", "thread.turn.start"], + ); + const setupFailureActivity = dispatchedCommands.find( + (command): command is Extract => + command.type === "thread.activity.append", + ); + assert.equal(setupFailureActivity?.activity.kind, "setup-script.failed"); + assert.deepEqual(setupFailureActivity?.activity.payload, { + detail: "pty unavailable", + worktreePath: "/tmp/bootstrap-worktree", + }); + assertTrue(dispatchedCommands.every((command) => command.type !== "thread.delete")); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("does not misattribute setup activity dispatch failures as setup launch failures", () => + Effect.gen(function* () { + const dispatchedCommands: Array = []; + const createWorktree = vi.fn((_: Parameters[0]) => + Effect.succeed({ + worktree: { + branch: "t3code/bootstrap-branch", + path: "/tmp/bootstrap-worktree", + }, + }), + ); + const runForThread = vi.fn( + (_: Parameters[0]) => + Effect.succeed({ + status: "started" as const, + scriptId: "setup", + scriptName: "Setup", + terminalId: "setup-setup", + cwd: "/tmp/bootstrap-worktree", + }), + ); + let setupActivityAppendAttempt = 0; + + yield* buildAppUnderTest({ + layers: { + gitCore: { + createWorktree, + }, + orchestrationEngine: { + dispatch: (command) => { + if ( + command.type === "thread.activity.append" && + command.activity.kind.startsWith("setup-script.") + ) { + setupActivityAppendAttempt += 1; + if (setupActivityAppendAttempt === 2) { + return Effect.fail( + new OrchestrationListenerCallbackError({ + listener: "domain-event", + detail: "failed to append setup-script.started activity", + }), + ); + } + } + + return Effect.sync(() => { + dispatchedCommands.push(command); + return { sequence: dispatchedCommands.length }; + }); + }, + readEvents: () => Stream.empty, + }, + projectSetupScriptRunner: { + runForThread, + }, + }, + }); + + const createdAt = new Date().toISOString(); + const wsUrl = yield* getWsServerUrl("/ws"); + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-bootstrap-turn-start-setup-activity-failure"), + threadId: ThreadId.make("thread-bootstrap-setup-activity-failure"), + message: { + messageId: MessageId.make("msg-bootstrap-setup-activity-failure"), + role: "user", + text: "hello", + attachments: [], + }, + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + bootstrap: { + createThread: { + projectId: defaultProjectId, + title: "Bootstrap Thread", + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + createdAt, + }, + prepareWorktree: { + projectCwd: "/tmp/project", + baseBranch: "main", + branch: "t3code/bootstrap-branch", + }, + runSetupScript: true, + }, + createdAt, + }), + ), + ); + + assert.equal(response.sequence, 4); + assert.deepEqual( + dispatchedCommands.map((command) => command.type), + ["thread.create", "thread.meta.update", "thread.activity.append", "thread.turn.start"], + ); + const setupActivities = dispatchedCommands.filter( + (command): command is Extract => + command.type === "thread.activity.append", + ); + assert.deepEqual( + setupActivities.map((command) => command.activity.kind), + ["setup-script.requested"], + ); + assertTrue( + setupActivities.every((command) => command.activity.kind !== "setup-script.failed"), + ); + assertTrue(dispatchedCommands.every((command) => command.type !== "thread.delete")); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("cleans up created bootstrap threads when worktree creation defects", () => + Effect.gen(function* () { + const dispatchedCommands: Array = []; + const createWorktree = vi.fn((_: Parameters[0]) => + Effect.die(new Error("worktree exploded")), + ); + + yield* buildAppUnderTest({ + layers: { + gitCore: { + createWorktree, + }, + orchestrationEngine: { + dispatch: (command) => + Effect.sync(() => { + dispatchedCommands.push(command); + return { sequence: dispatchedCommands.length }; + }), + readEvents: () => Stream.empty, + }, + }, + }); + + const createdAt = new Date().toISOString(); + const wsUrl = yield* getWsServerUrl("/ws"); + const result = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-bootstrap-turn-start-defect"), + threadId: ThreadId.make("thread-bootstrap-defect"), + message: { + messageId: MessageId.make("msg-bootstrap-defect"), + role: "user", + text: "hello", + attachments: [], + }, + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + bootstrap: { + createThread: { + projectId: defaultProjectId, + title: "Bootstrap Thread", + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + createdAt, + }, + prepareWorktree: { + projectCwd: "/tmp/project", + baseBranch: "main", + branch: "t3code/bootstrap-branch", + }, + runSetupScript: false, + }, + createdAt, + }), + ).pipe(Effect.result), + ); + + assertTrue(result._tag === "Failure"); + assertTrue(result.failure._tag === "OrchestrationDispatchCommandError"); + assert.include(result.failure.message, "worktree exploded"); + assert.deepEqual( + dispatchedCommands.map((command) => command.type), + ["thread.create", "thread.delete"], + ); + }).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.make("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("enriches replayed project events only once before streaming them to subscribers", () => + Effect.gen(function* () { + let resolveCalls = 0; + const repositoryIdentity = { + canonicalKey: "github.com/t3tools/t3code", + locator: { + source: "git-remote" as const, + remoteName: "origin", + remoteUrl: "git@github.com:t3tools/t3code.git", + }, + displayName: "t3tools/t3code", + provider: "github" as const, + owner: "t3tools", + name: "t3code", + }; + + yield* buildAppUnderTest({ + layers: { + orchestrationEngine: { + getReadModel: () => + Effect.succeed({ + ...makeDefaultOrchestrationReadModel(), + snapshotSequence: 0, + }), + readEvents: () => + Stream.make({ + sequence: 1, + eventId: EventId.make("event-1"), + aggregateKind: "project", + aggregateId: defaultProjectId, + occurredAt: "2026-04-06T00:00:00.000Z", + commandId: null, + causationEventId: null, + correlationId: null, + metadata: {}, + type: "project.meta-updated", + payload: { + projectId: defaultProjectId, + title: "Replayed Project", + updatedAt: "2026-04-06T00:00:00.000Z", + }, + } satisfies Extract), + streamDomainEvents: Stream.empty, + }, + repositoryIdentityResolver: { + resolve: () => { + resolveCalls += 1; + return Effect.succeed(repositoryIdentity); + }, + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const events = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.subscribeOrchestrationDomainEvents]({}).pipe( + Stream.take(1), + Stream.runCollect, + ), + ), + ); + + const event = Array.from(events)[0]; + assert.equal(resolveCalls, 1); + assert.equal(event?.type, "project.meta-updated"); + assert.deepEqual( + event && event.type === "project.meta-updated" ? event.payload.repositoryIdentity : null, + repositoryIdentity, + ); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("enriches subscribed project meta updates with repository identity metadata", () => + Effect.gen(function* () { + const repositoryIdentity = { + canonicalKey: "github.com/t3tools/t3code", + locator: { + source: "git-remote" as const, + remoteName: "upstream", + remoteUrl: "git@github.com:T3Tools/t3code.git", + }, + displayName: "T3Tools/t3code", + provider: "github", + owner: "T3Tools", + name: "t3code", + }; + + yield* buildAppUnderTest({ + layers: { + orchestrationEngine: { + getReadModel: () => + Effect.succeed({ + ...makeDefaultOrchestrationReadModel(), + snapshotSequence: 0, + }), + streamDomainEvents: Stream.make({ + sequence: 1, + eventId: EventId.make("event-1"), + aggregateKind: "project", + aggregateId: defaultProjectId, + occurredAt: "2026-04-05T00:00:00.000Z", + commandId: null, + causationEventId: null, + correlationId: null, + metadata: {}, + type: "project.meta-updated", + payload: { + projectId: defaultProjectId, + title: "Renamed Project", + updatedAt: "2026-04-05T00:00:00.000Z", + }, + } satisfies Extract), + }, + repositoryIdentityResolver: { + resolve: () => Effect.succeed(repositoryIdentity), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const events = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.subscribeOrchestrationDomainEvents]({}).pipe( + Stream.take(1), + Stream.runCollect, + ), + ), + ); + + const event = Array.from(events)[0]; + assert.equal(event?.type, "project.meta-updated"); + assert.deepEqual( + event && event.type === "project.meta-updated" ? event.payload.repositoryIdentity : null, + repositoryIdentity, + ); + }).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", + worktreePath: null, + 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..23c53ad07f --- /dev/null +++ b/apps/server/src/server.ts @@ -0,0 +1,303 @@ +import { Effect, Layer } from "effect"; +import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http"; + +import { ServerConfig } from "./config"; +import { + attachmentsRouteLayer, + otlpTracesProxyRouteLayer, + projectFaviconRouteLayer, + serverEnvironmentRouteLayer, + staticAndDevRouteLayer, + browserApiCorsLayer, +} 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 { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery"; +import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore"; +import { GitCoreLive } from "./git/Layers/GitCore"; +import { GitHubCliLive } from "./git/Layers/GitHubCli"; +import { GitStatusBroadcasterLive } from "./git/Layers/GitStatusBroadcaster"; +import { RoutingTextGenerationLive } from "./git/Layers/RoutingTextGeneration"; +import { TerminalManagerLive } from "./terminal/Layers/Manager"; +import { GitManagerLive } from "./git/Layers/GitManager"; +import { KeybindingsLive } from "./keybindings"; +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 { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver"; +import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries"; +import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem"; +import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths"; +import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner"; +import { ObservabilityLive } from "./observability/Layers/Observability"; +import { ServerEnvironmentLive } from "./environment/Layers/ServerEnvironment"; +import { + authBearerBootstrapRouteLayer, + authBootstrapRouteLayer, + authClientsRevokeOthersRouteLayer, + authClientsRevokeRouteLayer, + authClientsRouteLayer, + authPairingLinksRevokeRouteLayer, + authPairingLinksRouteLayer, + authPairingCredentialRouteLayer, + authSessionRouteLayer, + authWebSocketTokenRouteLayer, +} from "./auth/http"; +import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore"; +import { ServerAuthLive } from "./auth/Layers/ServerAuth"; +import { OrchestrationLayerLive } from "./orchestration/runtimeLayer"; +import { + clearPersistedServerRuntimeState, + makePersistedServerRuntimeState, + persistServerRuntimeState, +} from "./serverRuntimeState"; +import { + orchestrationDispatchRouteLayer, + orchestrationSnapshotRouteLayer, +} from "./orchestration/http"; + +const PtyAdapterLive = Layer.unwrap( + Effect.gen(function* () { + if (typeof Bun !== "undefined") { + const BunPTY = yield* Effect.promise(() => import("./terminal/Layers/BunPTY")); + return BunPTY.layer; + } else { + const NodePTY = yield* Effect.promise(() => import("./terminal/Layers/NodePTY")); + return NodePTY.layer; + } + }), +); + +const HttpServerLive = Layer.unwrap( + Effect.gen(function* () { + const config = yield* ServerConfig; + if (typeof Bun !== "undefined") { + const BunHttpServer = yield* Effect.promise( + () => import("@effect/platform-bun/BunHttpServer"), + ); + return BunHttpServer.layer({ + port: config.port, + ...(config.host ? { hostname: config.host } : {}), + }); + } else { + const [NodeHttpServer, NodeHttp] = yield* Effect.all([ + Effect.promise(() => import("@effect/platform-node/NodeHttpServer")), + Effect.promise(() => import("node:http")), + ]); + return NodeHttpServer.layer(NodeHttp.createServer, { + host: config.host, + port: config.port, + }); + } + }), +); + +const PlatformServicesLive = Layer.unwrap( + Effect.gen(function* () { + if (typeof Bun !== "undefined") { + const { layer } = yield* Effect.promise(() => import("@effect/platform-bun/BunServices")); + return layer; + } else { + const { layer } = yield* Effect.promise(() => import("@effect/platform-node/NodeServices")); + return layer; + } + }), +); + +const ReactorLayerLive = Layer.empty.pipe( + Layer.provideMerge(OrchestrationReactorLive), + Layer.provideMerge(ProviderRuntimeIngestionLive), + Layer.provideMerge(ProviderCommandReactorLive), + Layer.provideMerge(CheckpointReactorLive), + Layer.provideMerge(RuntimeReceiptBusLive), +); + +const 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 GitManagerLayerLive = GitManagerLive.pipe( + Layer.provideMerge(ProjectSetupScriptRunnerLive), + Layer.provideMerge(GitCoreLive), + Layer.provideMerge(GitHubCliLive), + Layer.provideMerge(RoutingTextGenerationLive), +); + +const GitLayerLive = Layer.empty.pipe( + Layer.provideMerge(GitManagerLayerLive), + Layer.provideMerge(GitStatusBroadcasterLive.pipe(Layer.provide(GitManagerLayerLive))), + 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 AuthLayerLive = ServerAuthLive.pipe( + Layer.provideMerge(PersistenceLayerLive), + Layer.provide(ServerSecretStoreLive), +); + +const RuntimeDependenciesLive = ReactorLayerLive.pipe( + // Core Services + Layer.provideMerge(CheckpointingLayerLive), + Layer.provideMerge(GitLayerLive), + Layer.provideMerge(OrchestrationLayerLive), + Layer.provideMerge(ProviderLayerLive), + Layer.provideMerge(TerminalLayerLive), + Layer.provideMerge(PersistenceLayerLive), + Layer.provideMerge(KeybindingsLive), + Layer.provideMerge(ProviderRegistryLive), + Layer.provideMerge(ServerSettingsLive), + Layer.provideMerge(WorkspaceLayerLive), + Layer.provideMerge(ProjectFaviconResolverLive), + Layer.provideMerge(RepositoryIdentityResolverLive), + Layer.provideMerge(ServerEnvironmentLive), + Layer.provideMerge(AuthLayerLive), + + // Misc. + Layer.provideMerge(AnalyticsServiceLayerLive), + Layer.provideMerge(OpenLive), + Layer.provideMerge(ServerLifecycleEventsLive), +); + +const RuntimeServicesLive = ServerRuntimeStartupLive.pipe( + Layer.provideMerge(RuntimeDependenciesLive), +); + +export const makeRoutesLayer = Layer.mergeAll( + authBearerBootstrapRouteLayer, + authBootstrapRouteLayer, + authClientsRevokeOthersRouteLayer, + authClientsRevokeRouteLayer, + authClientsRouteLayer, + authPairingLinksRevokeRouteLayer, + authPairingLinksRouteLayer, + authPairingCredentialRouteLayer, + authSessionRouteLayer, + authWebSocketTokenRouteLayer, + attachmentsRouteLayer, + orchestrationDispatchRouteLayer, + orchestrationSnapshotRouteLayer, + otlpTracesProxyRouteLayer, + projectFaviconRouteLayer, + serverEnvironmentRouteLayer, + staticAndDevRouteLayer, + websocketRpcRouteLayer, +).pipe(Layer.provide(browserApiCorsLayer)); + +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 runtimeStateLayer = Layer.effectDiscard( + Effect.acquireRelease( + Effect.gen(function* () { + const server = yield* HttpServer.HttpServer; + const address = server.address; + if (typeof address === "string" || !("port" in address)) { + return; + } + + const state = makePersistedServerRuntimeState({ + config, + port: address.port, + }); + yield* persistServerRuntimeState({ + path: config.serverRuntimeStatePath, + state, + }); + }), + () => clearPersistedServerRuntimeState(config.serverRuntimeStatePath), + ), + ); + + const serverApplicationLayer = Layer.mergeAll( + HttpRouter.serve(makeRoutesLayer, { + disableLogger: !config.logWebSocketEvents, + }), + httpListeningLayer, + runtimeStateLayer, + ); + + return serverApplicationLayer.pipe( + Layer.provideMerge(RuntimeServicesLive), + Layer.provideMerge(HttpServerLive), + Layer.provide(ObservabilityLive), + 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 f745d553a1..0000000000 --- a/apps/server/src/serverLayers.ts +++ /dev/null @@ -1,161 +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"; -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"; - -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 gitCoreLayer = GitCoreLive; - const checkpointStoreLayer = CheckpointStoreLive; - - 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(textGenerationLayer), - ); - const checkpointReactorLayer = CheckpointReactorLive.pipe( - Layer.provideMerge(runtimeServicesLayer), - Layer.provideMerge(WorkspaceEntriesLive), - ); - 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(GitHubCliLive), - Layer.provideMerge(textGenerationLayer), - ); - - const workspacePathsLayer = WorkspacePathsLive; - const workspaceEntriesLayer = WorkspaceEntriesLive; - const workspaceFileSystemLayer = WorkspaceFileSystemLive.pipe( - Layer.provide(workspacePathsLayer), - Layer.provide(workspaceEntriesLayer), - ); - const projectFaviconResolverLayer = ProjectFaviconResolverLive; - - return Layer.mergeAll( - orchestrationReactorLayer, - workspacePathsLayer, - workspaceEntriesLayer, - workspaceFileSystemLayer, - projectFaviconResolverLayer, - gitManagerLayer, - terminalLayer, - KeybindingsLive, - ).pipe(Layer.provideMerge(gitCoreLayer), 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..47e24c1b87 --- /dev/null +++ b/apps/server/src/serverLifecycleEvents.test.ts @@ -0,0 +1,52 @@ +import { EnvironmentId } from "@t3tools/contracts"; +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 environment = { + environmentId: EnvironmentId.make("environment-test"), + label: "Test environment", + platform: { os: "darwin" as const, arch: "arm64" as const }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, + }; + + const welcome = yield* lifecycleEvents + .publish({ + version: 1, + type: "welcome", + payload: { + environment, + 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(), + environment, + }, + }) + .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..145d1cbaa4 --- /dev/null +++ b/apps/server/src/serverLifecycleEvents.ts @@ -0,0 +1,53 @@ +import type { ServerLifecycleStreamEvent } from "@t3tools/contracts"; +import { Effect, Layer, PubSub, Ref, Context, 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 Context.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..ea098dcbbe 100644 --- a/apps/server/src/serverLogger.ts +++ b/apps/server/src/serverLogger.ts @@ -1,20 +1,13 @@ -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 fileLogger = Logger.formatSimple.pipe(Logger.toFile(serverLogPath)); - - return Logger.layer([Logger.defaultLogger, fileLogger], { + const config = yield* ServerConfig; + const minimumLogLevelLayer = Layer.succeed(References.MinimumLogLevel, config.logLevel); + const loggerLayer = Logger.layer([Logger.consolePretty(), Logger.tracerLogger], { 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..c3159cc9d8 --- /dev/null +++ b/apps/server/src/serverRuntimeStartup.test.ts @@ -0,0 +1,91 @@ +import { DEFAULT_MODEL_BY_PROVIDER } from "@t3tools/contracts"; +import { assert, it } from "@effect/vitest"; +import { Deferred, Effect, Fiber, Option, Ref } from "effect"; + +import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts"; +import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts"; +import { + getAutoBootstrapDefaultModelSelection, + launchStartupHeartbeat, + makeCommandGate, + ServerRuntimeStartupError, +} from "./serverRuntimeStartup.ts"; + +it("uses the canonical Codex default for auto-bootstrapped model selection", () => { + assert.deepStrictEqual(getAutoBootstrapDefaultModelSelection(), { + provider: "codex", + model: DEFAULT_MODEL_BY_PROVIDER.codex, + }); +}); + +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* Effect.yieldNow; + 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"); + }), + ), +); + +it.effect("launchStartupHeartbeat does not block the caller while counts are loading", () => + Effect.scoped( + Effect.gen(function* () { + const releaseCounts = yield* Deferred.make(); + + yield* launchStartupHeartbeat.pipe( + Effect.provideService(ProjectionSnapshotQuery, { + getSnapshot: () => Effect.die("unused"), + getCounts: () => + Deferred.await(releaseCounts).pipe( + Effect.as({ + projectCount: 2, + threadCount: 3, + }), + ), + getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()), + getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()), + getThreadCheckpointContext: () => Effect.succeed(Option.none()), + }), + Effect.provideService(AnalyticsService, { + record: () => Effect.void, + flush: Effect.void, + }), + ); + }), + ), +); diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts new file mode 100644 index 0000000000..441df3395d --- /dev/null +++ b/apps/server/src/serverRuntimeStartup.ts @@ -0,0 +1,418 @@ +import { + CommandId, + DEFAULT_MODEL_BY_PROVIDER, + DEFAULT_PROVIDER_INTERACTION_MODE, + type ModelSelection, + ProjectId, + ThreadId, +} from "@t3tools/contracts"; +import { + Data, + Deferred, + Effect, + Exit, + Layer, + Option, + Path, + Queue, + Ref, + Scope, + Context, + Console, +} 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 { ServerEnvironment } from "./environment/Services/ServerEnvironment"; +import { AnalyticsService } from "./telemetry/Services/AnalyticsService"; +import { ServerAuth } from "./auth/Services/ServerAuth"; +import { + formatHeadlessServeOutput, + formatHostForUrl, + isWildcardHost, + issueHeadlessServeAccessInfo, +} from "./startupAccess"; + +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 Context.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; +}); + +export const recordStartupHeartbeat = Effect.gen(function* () { + const analytics = yield* AnalyticsService; + const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; + + const { threadCount, projectCount } = yield* projectionSnapshotQuery.getCounts().pipe( + Effect.catch((cause) => + Effect.logWarning("failed to gather startup projection counts for telemetry", { + cause, + }).pipe( + Effect.as({ + threadCount: 0, + projectCount: 0, + }), + ), + ), + ); + + yield* analytics.record("server.boot.heartbeat", { + threadCount, + projectCount, + }); +}); + +export const launchStartupHeartbeat = recordStartupHeartbeat.pipe( + Effect.annotateSpans({ "startup.phase": "heartbeat.record" }), + Effect.withSpan("server.startup.heartbeat.record"), + Effect.ignoreCause({ log: true }), + Effect.forkScoped, + Effect.asVoid, +); + +export const getAutoBootstrapDefaultModelSelection = (): ModelSelection => ({ + provider: "codex", + model: DEFAULT_MODEL_BY_PROVIDER.codex, +}); + +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 existingProject = yield* projectionReadModelQuery.getActiveProjectByWorkspaceRoot( + serverConfig.cwd, + ); + let nextProjectId: ProjectId; + let nextProjectDefaultModelSelection: ModelSelection; + + if (Option.isNone(existingProject)) { + const createdAt = new Date().toISOString(); + nextProjectId = ProjectId.make(crypto.randomUUID()); + const bootstrapProjectTitle = path.basename(serverConfig.cwd) || "project"; + nextProjectDefaultModelSelection = getAutoBootstrapDefaultModelSelection(); + yield* orchestrationEngine.dispatch({ + type: "project.create", + commandId: CommandId.make(crypto.randomUUID()), + projectId: nextProjectId, + title: bootstrapProjectTitle, + workspaceRoot: serverConfig.cwd, + defaultModelSelection: nextProjectDefaultModelSelection, + createdAt, + }); + } else { + nextProjectId = existingProject.value.id; + nextProjectDefaultModelSelection = + existingProject.value.defaultModelSelection ?? getAutoBootstrapDefaultModelSelection(); + } + + const existingThreadId = + yield* projectionReadModelQuery.getFirstActiveThreadIdByProjectId(nextProjectId); + if (Option.isNone(existingThreadId)) { + const createdAt = new Date().toISOString(); + const createdThreadId = ThreadId.make(crypto.randomUUID()); + yield* orchestrationEngine.dispatch({ + type: "thread.create", + commandId: CommandId.make(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 = existingThreadId.value; + } + }); + } + + 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 resolveStartupBrowserTarget = Effect.gen(function* () { + const serverConfig = yield* ServerConfig; + const serverAuth = yield* ServerAuth; + const localUrl = `http://localhost:${serverConfig.port}`; + const bindUrl = + serverConfig.host && !isWildcardHost(serverConfig.host) + ? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}` + : localUrl; + const baseTarget = serverConfig.devUrl?.toString() ?? bindUrl; + return yield* Effect.succeed(serverConfig.mode === "desktop" ? baseTarget : undefined).pipe( + Effect.flatMap((target) => + target ? Effect.succeed(target) : serverAuth.issueStartupPairingUrl(baseTarget), + ), + ); +}); + +const maybeOpenBrowser = (target: string) => + Effect.gen(function* () { + const serverConfig = yield* ServerConfig; + if (serverConfig.noBrowser) { + return; + } + const { openBrowser } = yield* Open; + + yield* openBrowser(target).pipe( + Effect.catch(() => + Effect.logInfo("browser auto-open unavailable", { + hint: `Open ${target} in your browser.`, + }), + ), + ); + }); + +const runStartupPhase = (phase: string, effect: Effect.Effect) => + effect.pipe( + Effect.annotateSpans({ "startup.phase": phase }), + Effect.withSpan(`server.startup.${phase}`), + ); + +const makeServerRuntimeStartup = Effect.gen(function* () { + const serverConfig = yield* ServerConfig; + const keybindings = yield* Keybindings; + const orchestrationReactor = yield* OrchestrationReactor; + const lifecycleEvents = yield* ServerLifecycleEvents; + const serverSettings = yield* ServerSettingsService; + const serverEnvironment = yield* ServerEnvironment; + + 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* runStartupPhase( + "keybindings.start", + 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* runStartupPhase( + "settings.start", + 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* runStartupPhase( + "reactors.start", + orchestrationReactor.start().pipe(Scope.provide(reactorScope)), + ); + + yield* Effect.logDebug("startup phase: preparing welcome payload"); + const welcome = yield* runStartupPhase("welcome.prepare", autoBootstrapWelcome); + const environment = yield* serverEnvironment.getDescriptor; + yield* Effect.logDebug("startup phase: publishing welcome event", { + environmentId: environment.environmentId, + cwd: welcome.cwd, + projectName: welcome.projectName, + bootstrapProjectId: welcome.bootstrapProjectId, + bootstrapThreadId: welcome.bootstrapThreadId, + }); + yield* runStartupPhase( + "welcome.publish", + lifecycleEvents.publish({ + version: 1, + type: "welcome", + payload: { + environment, + ...welcome, + }, + }), + ); + }).pipe( + Effect.annotateSpans({ + "server.mode": serverConfig.mode, + "server.port": serverConfig.port, + "server.host": serverConfig.host ?? "default", + }), + Effect.withSpan("server.startup", { kind: "server", root: true }), + ); + + 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* runStartupPhase("http.wait", Deferred.await(httpListening)); + yield* Effect.logDebug("startup phase: publishing ready event"); + yield* runStartupPhase( + "ready.publish", + lifecycleEvents.publish({ + version: 1, + type: "ready", + payload: { + at: new Date().toISOString(), + environment: yield* serverEnvironment.getDescriptor, + }, + }), + ); + + yield* Effect.logDebug("startup phase: recording startup heartbeat"); + yield* launchStartupHeartbeat; + if (serverConfig.startupPresentation === "headless") { + yield* Effect.logDebug("startup phase: headless access info"); + const accessInfo = yield* issueHeadlessServeAccessInfo(); + yield* runStartupPhase( + "headless.output", + Console.log(formatHeadlessServeOutput(accessInfo)), + ); + } else { + yield* Effect.logDebug("startup phase: browser open check"); + const startupBrowserTarget = yield* resolveStartupBrowserTarget; + if (serverConfig.mode !== "desktop") { + yield* Effect.logInfo( + "Authentication required. Open T3 Code using the pairing URL.", + ).pipe(Effect.annotateLogs({ pairingUrl: startupBrowserTarget })); + } + yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget)); + } + 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/serverRuntimeState.ts b/apps/server/src/serverRuntimeState.ts new file mode 100644 index 0000000000..00c8384468 --- /dev/null +++ b/apps/server/src/serverRuntimeState.ts @@ -0,0 +1,77 @@ +import { Effect, FileSystem, Option, Path, Schema } from "effect"; + +import { type ServerConfigShape } from "./config"; +import { formatHostForUrl, isWildcardHost } from "./startupAccess"; + +export const PersistedServerRuntimeState = Schema.Struct({ + version: Schema.Literal(1), + pid: Schema.Int, + host: Schema.optional(Schema.String), + port: Schema.Int, + origin: Schema.String, + startedAt: Schema.String, +}); +export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type; + +const decodePersistedServerRuntimeState = Schema.decodeUnknownEffect( + Schema.fromJsonString(PersistedServerRuntimeState), +); + +const runtimeOriginForConfig = ( + config: Pick, + port: number, +): PersistedServerRuntimeState["origin"] => { + const hostname = + config.host && !isWildcardHost(config.host) ? formatHostForUrl(config.host) : "127.0.0.1"; + return `http://${hostname}:${port}`; +}; + +export const makePersistedServerRuntimeState = (input: { + readonly config: Pick; + readonly port: number; +}): PersistedServerRuntimeState => ({ + version: 1, + pid: process.pid, + ...(input.config.host ? { host: input.config.host } : {}), + port: input.port, + origin: runtimeOriginForConfig(input.config, input.port), + startedAt: new Date().toISOString(), +}); + +export const persistServerRuntimeState = (input: { + readonly path: string; + readonly state: PersistedServerRuntimeState; +}) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const pathService = yield* Path.Path; + const tempPath = `${input.path}.${process.pid}.${Date.now()}.tmp`; + return yield* fs.makeDirectory(pathService.dirname(input.path), { recursive: true }).pipe( + Effect.flatMap(() => fs.writeFileString(tempPath, `${JSON.stringify(input.state)}\n`)), + Effect.flatMap(() => fs.rename(tempPath, input.path)), + Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))), + ); + }); + +export const clearPersistedServerRuntimeState = (path: string) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + yield* fs.remove(path, { force: true }).pipe(Effect.ignore({ log: true })); + }); + +export const readPersistedServerRuntimeState = (path: string) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const exists = yield* fs.exists(path).pipe(Effect.orElseSucceed(() => false)); + if (!exists) { + return Option.none(); + } + + const raw = yield* fs.readFileString(path).pipe(Effect.orElseSucceed(() => "")); + const trimmed = raw.trim(); + if (trimmed.length === 0) { + return Option.none(); + } + + return yield* decodePersistedServerRuntimeState(trimmed).pipe(Effect.option); + }); diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index c0aec009a0..289bc68961 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -171,6 +171,24 @@ it.layer(NodeServices.layer)("server settings", (it) => { }).pipe(Effect.provide(makeServerSettingsLayer())), ); + it.effect("trims observability settings when updates are applied", () => + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + + const next = yield* serverSettings.updateSettings({ + observability: { + otlpTracesUrl: " http://localhost:4318/v1/traces ", + otlpMetricsUrl: " http://localhost:4318/v1/metrics ", + }, + }); + + assert.deepEqual(next.observability, { + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + }); + }).pipe(Effect.provide(makeServerSettingsLayer())), + ); + it.effect("defaults blank binary paths to provider executables", () => Effect.gen(function* () { const serverSettings = yield* ServerSettingsService; @@ -197,6 +215,10 @@ it.layer(NodeServices.layer)("server settings", (it) => { const serverConfig = yield* ServerConfig; const fileSystem = yield* FileSystem.FileSystem; const next = yield* serverSettings.updateSettings({ + observability: { + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + }, providers: { codex: { binaryPath: "/opt/homebrew/bin/codex", @@ -208,6 +230,10 @@ it.layer(NodeServices.layer)("server settings", (it) => { const raw = yield* fileSystem.readFileString(serverConfig.settingsPath); assert.deepEqual(JSON.parse(raw), { + observability: { + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + }, providers: { codex: { binaryPath: "/opt/homebrew/bin/codex", diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index a5b4345d50..5a708d5c23 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 { @@ -33,27 +34,15 @@ import { Schema, SchemaIssue, Scope, - ServiceMap, + Context, 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; @@ -73,7 +62,7 @@ export interface ServerSettingsShape { readonly streamChanges: Stream.Stream; } -export class ServerSettingsService extends ServiceMap.Service< +export class ServerSettingsService extends Context.Service< ServerSettingsService, ServerSettingsShape >()("t3/serverSettings/ServerSettingsService") { @@ -215,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/startupAccess.test.ts b/apps/server/src/startupAccess.test.ts new file mode 100644 index 0000000000..ef6ece31e2 --- /dev/null +++ b/apps/server/src/startupAccess.test.ts @@ -0,0 +1,79 @@ +import { assert, expect, it } from "@effect/vitest"; + +import { + buildPairingUrl, + formatHeadlessServeOutput, + renderTerminalQrCode, + resolveHeadlessConnectionHost, + resolveHeadlessConnectionString, + resolveListeningPort, +} from "./startupAccess"; + +it("prefers localhost when no explicit host is configured", () => { + expect(resolveHeadlessConnectionHost(undefined)).toBe("localhost"); + expect(resolveHeadlessConnectionString(undefined, 3773)).toBe("http://localhost:3773"); +}); + +it("keeps explicit bind hosts in the connection string", () => { + expect(resolveHeadlessConnectionString("127.0.0.1", 3773)).toBe("http://127.0.0.1:3773"); + expect(resolveHeadlessConnectionString("::1", 3773)).toBe("http://[::1]:3773"); +}); + +it("resolves wildcard hosts to a concrete external interface when one is available", () => { + const connectionString = resolveHeadlessConnectionString("0.0.0.0", 3773, { + en0: [ + { + address: "192.168.1.42", + netmask: "255.255.255.0", + family: "IPv4", + mac: "00:00:00:00:00:00", + internal: false, + cidr: "192.168.1.42/24", + }, + ], + lo0: [ + { + address: "127.0.0.1", + netmask: "255.0.0.0", + family: "IPv4", + mac: "00:00:00:00:00:00", + internal: true, + cidr: "127.0.0.1/8", + }, + ], + }); + + expect(connectionString).toBe("http://192.168.1.42:3773"); +}); + +it("prefers the actual bound port when an http server address is available", () => { + expect(resolveListeningPort({ port: 4123 }, 3773)).toBe(4123); + expect(resolveListeningPort("pipe", 3773)).toBe(3773); + expect(resolveListeningPort(null, 3773)).toBe(3773); +}); + +it("builds a pairing URL that embeds the token in the hash", () => { + expect(buildPairingUrl("http://192.168.1.42:3773", "PAIRCODE")).toBe( + "http://192.168.1.42:3773/pair#token=PAIRCODE", + ); +}); + +it("renders terminal QR codes as a multi-line unicode block grid", () => { + const qrCode = renderTerminalQrCode("http://192.168.1.42:3773/pair#token=PAIRCODE"); + + assert.isTrue(qrCode.includes("█")); + assert.isTrue(qrCode.split("\n").length > 10); +}); + +it("formats headless serve output with the connection string, token, pairing url, and qr code", () => { + const output = formatHeadlessServeOutput({ + connectionString: "http://192.168.1.42:3773", + token: "PAIRCODE", + pairingUrl: "http://192.168.1.42:3773/pair#token=PAIRCODE", + }); + + expect(output).toContain("Connection string: http://192.168.1.42:3773"); + expect(output).toContain("Token: PAIRCODE"); + expect(output).toContain("Pairing URL: http://192.168.1.42:3773/pair#token=PAIRCODE"); + assert.isTrue(output.includes("█") || output.includes("▀") || output.includes("▄")); +}); diff --git a/apps/server/src/startupAccess.ts b/apps/server/src/startupAccess.ts new file mode 100644 index 0000000000..a350d729d0 --- /dev/null +++ b/apps/server/src/startupAccess.ts @@ -0,0 +1,148 @@ +import { networkInterfaces } from "node:os"; + +import { QrCode } from "@t3tools/shared/qrCode"; +import { Effect } from "effect"; +import { HttpServer } from "effect/unstable/http"; + +import { ServerConfig } from "./config"; +import { ServerAuth } from "./auth/Services/ServerAuth"; + +export interface HeadlessServeAccessInfo { + readonly connectionString: string; + readonly token: string; + readonly pairingUrl: string; +} + +type NetworkInterfacesMap = ReturnType; + +export const isLoopbackHost = (host: string | undefined): boolean => { + if (!host || host.length === 0) { + return true; + } + + return ( + host === "localhost" || + host === "127.0.0.1" || + host === "::1" || + host === "[::1]" || + host.startsWith("127.") + ); +}; + +export const isWildcardHost = (host: string | undefined): boolean => + host === "0.0.0.0" || host === "::" || host === "[::]"; + +export const formatHostForUrl = (host: string): string => + host.includes(":") && !host.startsWith("[") ? `[${host}]` : host; + +const normalizeHost = (host: string): string => + host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host; + +const isIpv4Family = (family: string | number): boolean => family === "IPv4" || family === 4; + +const isIpv6Family = (family: string | number): boolean => family === "IPv6" || family === 6; + +export const resolveHeadlessConnectionHost = ( + host: string | undefined, + interfaces: NetworkInterfacesMap = networkInterfaces(), +): string => { + if (!host) { + return "localhost"; + } + + if (!isWildcardHost(host)) { + return normalizeHost(host); + } + + const interfaceEntries = Object.values(interfaces).flatMap((entries) => entries ?? []); + const externalIpv4 = interfaceEntries.find( + (entry) => !entry.internal && isIpv4Family(entry.family), + ); + if (externalIpv4) { + return externalIpv4.address; + } + + const externalIpv6 = interfaceEntries.find( + (entry) => !entry.internal && isIpv6Family(entry.family), + ); + return externalIpv6 ? normalizeHost(externalIpv6.address) : "localhost"; +}; + +export const resolveHeadlessConnectionString = ( + host: string | undefined, + port: number, + interfaces: NetworkInterfacesMap = networkInterfaces(), +): string => { + const connectionHost = resolveHeadlessConnectionHost(host, interfaces); + return `http://${formatHostForUrl(connectionHost)}:${port}`; +}; + +export const resolveListeningPort = (address: unknown, fallbackPort: number): number => { + if ( + typeof address === "object" && + address !== null && + "port" in address && + typeof address.port === "number" + ) { + return address.port; + } + return fallbackPort; +}; + +export const buildPairingUrl = (connectionString: string, token: string): string => { + const url = new URL(connectionString); + url.pathname = "/pair"; + url.searchParams.delete("token"); + url.hash = new URLSearchParams([["token", token]]).toString(); + return url.toString(); +}; + +export const renderTerminalQrCode = (value: string, margin = 2): string => { + const qrCode = QrCode.encodeText(value, QrCode.Ecc.MEDIUM); + const rows: Array = []; + const isDark = (x: number, y: number): boolean => + x >= 0 && x < qrCode.size && y >= 0 && y < qrCode.size && qrCode.getModule(x, y); + + for (let y = -margin; y < qrCode.size + margin; y += 2) { + let row = ""; + + for (let x = -margin; x < qrCode.size + margin; x += 1) { + const topDark = isDark(x, y); + const bottomDark = isDark(x, y + 1); + + row += topDark ? (bottomDark ? "█" : "▀") : bottomDark ? "▄" : " "; + } + + rows.push(row); + } + + return rows.join("\n"); +}; + +export const formatHeadlessServeOutput = (accessInfo: HeadlessServeAccessInfo): string => + [ + "T3 Code server is ready.", + `Connection string: ${accessInfo.connectionString}`, + `Token: ${accessInfo.token}`, + `Pairing URL: ${accessInfo.pairingUrl}`, + "", + renderTerminalQrCode(accessInfo.pairingUrl), + "", + ].join("\n"); + +export const issueHeadlessServeAccessInfo = Effect.fn("issueHeadlessServeAccessInfo")(function* () { + const serverConfig = yield* ServerConfig; + const httpServer = yield* HttpServer.HttpServer; + const serverAuth = yield* ServerAuth; + const connectionString = resolveHeadlessConnectionString( + serverConfig.host, + resolveListeningPort(httpServer.address, serverConfig.port), + ); + const issued = yield* serverAuth.issuePairingCredential({ role: "owner" }); + + return { + connectionString, + token: issued.credential, + pairingUrl: buildPairingUrl(connectionString, issued.credential), + } satisfies HeadlessServeAccessInfo; +}); diff --git a/apps/server/src/telemetry/Layers/AnalyticsService.ts b/apps/server/src/telemetry/Layers/AnalyticsService.ts index 297776f9db..e933576dff 100644 --- a/apps/server/src/telemetry/Layers/AnalyticsService.ts +++ b/apps/server/src/telemetry/Layers/AnalyticsService.ts @@ -70,34 +70,35 @@ const makeAnalyticsService = Effect.gen(function* () { }), ); - const sendBatch = (events: ReadonlyArray) => - Effect.gen(function* () { - if (!telemetryConfig.enabled || !identifier) return; + const sendBatch = Effect.fn("sendBatch")(function* ( + events: ReadonlyArray, + ) { + if (!telemetryConfig.enabled || !identifier) return; - const payload = { - api_key: telemetryConfig.posthogKey, - batch: events.map((event) => ({ - event: event.event, - distinct_id: identifier, - properties: { - ...event.properties, - $process_person_profile: false, - platform: process.platform, - wsl: process.env.WSL_DISTRO_NAME, - arch: process.arch, - t3CodeVersion: version, - clientType, - }, - timestamp: event.capturedAt, - })), - }; + const payload = { + api_key: telemetryConfig.posthogKey, + batch: events.map((event) => ({ + event: event.event, + distinct_id: identifier, + properties: { + ...event.properties, + $process_person_profile: false, + platform: process.platform, + wsl: process.env.WSL_DISTRO_NAME, + arch: process.arch, + t3CodeVersion: version, + clientType, + }, + timestamp: event.capturedAt, + })), + }; - yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe( - HttpClientRequest.bodyJson(payload), - Effect.flatMap(httpClient.execute), - Effect.flatMap(HttpClientResponse.filterStatusOk), - ); - }); + yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe( + HttpClientRequest.bodyJson(payload), + Effect.flatMap(httpClient.execute), + Effect.flatMap(HttpClientResponse.filterStatusOk), + ); + }); const flush: AnalyticsServiceShape["flush"] = Effect.gen(function* () { while (true) { @@ -124,17 +125,19 @@ const makeAnalyticsService = Effect.gen(function* () { } }).pipe(Effect.catch((cause) => Effect.logError("Failed to flush telemetry", { cause }))); - const record: AnalyticsServiceShape["record"] = Effect.fnUntraced(function* (event, properties) { - if (!telemetryConfig.enabled || !identifier) return; + const record: AnalyticsServiceShape["record"] = Effect.fn("record")( + function* (event, properties) { + if (!telemetryConfig.enabled || !identifier) return; - const enqueueResult = yield* enqueueBufferedEvent(event, properties); - if (enqueueResult.dropped) { - yield* Effect.logDebug("analytics buffer full; dropping oldest event", { - size: enqueueResult.size, - event, - }); - } - }); + const enqueueResult = yield* enqueueBufferedEvent(event, properties); + if (enqueueResult.dropped) { + yield* Effect.logDebug("analytics buffer full; dropping oldest event", { + size: enqueueResult.size, + event, + }); + } + }, + ); yield* Effect.forever(Effect.sleep(1000).pipe(Effect.flatMap(() => flush)), { disableYield: true, diff --git a/apps/server/src/telemetry/Services/AnalyticsService.ts b/apps/server/src/telemetry/Services/AnalyticsService.ts index 64f8c8de55..0e703573d4 100644 --- a/apps/server/src/telemetry/Services/AnalyticsService.ts +++ b/apps/server/src/telemetry/Services/AnalyticsService.ts @@ -6,7 +6,7 @@ * * @module AnalyticsService */ -import { Effect, Layer, ServiceMap } from "effect"; +import { Effect, Layer, Context } from "effect"; export interface AnalyticsServiceShape { /** @@ -23,7 +23,7 @@ export interface AnalyticsServiceShape { readonly flush: Effect.Effect; } -export class AnalyticsService extends ServiceMap.Service()( +export class AnalyticsService extends Context.Service()( "t3/telemetry/Services/AnalyticsService", ) { static readonly layerTest = Layer.succeed(AnalyticsService, { diff --git a/apps/server/src/terminal/Layers/Manager.test.ts b/apps/server/src/terminal/Layers/Manager.test.ts index ccdd477178..8207861e20 100644 --- a/apps/server/src/terminal/Layers/Manager.test.ts +++ b/apps/server/src/terminal/Layers/Manager.test.ts @@ -428,6 +428,85 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", ( }), ); + it.effect("propagates explicit worktree metadata through snapshots and lifecycle events", () => + Effect.gen(function* () { + const { manager, getEvents, baseDir } = yield* createManager(); + const firstWorktreePath = path.join(baseDir, "worktrees", "feature-a"); + const secondWorktreePath = path.join(baseDir, "worktrees", "feature-b"); + yield* makeDirectory(firstWorktreePath); + yield* makeDirectory(secondWorktreePath); + const startedSnapshot = yield* manager.open( + openInput({ + cwd: firstWorktreePath, + worktreePath: firstWorktreePath, + }), + ); + const restartedSnapshot = yield* manager.restart( + restartInput({ + cwd: secondWorktreePath, + worktreePath: secondWorktreePath, + }), + ); + + assert.equal(startedSnapshot.worktreePath, firstWorktreePath); + assert.equal(restartedSnapshot.worktreePath, secondWorktreePath); + + const events = yield* getEvents; + const startedEvent = events.find( + (event): event is Extract => event.type === "started", + ); + const restartedEvent = events.find( + (event): event is Extract => + event.type === "restarted", + ); + + assert.equal(startedEvent?.snapshot.worktreePath, firstWorktreePath); + assert.equal(restartedEvent?.snapshot.worktreePath, secondWorktreePath); + }), + ); + + it.effect("preserves worktree metadata when reopening an exited session", () => + Effect.gen(function* () { + const { manager, ptyAdapter, getEvents, baseDir } = yield* createManager(); + const worktreePath = path.join(baseDir, "worktrees", "feature-a"); + yield* makeDirectory(worktreePath); + + yield* manager.open( + openInput({ + cwd: worktreePath, + worktreePath, + }), + ); + + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + process.emitExit({ exitCode: 0, signal: 0 }); + + yield* waitFor( + Effect.map(getEvents, (events) => events.some((event) => event.type === "exited")), + ); + + const reopenedSnapshot = yield* manager.open( + openInput({ + cwd: worktreePath, + worktreePath, + }), + ); + + assert.equal(reopenedSnapshot.worktreePath, worktreePath); + + const events = yield* getEvents; + const reopenedEvent = events + .toReversed() + .find( + (event): event is Extract => event.type === "started", + ); + + assert.equal(reopenedEvent?.snapshot.worktreePath, worktreePath); + }), + ); + it.effect("emits exited event and reopens with clean transcript after exit", () => Effect.gen(function* () { const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager(); diff --git a/apps/server/src/terminal/Layers/Manager.ts b/apps/server/src/terminal/Layers/Manager.ts index bcb9864502..7a1e716870 100644 --- a/apps/server/src/terminal/Layers/Manager.ts +++ b/apps/server/src/terminal/Layers/Manager.ts @@ -8,7 +8,6 @@ import { } from "@t3tools/contracts"; import { makeKeyedCoalescingWorker } from "@t3tools/shared/KeyedCoalescingWorker"; import { - Data, Effect, Encoding, Equal, @@ -17,6 +16,7 @@ import { FileSystem, Layer, Option, + Schema, Scope, Semaphore, SynchronizedRef, @@ -25,6 +25,11 @@ import { import { ServerConfig } from "../../config"; import { runProbeProcess } from "../../process/runProbeProcess"; import { resolveWindowsCommandShell } from "../../process/windowsCommand"; +import { + increment, + terminalRestartsTotal, + terminalSessionsTotal, +} from "../../observability/Metrics"; import { TerminalCwdError, TerminalHistoryError, @@ -50,22 +55,28 @@ const DEFAULT_OPEN_COLS = 120; const DEFAULT_OPEN_ROWS = 30; const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]); -type TerminalSubprocessChecker = ( - terminalPid: number, -) => Effect.Effect; +class TerminalSubprocessCheckError extends Schema.TaggedErrorClass()( + "TerminalSubprocessCheckError", + { + message: Schema.String, + cause: Schema.optional(Schema.Defect), + terminalPid: Schema.Number, + command: Schema.Literals(["powershell", "pgrep", "ps"]), + }, +) {} -class TerminalSubprocessCheckError extends Data.TaggedError("TerminalSubprocessCheckError")<{ - readonly message: string; - readonly cause?: unknown; - readonly terminalPid: number; - readonly command: "powershell" | "pgrep" | "ps"; -}> {} +class TerminalProcessSignalError extends Schema.TaggedErrorClass()( + "TerminalProcessSignalError", + { + message: Schema.String, + cause: Schema.optional(Schema.Defect), + signal: Schema.Literals(["SIGTERM", "SIGKILL"]), + }, +) {} -class TerminalProcessSignalError extends Data.TaggedError("TerminalProcessSignalError")<{ - readonly message: string; - readonly cause?: unknown; - readonly signal: "SIGTERM" | "SIGKILL"; -}> {} +interface TerminalSubprocessChecker { + (terminalPid: number): Effect.Effect; +} interface ShellCandidate { shell: string; @@ -76,6 +87,7 @@ interface TerminalStartInput { threadId: string; terminalId: string; cwd: string; + worktreePath?: string | null; cols: number; rows: number; env?: Record; @@ -85,6 +97,7 @@ interface TerminalSessionState { threadId: string; terminalId: string; cwd: string; + worktreePath: string | null; status: TerminalSessionStatus; pid: number | null; history: string; @@ -139,6 +152,7 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { threadId: session.threadId, terminalId: session.terminalId, cwd: session.cwd, + worktreePath: session.worktreePath, status: session.status, pid: session.pid, history: session.history, @@ -264,9 +278,8 @@ function isRetryableShellSpawnError(error: PtySpawnError): boolean { if (current instanceof Error) { messages.push(current.message); - const cause = (current as { cause?: unknown }).cause; - if (cause) { - queue.push(cause); + if (current.cause) { + queue.push(current.cause); } continue; } @@ -654,8 +667,8 @@ const makeTerminalManager = Effect.fn("makeTerminalManager")(function* () { 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 context = yield* Effect.context(); + const runFork = Effect.runForkWith(context); const logsDir = options.logsDir; const historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT; @@ -866,7 +879,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith Effect.logWarning("failed to persist terminal history", { threadId, terminalId, - error: error instanceof Error ? error.message : String(error), + error, }), ), ); @@ -949,7 +962,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith Effect.catch((cleanupError) => Effect.logWarning("failed to remove legacy terminal history", { threadId, - error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError), + error: cleanupError, }), ), ); @@ -965,7 +978,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith Effect.logWarning("failed to delete terminal history", { threadId, terminalId, - error: error instanceof Error ? error.message : String(error), + error, }), ), ); @@ -975,7 +988,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith Effect.logWarning("failed to delete terminal history", { threadId, terminalId, - error: error instanceof Error ? error.message : String(error), + error, }), ), ); @@ -1001,7 +1014,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith Effect.catch((error) => Effect.logWarning("failed to delete terminal histories for thread", { threadId, - error: error instanceof Error ? error.message : String(error), + error, }), ), ), @@ -1292,10 +1305,17 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith eventType: "started" | "restarted", ) { yield* stopProcess(session); + yield* Effect.annotateCurrentSpan({ + "terminal.thread_id": session.threadId, + "terminal.id": session.terminalId, + "terminal.event_type": eventType, + "terminal.cwd": input.cwd, + }); yield* modifyManagerState((state) => { session.status = "starting"; session.cwd = input.cwd; + session.worktreePath = input.worktreePath ?? null; session.cols = input.cols; session.rows = input.rows; session.exitCode = null; @@ -1312,45 +1332,49 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith 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; + increment(terminalSessionsTotal, { lifecycle: eventType }).pipe( + Effect.andThen( + 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)); - }); + 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* 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), - }); - }), + yield* publishEvent({ + type: eventType, + threadId: session.threadId, + terminalId: session.terminalId, + createdAt: new Date().toISOString(), + snapshot: snapshot(session), + }); + }), + ), + ), ); if (startResult._tag === "Success") { @@ -1442,12 +1466,12 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith const terminalPid = session.pid; const hasRunningSubprocess = yield* subprocessChecker(terminalPid).pipe( Effect.map(Option.some), - Effect.catch((error) => + Effect.catch((reason) => Effect.logWarning("failed to check terminal subprocess activity", { threadId: session.threadId, terminalId: session.terminalId, terminalPid, - error: error instanceof Error ? error.message : String(error), + reason, }).pipe(Effect.as(Option.none())), ), ); @@ -1560,6 +1584,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith threadId: input.threadId, terminalId, cwd: input.cwd, + worktreePath: input.worktreePath ?? null, status: "starting", pid: null, history, @@ -1593,6 +1618,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith threadId: input.threadId, terminalId, cwd: input.cwd, + ...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}), cols, rows, ...(input.env ? { env: input.env } : {}), @@ -1612,6 +1638,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith if (liveSession.cwd !== input.cwd || runtimeEnvChanged) { yield* stopProcess(liveSession); liveSession.cwd = input.cwd; + liveSession.worktreePath = input.worktreePath ?? null; liveSession.runtimeEnv = nextRuntimeEnv; liveSession.history = ""; liveSession.pendingHistoryControlSequence = ""; @@ -1625,6 +1652,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith ); } else if (liveSession.status === "exited" || liveSession.status === "error") { liveSession.runtimeEnv = nextRuntimeEnv; + liveSession.worktreePath = input.worktreePath ?? null; liveSession.history = ""; liveSession.pendingHistoryControlSequence = ""; liveSession.pendingProcessEvents = []; @@ -1644,6 +1672,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith threadId: input.threadId, terminalId, cwd: input.cwd, + worktreePath: liveSession.worktreePath, cols: targetCols, rows: targetRows, ...(input.env ? { env: input.env } : {}), @@ -1720,6 +1749,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith withThreadLock( input.threadId, Effect.gen(function* () { + yield* increment(terminalRestartsTotal, { scope: "thread" }); const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; yield* assertValidCwd(input.cwd); @@ -1733,6 +1763,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith threadId: input.threadId, terminalId, cwd: input.cwd, + worktreePath: input.worktreePath ?? null, status: "starting", pid: null, history: "", @@ -1762,6 +1793,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith session = existingSession.value; yield* stopProcess(session); session.cwd = input.cwd; + session.worktreePath = input.worktreePath ?? null; session.runtimeEnv = normalizedRuntimeEnv(input.env); } @@ -1780,6 +1812,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith threadId: input.threadId, terminalId, cwd: input.cwd, + ...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}), cols, rows, ...(input.env ? { env: input.env } : {}), diff --git a/apps/server/src/terminal/Services/Manager.ts b/apps/server/src/terminal/Services/Manager.ts index 067cd55438..b59c4721cd 100644 --- a/apps/server/src/terminal/Services/Manager.ts +++ b/apps/server/src/terminal/Services/Manager.ts @@ -10,84 +10,59 @@ import { TerminalClearInput, TerminalCloseInput, TerminalEvent, + TerminalCwdError, + TerminalError, + TerminalHistoryError, + TerminalNotRunningError, TerminalOpenInput, TerminalResizeInput, TerminalRestartInput, TerminalSessionSnapshot, + TerminalSessionLookupError, + TerminalSessionStatus, TerminalWriteInput, } from "@t3tools/contracts"; -import { Effect, Schema, ServiceMap } from "effect"; +import { PtyProcess } from "./PTY"; +import { Effect, Context } from "effect"; -export class TerminalCwdError extends Schema.TaggedErrorClass()( - "TerminalCwdError", - { - cwd: Schema.String, - reason: Schema.Literals(["notFound", "notDirectory", "statFailed"]), - cause: Schema.optional(Schema.Defect), - }, -) { - override get message() { - if (this.reason === "notDirectory") { - return `Terminal cwd is not a directory: ${this.cwd}`; - } - if (this.reason === "notFound") { - return `Terminal cwd does not exist: ${this.cwd}`; - } - const causeMessage = - this.cause && typeof this.cause === "object" && "message" in this.cause - ? this.cause.message - : undefined; - return causeMessage - ? `Failed to access terminal cwd: ${this.cwd} (${causeMessage})` - : `Failed to access terminal cwd: ${this.cwd}`; - } -} - -export class TerminalHistoryError extends Schema.TaggedErrorClass()( - "TerminalHistoryError", - { - operation: Schema.Literals(["read", "truncate", "migrate"]), - threadId: Schema.String, - terminalId: Schema.String, - cause: Schema.optional(Schema.Defect), - }, -) { - override get message() { - return `Failed to ${this.operation} terminal history for thread: ${this.threadId}, terminal: ${this.terminalId}`; - } -} - -export class TerminalSessionLookupError extends Schema.TaggedErrorClass()( - "TerminalSessionLookupError", - { - threadId: Schema.String, - terminalId: Schema.String, - }, -) { - override get message() { - return `Unknown terminal thread: ${this.threadId}, terminal: ${this.terminalId}`; - } -} - -export class TerminalNotRunningError extends Schema.TaggedErrorClass()( - "TerminalNotRunningError", - { - threadId: Schema.String, - terminalId: Schema.String, - }, -) { - override get message() { - return `Terminal is not running for thread: ${this.threadId}, terminal: ${this.terminalId}`; - } -} - -export const TerminalError = Schema.Union([ +export { TerminalCwdError, + TerminalError, TerminalHistoryError, - TerminalSessionLookupError, TerminalNotRunningError, -]); -export type TerminalError = typeof TerminalError.Type; + TerminalSessionLookupError, +}; + +export interface TerminalSessionState { + threadId: string; + terminalId: string; + cwd: string; + worktreePath: string | null; + status: TerminalSessionStatus; + pid: number | null; + history: string; + pendingHistoryControlSequence: string; + exitCode: number | null; + exitSignal: number | null; + updatedAt: string; + cols: number; + rows: number; + process: PtyProcess | null; + unsubscribeData: (() => void) | null; + unsubscribeExit: (() => void) | null; + hasRunningSubprocess: boolean; + runtimeEnv: Record | null; +} + +export interface ShellCandidate { + shell: string; + args?: string[]; +} + +export interface TerminalStartInput extends TerminalOpenInput { + cols: number; + rows: number; +} /** * TerminalManagerShape - Service API for terminal session lifecycle operations. @@ -147,6 +122,6 @@ export interface TerminalManagerShape { /** * TerminalManager - Service tag for terminal session orchestration. */ -export class TerminalManager extends ServiceMap.Service()( +export class TerminalManager extends Context.Service()( "t3/terminal/Services/Manager/TerminalManager", ) {} diff --git a/apps/server/src/terminal/Services/PTY.ts b/apps/server/src/terminal/Services/PTY.ts index dc164b2621..091e527ef2 100644 --- a/apps/server/src/terminal/Services/PTY.ts +++ b/apps/server/src/terminal/Services/PTY.ts @@ -6,7 +6,7 @@ * * @module PtyAdapter */ -import { Effect, Schema, ServiceMap } from "effect"; +import { Effect, Schema, Context } from "effect"; /** * PtyError - Error type for PTY adapter operations. @@ -53,6 +53,6 @@ export interface PtyAdapterShape { /** * PtyAdapter - Service tag for PTY process integration. */ -export class PtyAdapter extends ServiceMap.Service()( +export class PtyAdapter extends Context.Service()( "t3/terminal/Services/PTY/PtyAdapter", ) {} diff --git a/apps/server/src/workspace/Layers/WorkspaceEntries.test.ts b/apps/server/src/workspace/Layers/WorkspaceEntries.test.ts index 1d1eb4f0e2..09f6905ce9 100644 --- a/apps/server/src/workspace/Layers/WorkspaceEntries.test.ts +++ b/apps/server/src/workspace/Layers/WorkspaceEntries.test.ts @@ -9,9 +9,11 @@ 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), + Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))), + Layer.provideMerge(WorkspacePathsLive), Layer.provideMerge(GitCoreLive), Layer.provide( ServerConfig.layerTest(process.cwd(), { @@ -127,6 +129,18 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => { }), ); + it.effect("prioritizes exact basename matches ahead of broader path matches", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-exact-ranking-" }); + yield* writeTextFile(cwd, "src/components/Composer.tsx"); + yield* writeTextFile(cwd, "docs/composer.tsx-notes.md"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "Composer.tsx", limit: 5 }); + + expect(result.entries[0]?.path).toBe("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-" }); diff --git a/apps/server/src/workspace/Layers/WorkspaceEntries.ts b/apps/server/src/workspace/Layers/WorkspaceEntries.ts index c64960593c..c4d3c3c81f 100644 --- a/apps/server/src/workspace/Layers/WorkspaceEntries.ts +++ b/apps/server/src/workspace/Layers/WorkspaceEntries.ts @@ -4,6 +4,12 @@ import type { Dirent } from "node:fs"; import { Cache, Duration, Effect, Exit, Layer, Option, Path } from "effect"; import { type ProjectEntry } from "@t3tools/contracts"; +import { + insertRankedSearchResult, + normalizeSearchQuery, + scoreQueryMatch, + type RankedSearchResult, +} from "@t3tools/shared/searchRanking"; import { GitCore } from "../../git/Services/GitCore.ts"; import { @@ -11,6 +17,7 @@ import { 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; @@ -39,10 +46,7 @@ interface SearchableWorkspaceEntry extends ProjectEntry { normalizedName: string; } -interface RankedWorkspaceEntry { - entry: SearchableWorkspaceEntry; - score: number; -} +type RankedWorkspaceEntry = RankedSearchResult; function toPosixPath(input: string): string { return input.replaceAll("\\", "/"); @@ -73,45 +77,6 @@ function toSearchableWorkspaceEntry(entry: ProjectEntry): SearchableWorkspaceEnt }; } -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; @@ -119,81 +84,32 @@ function scoreEntry(entry: SearchableWorkspaceEntry, query: string): number | nu 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 scores = [ + scoreQueryMatch({ + value: normalizedName, + query, + exactBase: 0, + prefixBase: 2, + includesBase: 5, + fuzzyBase: 100, + }), + scoreQueryMatch({ + value: normalizedPath, + query, + exactBase: 1, + prefixBase: 3, + boundaryBase: 4, + includesBase: 6, + fuzzyBase: 200, + boundaryMarkers: ["/"], + }), + ].filter((score): score is number => score !== null); - const nameFuzzyScore = scoreSubsequenceMatch(normalizedName, query); - if (nameFuzzyScore !== null) { - return 100 + nameFuzzyScore; + if (scores.length === 0) { + return null; } - 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(); + return Math.min(...scores); } function isPathInIgnoredDirectory(relativePath: string): boolean { @@ -213,12 +129,10 @@ function directoryAncestorsOf(relativePath: string): string[] { 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, { @@ -317,7 +231,7 @@ export const makeWorkspaceEntries = Effect.gen(function* () { new WorkspaceEntriesError({ cwd, operation: "workspaceEntries.readDirectoryEntries", - detail: processErrorDetail(cause), + detail: cause instanceof Error ? cause.message : String(cause), cause, }), }).pipe( @@ -428,24 +342,51 @@ export const makeWorkspaceEntries = Effect.gen(function* () { 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 workspaceIndexCache = yield* Cache.makeWith( + buildWorkspaceIndex, + { + capacity: WORKSPACE_CACHE_MAX_KEYS, + 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) { - return yield* Cache.invalidate(workspaceIndexCache, 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) { - return yield* Cache.get(workspaceIndexCache, input.cwd).pipe( + const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd); + return yield* Cache.get(workspaceIndexCache, normalizedCwd).pipe( Effect.map((index) => { - const normalizedQuery = normalizeQuery(input.query); + const normalizedQuery = normalizeSearchQuery(input.query, { + trimLeadingPattern: /^[@./]+/, + }); const limit = Math.max(0, Math.floor(input.limit)); const rankedEntries: RankedWorkspaceEntry[] = []; let matchedEntryCount = 0; @@ -457,11 +398,15 @@ export const makeWorkspaceEntries = Effect.gen(function* () { } matchedEntryCount += 1; - insertRankedEntry(rankedEntries, { entry, score }, limit); + insertRankedSearchResult( + rankedEntries, + { item: entry, score, tieBreaker: entry.path }, + limit, + ); } return { - entries: rankedEntries.map((candidate) => candidate.entry), + entries: rankedEntries.map((candidate) => candidate.item), truncated: index.truncated || matchedEntryCount > limit, }; }), diff --git a/apps/server/src/workspace/Layers/WorkspaceFileSystem.test.ts b/apps/server/src/workspace/Layers/WorkspaceFileSystem.test.ts index 9ea8835ba3..fcfd13c912 100644 --- a/apps/server/src/workspace/Layers/WorkspaceFileSystem.test.ts +++ b/apps/server/src/workspace/Layers/WorkspaceFileSystem.test.ts @@ -12,12 +12,13 @@ import { WorkspacePathsLive } from "./WorkspacePaths.ts"; const ProjectLayer = WorkspaceFileSystemLive.pipe( Layer.provide(WorkspacePathsLive), - Layer.provide(WorkspaceEntriesLive), + Layer.provide(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))), ); const TestLayer = Layer.empty.pipe( Layer.provideMerge(ProjectLayer), - Layer.provideMerge(WorkspaceEntriesLive), + Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))), + Layer.provideMerge(WorkspacePathsLive), Layer.provideMerge(GitCoreLive), Layer.provide( ServerConfig.layerTest(process.cwd(), { diff --git a/apps/server/src/workspace/Services/WorkspaceEntries.ts b/apps/server/src/workspace/Services/WorkspaceEntries.ts index 2841b1fe2f..c0011a9dc9 100644 --- a/apps/server/src/workspace/Services/WorkspaceEntries.ts +++ b/apps/server/src/workspace/Services/WorkspaceEntries.ts @@ -6,7 +6,7 @@ * * @module WorkspaceEntries */ -import { Schema, ServiceMap } from "effect"; +import { Schema, Context } from "effect"; import type { Effect } from "effect"; import type { ProjectSearchEntriesInput, ProjectSearchEntriesResult } from "@t3tools/contracts"; @@ -43,6 +43,6 @@ export interface WorkspaceEntriesShape { /** * WorkspaceEntries - Service tag for cached workspace entry search. */ -export class WorkspaceEntries extends ServiceMap.Service()( +export class WorkspaceEntries extends Context.Service()( "t3/workspace/Services/WorkspaceEntries", ) {} diff --git a/apps/server/src/workspace/Services/WorkspaceFileSystem.ts b/apps/server/src/workspace/Services/WorkspaceFileSystem.ts index 85db1514a3..dc6cc6e9d8 100644 --- a/apps/server/src/workspace/Services/WorkspaceFileSystem.ts +++ b/apps/server/src/workspace/Services/WorkspaceFileSystem.ts @@ -6,7 +6,7 @@ * * @module WorkspaceFileSystem */ -import { Schema, ServiceMap } from "effect"; +import { Schema, Context } from "effect"; import type { Effect } from "effect"; import type { ProjectWriteFileInput, ProjectWriteFileResult } from "@t3tools/contracts"; @@ -44,7 +44,7 @@ export interface WorkspaceFileSystemShape { /** * WorkspaceFileSystem - Service tag for workspace file operations. */ -export class WorkspaceFileSystem extends ServiceMap.Service< +export class WorkspaceFileSystem extends Context.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 index ad6d9cd3e5..86cef90735 100644 --- a/apps/server/src/workspace/Services/WorkspacePaths.ts +++ b/apps/server/src/workspace/Services/WorkspacePaths.ts @@ -6,7 +6,7 @@ * * @module WorkspacePaths */ -import { Schema, ServiceMap } from "effect"; +import { Schema, Context } from "effect"; import type { Effect } from "effect"; export class WorkspaceRootNotExistsError extends Schema.TaggedErrorClass()( @@ -80,6 +80,6 @@ export interface WorkspacePathsShape { /** * WorkspacePaths - Service tag for workspace path normalization and resolution. */ -export class WorkspacePaths extends ServiceMap.Service()( +export class WorkspacePaths extends Context.Service()( "t3/workspace/Services/WorkspacePaths", ) {} diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts new file mode 100644 index 0000000000..3ef4a86469 --- /dev/null +++ b/apps/server/src/ws.ts @@ -0,0 +1,941 @@ +import { Cause, Effect, Layer, Queue, Ref, Schema, Stream } from "effect"; +import { + type AuthAccessStreamEvent, + AuthSessionId, + CommandId, + EventId, + type OrchestrationCommand, + type GitActionProgressEvent, + type GitManagerServiceError, + OrchestrationDispatchCommandError, + type OrchestrationEvent, + OrchestrationGetFullThreadDiffError, + OrchestrationGetSnapshotError, + OrchestrationGetTurnDiffError, + ORCHESTRATION_WS_METHODS, + ProjectSearchEntriesError, + ProjectWriteFileError, + OrchestrationReplayEventsError, + ThreadId, + type TerminalEvent, + WS_METHODS, + WsRpcGroup, +} from "@t3tools/contracts"; +import { clamp } from "effect/Number"; +import { HttpRouter, HttpServerRequest } 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 { GitStatusBroadcaster } from "./git/Services/GitStatusBroadcaster"; +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 { + observeRpcEffect, + observeRpcStream, + observeRpcStreamEffect, +} from "./observability/RpcInstrumentation"; +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"; +import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner"; +import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentityResolver"; +import { ServerEnvironment } from "./environment/Services/ServerEnvironment"; +import { ServerAuth } from "./auth/Services/ServerAuth"; +import { + BootstrapCredentialService, + type BootstrapCredentialChange, +} from "./auth/Services/BootstrapCredentialService"; +import { + SessionCredentialService, + type SessionCredentialChange, +} from "./auth/Services/SessionCredentialService"; +import { respondToAuthError } from "./auth/http"; + +function toAuthAccessStreamEvent( + change: BootstrapCredentialChange | SessionCredentialChange, + revision: number, + currentSessionId: AuthSessionId, +): AuthAccessStreamEvent { + switch (change.type) { + case "pairingLinkUpserted": + return { + version: 1, + revision, + type: "pairingLinkUpserted", + payload: change.pairingLink, + }; + case "pairingLinkRemoved": + return { + version: 1, + revision, + type: "pairingLinkRemoved", + payload: { id: change.id }, + }; + case "clientUpserted": + return { + version: 1, + revision, + type: "clientUpserted", + payload: { + ...change.clientSession, + current: change.clientSession.sessionId === currentSessionId, + }, + }; + case "clientRemoved": + return { + version: 1, + revision, + type: "clientRemoved", + payload: { sessionId: change.sessionId }, + }; + } +} + +const makeWsRpcLayer = (currentSessionId: AuthSessionId) => + 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 gitStatusBroadcaster = yield* GitStatusBroadcaster; + 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 projectSetupScriptRunner = yield* ProjectSetupScriptRunner; + const repositoryIdentityResolver = yield* RepositoryIdentityResolver; + const serverEnvironment = yield* ServerEnvironment; + const serverAuth = yield* ServerAuth; + const bootstrapCredentials = yield* BootstrapCredentialService; + const sessions = yield* SessionCredentialService; + const serverCommandId = (tag: string) => + CommandId.make(`server:${tag}:${crypto.randomUUID()}`); + + const loadAuthAccessSnapshot = () => + Effect.all({ + pairingLinks: serverAuth.listPairingLinks().pipe(Effect.orDie), + clientSessions: serverAuth.listClientSessions(currentSessionId).pipe(Effect.orDie), + }); + + const appendSetupScriptActivity = (input: { + readonly threadId: ThreadId; + readonly kind: "setup-script.requested" | "setup-script.started" | "setup-script.failed"; + readonly summary: string; + readonly createdAt: string; + readonly payload: Record; + readonly tone: "info" | "error"; + }) => + orchestrationEngine.dispatch({ + type: "thread.activity.append", + commandId: serverCommandId("setup-script-activity"), + threadId: input.threadId, + activity: { + id: EventId.make(crypto.randomUUID()), + tone: input.tone, + kind: input.kind, + summary: input.summary, + payload: input.payload, + turnId: null, + createdAt: input.createdAt, + }, + createdAt: input.createdAt, + }); + + const toDispatchCommandError = (cause: unknown, fallbackMessage: string) => + Schema.is(OrchestrationDispatchCommandError)(cause) + ? cause + : new OrchestrationDispatchCommandError({ + message: cause instanceof Error ? cause.message : fallbackMessage, + cause, + }); + + const toBootstrapDispatchCommandCauseError = (cause: Cause.Cause) => { + const error = Cause.squash(cause); + return Schema.is(OrchestrationDispatchCommandError)(error) + ? error + : new OrchestrationDispatchCommandError({ + message: + error instanceof Error ? error.message : "Failed to bootstrap thread turn start.", + cause, + }); + }; + + const enrichProjectEvent = ( + event: OrchestrationEvent, + ): Effect.Effect => { + switch (event.type) { + case "project.created": + return repositoryIdentityResolver.resolve(event.payload.workspaceRoot).pipe( + Effect.map((repositoryIdentity) => ({ + ...event, + payload: { + ...event.payload, + repositoryIdentity, + }, + })), + ); + case "project.meta-updated": + return Effect.gen(function* () { + const workspaceRoot = + event.payload.workspaceRoot ?? + (yield* orchestrationEngine.getReadModel()).projects.find( + (project) => project.id === event.payload.projectId, + )?.workspaceRoot ?? + null; + if (workspaceRoot === null) { + return event; + } + + const repositoryIdentity = yield* repositoryIdentityResolver.resolve(workspaceRoot); + return { + ...event, + payload: { + ...event.payload, + repositoryIdentity, + }, + } satisfies OrchestrationEvent; + }); + default: + return Effect.succeed(event); + } + }; + + const enrichOrchestrationEvents = (events: ReadonlyArray) => + Effect.forEach(events, enrichProjectEvent, { concurrency: 4 }); + + const dispatchBootstrapTurnStart = ( + command: Extract, + ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => + Effect.gen(function* () { + const bootstrap = command.bootstrap; + const { bootstrap: _bootstrap, ...finalTurnStartCommand } = command; + let createdThread = false; + let targetProjectId = bootstrap?.createThread?.projectId; + let targetProjectCwd = bootstrap?.prepareWorktree?.projectCwd; + let targetWorktreePath = bootstrap?.createThread?.worktreePath ?? null; + + const cleanupCreatedThread = () => + createdThread + ? orchestrationEngine + .dispatch({ + type: "thread.delete", + commandId: serverCommandId("bootstrap-thread-delete"), + threadId: command.threadId, + }) + .pipe(Effect.ignoreCause({ log: true })) + : Effect.void; + + const recordSetupScriptLaunchFailure = (input: { + readonly error: unknown; + readonly requestedAt: string; + readonly worktreePath: string; + }) => { + const detail = + input.error instanceof Error ? input.error.message : "Unknown setup failure."; + return appendSetupScriptActivity({ + threadId: command.threadId, + kind: "setup-script.failed", + summary: "Setup script failed to start", + createdAt: input.requestedAt, + payload: { + detail, + worktreePath: input.worktreePath, + }, + tone: "error", + }).pipe( + Effect.ignoreCause({ log: false }), + Effect.flatMap(() => + Effect.logWarning("bootstrap turn start failed to launch setup script", { + threadId: command.threadId, + worktreePath: input.worktreePath, + detail, + }), + ), + ); + }; + + const recordSetupScriptStarted = (input: { + readonly requestedAt: string; + readonly worktreePath: string; + readonly scriptId: string; + readonly scriptName: string; + readonly terminalId: string; + }) => { + const payload = { + scriptId: input.scriptId, + scriptName: input.scriptName, + terminalId: input.terminalId, + worktreePath: input.worktreePath, + }; + return Effect.all([ + appendSetupScriptActivity({ + threadId: command.threadId, + kind: "setup-script.requested", + summary: "Starting setup script", + createdAt: input.requestedAt, + payload, + tone: "info", + }), + appendSetupScriptActivity({ + threadId: command.threadId, + kind: "setup-script.started", + summary: "Setup script started", + createdAt: new Date().toISOString(), + payload, + tone: "info", + }), + ]).pipe( + Effect.asVoid, + Effect.catch((error) => + Effect.logWarning( + "bootstrap turn start launched setup script but failed to record setup activity", + { + threadId: command.threadId, + worktreePath: input.worktreePath, + scriptId: input.scriptId, + terminalId: input.terminalId, + detail: error.message, + }, + ), + ), + ); + }; + + const runSetupProgram = () => + bootstrap?.runSetupScript && targetWorktreePath + ? (() => { + const worktreePath = targetWorktreePath; + const requestedAt = new Date().toISOString(); + return projectSetupScriptRunner + .runForThread({ + threadId: command.threadId, + ...(targetProjectId ? { projectId: targetProjectId } : {}), + ...(targetProjectCwd ? { projectCwd: targetProjectCwd } : {}), + worktreePath, + }) + .pipe( + Effect.matchEffect({ + onFailure: (error) => + recordSetupScriptLaunchFailure({ + error, + requestedAt, + worktreePath, + }), + onSuccess: (setupResult) => { + if (setupResult.status !== "started") { + return Effect.void; + } + return recordSetupScriptStarted({ + requestedAt, + worktreePath, + scriptId: setupResult.scriptId, + scriptName: setupResult.scriptName, + terminalId: setupResult.terminalId, + }); + }, + }), + ); + })() + : Effect.void; + + const bootstrapProgram = Effect.gen(function* () { + if (bootstrap?.createThread) { + yield* orchestrationEngine.dispatch({ + type: "thread.create", + commandId: serverCommandId("bootstrap-thread-create"), + threadId: command.threadId, + projectId: bootstrap.createThread.projectId, + title: bootstrap.createThread.title, + modelSelection: bootstrap.createThread.modelSelection, + runtimeMode: bootstrap.createThread.runtimeMode, + interactionMode: bootstrap.createThread.interactionMode, + branch: bootstrap.createThread.branch, + worktreePath: bootstrap.createThread.worktreePath, + createdAt: bootstrap.createThread.createdAt, + }); + createdThread = true; + } + + if (bootstrap?.prepareWorktree) { + const worktree = yield* git.createWorktree({ + cwd: bootstrap.prepareWorktree.projectCwd, + branch: bootstrap.prepareWorktree.baseBranch, + newBranch: bootstrap.prepareWorktree.branch, + path: null, + }); + targetWorktreePath = worktree.worktree.path; + yield* orchestrationEngine.dispatch({ + type: "thread.meta.update", + commandId: serverCommandId("bootstrap-thread-meta-update"), + threadId: command.threadId, + branch: worktree.worktree.branch, + worktreePath: targetWorktreePath, + }); + } + + yield* runSetupProgram(); + + return yield* orchestrationEngine.dispatch(finalTurnStartCommand); + }); + + return yield* bootstrapProgram.pipe( + Effect.catchCause((cause) => { + const dispatchError = toBootstrapDispatchCommandCauseError(cause); + if (Cause.hasInterruptsOnly(cause)) { + return Effect.fail(dispatchError); + } + return cleanupCreatedThread().pipe(Effect.flatMap(() => Effect.fail(dispatchError))); + }), + ); + }); + + const dispatchNormalizedCommand = ( + normalizedCommand: OrchestrationCommand, + ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => { + const dispatchEffect = + normalizedCommand.type === "thread.turn.start" && normalizedCommand.bootstrap + ? dispatchBootstrapTurnStart(normalizedCommand) + : orchestrationEngine + .dispatch(normalizedCommand) + .pipe( + Effect.mapError((cause) => + toDispatchCommandError(cause, "Failed to dispatch orchestration command"), + ), + ); + + return startup + .enqueueCommand(dispatchEffect) + .pipe( + Effect.mapError((cause) => + toDispatchCommandError(cause, "Failed to dispatch orchestration command"), + ), + ); + }; + + const loadServerConfig = Effect.gen(function* () { + const keybindingsConfig = yield* keybindings.loadConfigState; + const providers = yield* providerRegistry.getProviders; + const settings = yield* serverSettings.getSettings; + const environment = yield* serverEnvironment.getDescriptor; + const auth = yield* serverAuth.getDescriptor(); + + return { + environment, + auth, + cwd: config.cwd, + keybindingsConfigPath: config.keybindingsConfigPath, + keybindings: keybindingsConfig.keybindings, + issues: keybindingsConfig.issues, + providers, + availableEditors: resolveAvailableEditors(), + observability: { + logsDirectoryPath: config.logsDir, + localTracingEnabled: true, + ...(config.otlpTracesUrl !== undefined ? { otlpTracesUrl: config.otlpTracesUrl } : {}), + otlpTracesEnabled: config.otlpTracesUrl !== undefined, + ...(config.otlpMetricsUrl !== undefined + ? { otlpMetricsUrl: config.otlpMetricsUrl } + : {}), + otlpMetricsEnabled: config.otlpMetricsUrl !== undefined, + }, + settings, + }; + }); + + const refreshGitStatus = (cwd: string) => + gitStatusBroadcaster + .refreshStatus(cwd) + .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid); + + return WsRpcGroup.of({ + [ORCHESTRATION_WS_METHODS.getSnapshot]: (_input) => + observeRpcEffect( + ORCHESTRATION_WS_METHODS.getSnapshot, + projectionSnapshotQuery.getSnapshot().pipe( + Effect.mapError( + (cause) => + new OrchestrationGetSnapshotError({ + message: "Failed to load orchestration snapshot", + cause, + }), + ), + ), + { "rpc.aggregate": "orchestration" }, + ), + [ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) => + observeRpcEffect( + ORCHESTRATION_WS_METHODS.dispatchCommand, + Effect.gen(function* () { + const normalizedCommand = yield* normalizeDispatchCommand(command); + const result = yield* dispatchNormalizedCommand(normalizedCommand); + if (normalizedCommand.type === "thread.archive") { + yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe( + Effect.catch((error) => + Effect.logWarning("failed to close thread terminals after archive", { + threadId: normalizedCommand.threadId, + error: error.message, + }), + ), + ); + } + return result; + }).pipe( + Effect.mapError((cause) => + Schema.is(OrchestrationDispatchCommandError)(cause) + ? cause + : new OrchestrationDispatchCommandError({ + message: "Failed to dispatch orchestration command", + cause, + }), + ), + ), + { "rpc.aggregate": "orchestration" }, + ), + [ORCHESTRATION_WS_METHODS.getTurnDiff]: (input) => + observeRpcEffect( + ORCHESTRATION_WS_METHODS.getTurnDiff, + checkpointDiffQuery.getTurnDiff(input).pipe( + Effect.mapError( + (cause) => + new OrchestrationGetTurnDiffError({ + message: "Failed to load turn diff", + cause, + }), + ), + ), + { "rpc.aggregate": "orchestration" }, + ), + [ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) => + observeRpcEffect( + ORCHESTRATION_WS_METHODS.getFullThreadDiff, + checkpointDiffQuery.getFullThreadDiff(input).pipe( + Effect.mapError( + (cause) => + new OrchestrationGetFullThreadDiffError({ + message: "Failed to load full thread diff", + cause, + }), + ), + ), + { "rpc.aggregate": "orchestration" }, + ), + [ORCHESTRATION_WS_METHODS.replayEvents]: (input) => + observeRpcEffect( + ORCHESTRATION_WS_METHODS.replayEvents, + Stream.runCollect( + orchestrationEngine.readEvents( + clamp(input.fromSequenceExclusive, { + maximum: Number.MAX_SAFE_INTEGER, + minimum: 0, + }), + ), + ).pipe( + Effect.map((events) => Array.from(events)), + Effect.flatMap(enrichOrchestrationEvents), + Effect.mapError( + (cause) => + new OrchestrationReplayEventsError({ + message: "Failed to replay orchestration events", + cause, + }), + ), + ), + { "rpc.aggregate": "orchestration" }, + ), + [WS_METHODS.subscribeOrchestrationDomainEvents]: (_input) => + observeRpcStreamEffect( + WS_METHODS.subscribeOrchestrationDomainEvents, + 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.flatMap(enrichOrchestrationEvents), + Effect.catch(() => Effect.succeed([] as Array)), + ); + const replayStream = Stream.fromIterable(replayEvents); + const liveStream = orchestrationEngine.streamDomainEvents.pipe( + Stream.mapEffect(enrichProjectEvent), + ); + const source = Stream.merge(replayStream, liveStream); + 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)), + ); + }), + { "rpc.aggregate": "orchestration" }, + ), + [WS_METHODS.serverGetConfig]: (_input) => + observeRpcEffect(WS_METHODS.serverGetConfig, loadServerConfig, { + "rpc.aggregate": "server", + }), + [WS_METHODS.serverRefreshProviders]: (_input) => + observeRpcEffect( + WS_METHODS.serverRefreshProviders, + providerRegistry.refresh().pipe(Effect.map((providers) => ({ providers }))), + { "rpc.aggregate": "server" }, + ), + [WS_METHODS.serverUpsertKeybinding]: (rule) => + observeRpcEffect( + WS_METHODS.serverUpsertKeybinding, + Effect.gen(function* () { + const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule); + return { keybindings: keybindingsConfig, issues: [] }; + }), + { "rpc.aggregate": "server" }, + ), + [WS_METHODS.serverGetSettings]: (_input) => + observeRpcEffect(WS_METHODS.serverGetSettings, serverSettings.getSettings, { + "rpc.aggregate": "server", + }), + [WS_METHODS.serverUpdateSettings]: ({ patch }) => + observeRpcEffect(WS_METHODS.serverUpdateSettings, serverSettings.updateSettings(patch), { + "rpc.aggregate": "server", + }), + [WS_METHODS.projectsSearchEntries]: (input) => + observeRpcEffect( + WS_METHODS.projectsSearchEntries, + workspaceEntries.search(input).pipe( + Effect.mapError( + (cause) => + new ProjectSearchEntriesError({ + message: `Failed to search workspace entries: ${cause.detail}`, + cause, + }), + ), + ), + { "rpc.aggregate": "workspace" }, + ), + [WS_METHODS.projectsWriteFile]: (input) => + observeRpcEffect( + WS_METHODS.projectsWriteFile, + 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, + }); + }), + ), + { "rpc.aggregate": "workspace" }, + ), + [WS_METHODS.shellOpenInEditor]: (input) => + observeRpcEffect(WS_METHODS.shellOpenInEditor, open.openInEditor(input), { + "rpc.aggregate": "workspace", + }), + [WS_METHODS.subscribeGitStatus]: (input) => + observeRpcStream( + WS_METHODS.subscribeGitStatus, + gitStatusBroadcaster.streamStatus(input), + { + "rpc.aggregate": "git", + }, + ), + [WS_METHODS.gitRefreshStatus]: (input) => + observeRpcEffect( + WS_METHODS.gitRefreshStatus, + gitStatusBroadcaster.refreshStatus(input.cwd), + { + "rpc.aggregate": "git", + }, + ), + [WS_METHODS.gitPull]: (input) => + observeRpcEffect( + WS_METHODS.gitPull, + git.pullCurrentBranch(input.cwd).pipe( + Effect.matchCauseEffect({ + onFailure: (cause) => Effect.failCause(cause), + onSuccess: (result) => + refreshGitStatus(input.cwd).pipe(Effect.ignore({ log: true }), Effect.as(result)), + }), + ), + { "rpc.aggregate": "git" }, + ), + [WS_METHODS.gitRunStackedAction]: (input) => + observeRpcStream( + WS_METHODS.gitRunStackedAction, + 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: () => + refreshGitStatus(input.cwd).pipe( + Effect.andThen(Queue.end(queue).pipe(Effect.asVoid)), + ), + }), + ), + ), + { "rpc.aggregate": "git" }, + ), + [WS_METHODS.gitResolvePullRequest]: (input) => + observeRpcEffect(WS_METHODS.gitResolvePullRequest, gitManager.resolvePullRequest(input), { + "rpc.aggregate": "git", + }), + [WS_METHODS.gitPreparePullRequestThread]: (input) => + observeRpcEffect( + WS_METHODS.gitPreparePullRequestThread, + gitManager + .preparePullRequestThread(input) + .pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + { "rpc.aggregate": "git" }, + ), + [WS_METHODS.gitListBranches]: (input) => + observeRpcEffect(WS_METHODS.gitListBranches, git.listBranches(input), { + "rpc.aggregate": "git", + }), + [WS_METHODS.gitCreateWorktree]: (input) => + observeRpcEffect( + WS_METHODS.gitCreateWorktree, + git.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + { "rpc.aggregate": "git" }, + ), + [WS_METHODS.gitRemoveWorktree]: (input) => + observeRpcEffect( + WS_METHODS.gitRemoveWorktree, + git.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + { "rpc.aggregate": "git" }, + ), + [WS_METHODS.gitCreateBranch]: (input) => + observeRpcEffect( + WS_METHODS.gitCreateBranch, + git.createBranch(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + { "rpc.aggregate": "git" }, + ), + [WS_METHODS.gitCheckout]: (input) => + observeRpcEffect( + WS_METHODS.gitCheckout, + Effect.scoped(git.checkoutBranch(input)).pipe( + Effect.tap(() => refreshGitStatus(input.cwd)), + ), + { "rpc.aggregate": "git" }, + ), + [WS_METHODS.gitInit]: (input) => + observeRpcEffect( + WS_METHODS.gitInit, + git.initRepo(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + { "rpc.aggregate": "git" }, + ), + [WS_METHODS.terminalOpen]: (input) => + observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.terminalWrite]: (input) => + observeRpcEffect(WS_METHODS.terminalWrite, terminalManager.write(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.terminalResize]: (input) => + observeRpcEffect(WS_METHODS.terminalResize, terminalManager.resize(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.terminalClear]: (input) => + observeRpcEffect(WS_METHODS.terminalClear, terminalManager.clear(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.terminalRestart]: (input) => + observeRpcEffect(WS_METHODS.terminalRestart, terminalManager.restart(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.terminalClose]: (input) => + observeRpcEffect(WS_METHODS.terminalClose, terminalManager.close(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.subscribeTerminalEvents]: (_input) => + observeRpcStream( + WS_METHODS.subscribeTerminalEvents, + Stream.callback((queue) => + Effect.acquireRelease( + terminalManager.subscribe((event) => Queue.offer(queue, event)), + (unsubscribe) => Effect.sync(unsubscribe), + ), + ), + { "rpc.aggregate": "terminal" }, + ), + [WS_METHODS.subscribeServerConfig]: (_input) => + observeRpcStreamEffect( + WS_METHODS.subscribeServerConfig, + 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)), + ); + }), + { "rpc.aggregate": "server" }, + ), + [WS_METHODS.subscribeServerLifecycle]: (_input) => + observeRpcStreamEffect( + WS_METHODS.subscribeServerLifecycle, + 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); + }), + { "rpc.aggregate": "server" }, + ), + [WS_METHODS.subscribeAuthAccess]: (_input) => + observeRpcStreamEffect( + WS_METHODS.subscribeAuthAccess, + Effect.gen(function* () { + const initialSnapshot = yield* loadAuthAccessSnapshot(); + const revisionRef = yield* Ref.make(1); + const accessChanges: Stream.Stream< + BootstrapCredentialChange | SessionCredentialChange + > = Stream.merge(bootstrapCredentials.streamChanges, sessions.streamChanges); + + const liveEvents: Stream.Stream = accessChanges.pipe( + Stream.mapEffect((change) => + Ref.updateAndGet(revisionRef, (revision) => revision + 1).pipe( + Effect.map((revision) => + toAuthAccessStreamEvent(change, revision, currentSessionId), + ), + ), + ), + ); + + return Stream.concat( + Stream.make({ + version: 1 as const, + revision: 1, + type: "snapshot" as const, + payload: initialSnapshot, + }), + liveEvents, + ); + }), + { "rpc.aggregate": "auth" }, + ), + }); + }), + ); + +export const websocketRpcRouteLayer = Layer.unwrap( + Effect.succeed( + HttpRouter.add( + "GET", + "/ws", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const serverAuth = yield* ServerAuth; + const sessions = yield* SessionCredentialService; + const session = yield* serverAuth.authenticateWebSocketUpgrade(request); + const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, { + spanPrefix: "ws.rpc", + spanAttributes: { + "rpc.transport": "websocket", + "rpc.system": "effect-rpc", + }, + }).pipe( + Effect.provide( + makeWsRpcLayer(session.sessionId).pipe(Layer.provideMerge(RpcSerialization.layerJson)), + ), + ); + return yield* Effect.acquireUseRelease( + sessions.markConnected(session.sessionId), + () => rpcWebSocketHttpEffect, + () => sessions.markDisconnected(session.sessionId), + ); + }).pipe(Effect.catchTag("AuthError", respondToAuthError)), + ), + ), +); diff --git a/apps/server/src/wsServer.test.ts b/apps/server/src/wsServer.test.ts deleted file mode 100644 index 539e4b0d9a..0000000000 --- a/apps/server/src/wsServer.test.ts +++ /dev/null @@ -1,2086 +0,0 @@ -import * as Http from "node:http"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { - Effect, - Exit, - Fiber, - Layer, - ManagedRuntime, - 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 { DesktopLauncher, type DesktopLauncherShape } from "./process/Services/DesktopLauncher"; -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 defaultDesktopLauncherService: DesktopLauncherShape = { - getAvailableEditors: Effect.succeed([]), - openExternal: () => Effect.void, - openBrowser: (_target) => Effect.void, - openInEditor: () => Effect.void, -}; - -const defaultProviderStatuses: ReadonlyArray = [ - { - provider: "codex", - enabled: true, - installed: true, - version: "0.116.0", - status: "ready", - auth: { status: "authenticated" }, - checkedAt: "2026-01-01T00:00:00.000Z", - models: [], - }, -]; - -const defaultProviderRegistryService: ProviderRegistryShape = { - getProviders: Effect.succeed(defaultProviderStatuses), - refresh: () => Effect.succeed(defaultProviderStatuses), - streamChanges: Stream.empty, -}; - -const defaultServerSettings = DEFAULT_SERVER_SETTINGS; - -class MockTerminalManager implements TerminalManagerShape { - private readonly sessions = new Map(); - private readonly eventPubSub = Effect.runSync(PubSub.unbounded()); - private activeSubscriptions = 0; - - private key(threadId: string, terminalId: string): string { - return `${threadId}\u0000${terminalId}`; - } - - emitEvent(event: TerminalEvent): void { - Effect.runSync(PubSub.publish(this.eventPubSub, event)); - } - - subscriptionCount(): number { - return this.activeSubscriptions; - } - - readonly open: TerminalManagerShape["open"] = (input: TerminalOpenInput) => - Effect.sync(() => { - const now = new Date().toISOString(); - const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; - const snapshot: TerminalSessionSnapshot = { - threadId: input.threadId, - terminalId, - cwd: input.cwd, - status: "running", - pid: 4242, - history: "", - exitCode: null, - exitSignal: null, - updatedAt: now, - }; - this.sessions.set(this.key(input.threadId, terminalId), snapshot); - queueMicrotask(() => { - this.emitEvent({ - type: "started", - threadId: input.threadId, - terminalId, - createdAt: now, - snapshot, - }); - }); - return snapshot; - }); - - readonly write: TerminalManagerShape["write"] = (input: TerminalWriteInput) => - Effect.sync(() => { - const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; - const existing = this.sessions.get(this.key(input.threadId, terminalId)); - if (!existing) { - throw new Error(`Unknown terminal thread: ${input.threadId}`); - } - queueMicrotask(() => { - this.emitEvent({ - type: "output", - threadId: input.threadId, - terminalId, - createdAt: new Date().toISOString(), - data: input.data, - }); - }); - }); - - readonly resize: TerminalManagerShape["resize"] = (_input: TerminalResizeInput) => Effect.void; - - readonly clear: TerminalManagerShape["clear"] = (input: TerminalClearInput) => - Effect.sync(() => { - const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; - queueMicrotask(() => { - this.emitEvent({ - type: "cleared", - threadId: input.threadId, - terminalId, - createdAt: new Date().toISOString(), - }); - }); - }); - - readonly restart: TerminalManagerShape["restart"] = (input: TerminalOpenInput) => - Effect.sync(() => { - const now = new Date().toISOString(); - const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; - const snapshot: TerminalSessionSnapshot = { - threadId: input.threadId, - terminalId, - cwd: input.cwd, - status: "running", - pid: 5252, - history: "", - exitCode: null, - exitSignal: null, - updatedAt: now, - }; - this.sessions.set(this.key(input.threadId, terminalId), snapshot); - queueMicrotask(() => { - this.emitEvent({ - type: "restarted", - threadId: input.threadId, - terminalId, - createdAt: now, - snapshot, - }); - }); - return snapshot; - }); - - readonly close: TerminalManagerShape["close"] = (input: TerminalCloseInput) => - Effect.sync(() => { - if (input.terminalId) { - this.sessions.delete(this.key(input.threadId, input.terminalId)); - return; - } - for (const key of this.sessions.keys()) { - if (key.startsWith(`${input.threadId}\u0000`)) { - this.sessions.delete(key); - } - } - }); - - readonly subscribe: TerminalManagerShape["subscribe"] = (listener) => - Effect.sync(() => { - this.activeSubscriptions += 1; - const fiber = Effect.runFork( - Stream.runForEach(Stream.fromPubSub(this.eventPubSub), (event) => listener(event)), - ); - return () => { - this.activeSubscriptions -= 1; - Effect.runFork(Fiber.interrupt(fiber).pipe(Effect.ignore)); - }; - }); -} - -// --------------------------------------------------------------------------- -// WebSocket test harness -// -// Incoming messages are split into two channels: -// - pushChannel: server push envelopes (type === "push") -// - responseChannel: request/response envelopes (have an "id" field) -// -// This means sendRequest never has to skip push messages and waitForPush -// never has to skip response messages, eliminating a class of ordering bugs. -// --------------------------------------------------------------------------- - -interface MessageChannel { - queue: T[]; - waiters: Array<{ - resolve: (value: T) => void; - reject: (error: Error) => void; - timeoutId: ReturnType | null; - }>; -} - -interface SocketChannels { - push: MessageChannel; - response: MessageChannel; -} - -const channelsBySocket = new WeakMap(); - -function enqueue(channel: MessageChannel, item: T) { - const waiter = channel.waiters.shift(); - if (waiter) { - if (waiter.timeoutId !== null) clearTimeout(waiter.timeoutId); - waiter.resolve(item); - return; - } - channel.queue.push(item); -} - -function dequeue(channel: MessageChannel, timeoutMs: number): Promise { - const queued = channel.queue.shift(); - if (queued !== undefined) { - return Promise.resolve(queued); - } - - return new Promise((resolve, reject) => { - const waiter = { - resolve, - reject, - timeoutId: setTimeout(() => { - const index = channel.waiters.indexOf(waiter); - if (index >= 0) channel.waiters.splice(index, 1); - reject(new Error(`Timed out waiting for WebSocket message after ${timeoutMs}ms`)); - }, timeoutMs) as ReturnType, - }; - channel.waiters.push(waiter); - }); -} - -function isWsPushEnvelope(message: unknown): message is WsPush { - if (typeof message !== "object" || message === null) return false; - if (!("type" in message) || !("channel" in message)) return false; - return (message as { type?: unknown }).type === "push"; -} - -function asWebSocketResponse(message: unknown): WebSocketResponse | null { - if (typeof message !== "object" || message === null) return null; - if (!("id" in message)) return null; - const id = (message as { id?: unknown }).id; - if (typeof id !== "string") return null; - return message as WebSocketResponse; -} - -function connectWsOnce(port: number, token?: string): Promise { - return new Promise((resolve, reject) => { - const query = token ? `?token=${encodeURIComponent(token)}` : ""; - const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`); - const channels: SocketChannels = { - push: { queue: [], waiters: [] }, - response: { queue: [], waiters: [] }, - }; - channelsBySocket.set(ws, channels); - - ws.on("message", (raw) => { - const parsed = JSON.parse(String(raw)); - if (isWsPushEnvelope(parsed)) { - enqueue(channels.push, parsed); - } else { - const response = asWebSocketResponse(parsed); - if (response) { - enqueue(channels.response, response); - } - } - }); - - ws.once("open", () => resolve(ws)); - ws.once("error", () => reject(new Error("WebSocket connection failed"))); - }); -} - -async function connectWs(port: number, token?: string, attempts = 5): Promise { - let lastError: unknown = new Error("WebSocket connection failed"); - - for (let attempt = 0; attempt < attempts; attempt += 1) { - try { - return await connectWsOnce(port, token); - } catch (error) { - lastError = error; - if (attempt < attempts - 1) { - await new Promise((resolve) => setTimeout(resolve, 25)); - } - } - } - - throw lastError; -} - -/** Connect and wait for the server.welcome push. Returns [ws, welcomeData]. */ -async function connectAndAwaitWelcome( - port: number, - token?: string, -): Promise<[WebSocket, WsPushMessage]> { - const ws = await connectWs(port, token); - const welcome = await waitForPush(ws, WS_CHANNELS.serverWelcome); - return [ws, welcome]; -} - -async function sendRequest( - ws: WebSocket, - method: string, - params?: unknown, -): Promise { - const channels = channelsBySocket.get(ws); - if (!channels) throw new Error("WebSocket not initialized"); - - const id = crypto.randomUUID(); - const body = - method === ORCHESTRATION_WS_METHODS.dispatchCommand - ? { _tag: method, command: params } - : params && typeof params === "object" && !Array.isArray(params) - ? { _tag: method, ...(params as Record) } - : { _tag: method }; - ws.send(JSON.stringify({ id, body })); - - // Response channel only contains responses — no push filtering needed - while (true) { - const response = await dequeue(channels.response, 60_000); - if (response.id === id || response.id === "unknown") { - return response; - } - } -} - -async function waitForPush( - ws: WebSocket, - channel: C, - predicate?: (push: WsPushMessage) => boolean, - maxMessages = 120, - idleTimeoutMs = 5_000, -): Promise> { - const channels = channelsBySocket.get(ws); - if (!channels) throw new Error("WebSocket not initialized"); - - for (let remaining = maxMessages; remaining > 0; remaining--) { - const push = await dequeue(channels.push, idleTimeoutMs); - if (push.channel !== channel) continue; - const typed = push as WsPushMessage; - if (!predicate || predicate(typed)) return typed; - } - throw new Error(`Timed out waiting for push on ${channel}`); -} - -async function rewriteKeybindingsAndWaitForPush( - ws: WebSocket, - keybindingsPath: string, - contents: string, - predicate: (push: WsPushMessage) => boolean, - attempts = 3, -): Promise> { - let lastError: unknown; - for (let attempt = 0; attempt < attempts; attempt++) { - fs.writeFileSync(keybindingsPath, contents, "utf8"); - try { - return await waitForPush(ws, WS_CHANNELS.serverConfigUpdated, predicate, 20, 3_000); - } catch (error) { - lastError = error; - } - } - throw lastError; -} - -async function requestPath( - port: number, - requestPath: string, -): Promise<{ statusCode: number; body: string }> { - return new Promise((resolve, reject) => { - const req = Http.request( - { - hostname: "127.0.0.1", - port, - path: requestPath, - method: "GET", - }, - (res) => { - const chunks: Buffer[] = []; - res.on("data", (chunk) => { - chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); - }); - res.on("end", () => { - resolve({ - statusCode: res.statusCode ?? 0, - body: Buffer.concat(chunks).toString("utf8"), - }); - }); - }, - ); - req.once("error", reject); - req.end(); - }); -} - -function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsConfig { - const resolved: Array = []; - for (const binding of bindings) { - const compiled = compileResolvedKeybindingRule(binding); - if (!compiled) { - throw new Error(`Unexpected invalid keybinding in test setup: ${binding.command}`); - } - resolved.push(compiled); - } - return resolved; -} - -const DEFAULT_RESOLVED_KEYBINDINGS = compileKeybindings([...DEFAULT_KEYBINDINGS]); -const VALID_EDITOR_IDS = new Set(EDITORS.map((editor) => editor.id)); - -function expectAvailableEditors(value: unknown): void { - expect(Array.isArray(value)).toBe(true); - for (const editorId of value as unknown[]) { - expect(typeof editorId).toBe("string"); - expect(VALID_EDITOR_IDS.has(editorId as (typeof EDITORS)[number]["id"])).toBe(true); - } -} - -function ensureParentDir(filePath: string): void { - fs.mkdirSync(path.dirname(filePath), { recursive: true }); -} - -function deriveServerPathsSync(baseDir: string, devUrl: URL | undefined) { - return Effect.runSync( - deriveServerPaths(baseDir, devUrl).pipe(Effect.provide(NodeServices.layer)), - ); -} - -describe("WebSocket Server", () => { - let server: Http.Server | null = null; - let serverScope: Scope.Closeable | null = null; - let disposeServerRuntime: (() => Promise) | 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; - desktopLauncher?: DesktopLauncherShape; - 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 desktopLauncherLayer = Layer.succeed( - DesktopLauncher, - options.desktopLauncher ?? defaultDesktopLauncherService, - ); - const nodeServicesLayer = NodeServices.layer; - const serverSettingsLayer = ServerSettingsService.layerTest(options.serverSettings); - const serverSettingsRuntimeLayer = serverSettingsLayer.pipe( - Layer.provideMerge(nodeServicesLayer), - ); - const analyticsLayer = AnalyticsService.layerTest; - 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 providerRuntimeLayer = infrastructureLayer.pipe( - Layer.provideMerge(serverConfigLayer), - Layer.provideMerge(serverSettingsRuntimeLayer), - Layer.provideMerge(analyticsLayer), - ); - 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.provideMerge(providerRuntimeLayer), - Layer.provideMerge(serverConfigLayer), - Layer.provideMerge(serverSettingsRuntimeLayer), - Layer.provideMerge(analyticsLayer), - Layer.provideMerge(nodeServicesLayer), - ), - Layer.mergeAll(providerRuntimeLayer, serverSettingsRuntimeLayer, analyticsLayer), - ), - runtimeOverrides, - ); - const dependenciesLayer = Layer.empty.pipe( - Layer.provideMerge(runtimeLayer), - Layer.provideMerge(providerRegistryLayer), - Layer.provideMerge(desktopLauncherLayer), - Layer.provideMerge(serverSettingsLayer), - Layer.provideMerge(serverConfigLayer), - Layer.provideMerge(analyticsLayer), - Layer.provideMerge(nodeServicesLayer), - ); - const runtime = ManagedRuntime.make(dependenciesLayer); - try { - const httpServer = await runtime.runPromise(createServer().pipe(Scope.provide(scope))); - disposeServerRuntime = () => runtime.dispose(); - serverScope = scope; - return httpServer; - } catch (error) { - await runtime.dispose(); - await Effect.runPromise(Scope.close(scope, Exit.void)); - throw error; - } - } - - async function closeTestServer() { - if (!serverScope && !disposeServerRuntime) return; - const scope = serverScope; - const disposeRuntime = disposeServerRuntime; - serverScope = null; - disposeServerRuntime = null; - if (scope) { - await Effect.runPromise(Scope.close(scope, Exit.void)); - } - if (disposeRuntime) { - await disposeRuntime(); - } - } - - 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 desktopLauncherService: DesktopLauncherShape = { - getAvailableEditors: Effect.succeed([]), - openExternal: () => Effect.void, - openBrowser: () => Effect.void, - openInEditor: (input) => { - openCalls.push({ cwd: input.cwd, editor: input.editor }); - return Effect.void; - }, - }; - - server = await createTestServer({ - cwd: "/my/workspace", - desktopLauncher: desktopLauncherService, - }); - 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("rejects project.create when the workspace root does not exist", 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 missingWorkspaceRoot = path.join(makeTempDir("t3code-ws-project-missing-"), "missing"); - const response = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, { - type: "project.create", - commandId: "cmd-ws-project-create-missing", - projectId: "project-missing", - title: "Missing Project", - workspaceRoot: missingWorkspaceRoot, - defaultModelSelection: { - provider: "codex", - model: "gpt-5-codex", - }, - createdAt: new Date().toISOString(), - }); - - expect(response.result).toBeUndefined(); - expect(response.error?.message).toContain("Workspace root does not exist:"); - }); - - it("keeps orchestration domain push behavior for provider runtime events", async () => { - const runtimeEventPubSub = Effect.runSync(PubSub.unbounded()); - const emitRuntimeEvent = (event: ProviderRuntimeEvent) => { - Effect.runSync(PubSub.publish(runtimeEventPubSub, event)); - }; - const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never; - const providerService: ProviderServiceShape = { - startSession: (threadId) => - Effect.succeed({ - provider: "codex", - status: "ready", - runtimeMode: "full-access", - threadId, - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - }), - sendTurn: ({ threadId }) => - Effect.succeed({ - threadId, - turnId: asTurnId("provider-turn-1"), - }), - interruptTurn: () => unsupported(), - respondToRequest: () => unsupported(), - respondToUserInput: () => unsupported(), - stopSession: () => unsupported(), - listSessions: () => Effect.succeed([]), - getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }), - rollbackConversation: () => unsupported(), - streamEvents: Stream.fromPubSub(runtimeEventPubSub), - }; - const providerLayer = Layer.succeed(ProviderService, providerService); - - server = await createTestServer({ - cwd: "/test", - providerLayer, - serverSettings: { enableAssistantStreaming: true }, - }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const workspaceRoot = makeTempDir("t3code-ws-project-"); - const createdAt = new Date().toISOString(); - const createProjectResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, { - type: "project.create", - commandId: "cmd-ws-project-create", - projectId: "project-1", - title: "WS Project", - workspaceRoot, - defaultModelSelection: { - provider: "codex", - model: "gpt-5-codex", - }, - createdAt, - }); - expect(createProjectResponse.error).toBeUndefined(); - const createThreadResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, { - type: "thread.create", - commandId: "cmd-ws-runtime-thread-create", - threadId: "thread-1", - projectId: "project-1", - title: "Thread 1", - modelSelection: { - provider: "codex", - model: "gpt-5-codex", - }, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - createdAt, - }); - expect(createThreadResponse.error).toBeUndefined(); - - const startTurnResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, { - type: "thread.turn.start", - commandId: "cmd-ws-runtime-turn-start", - threadId: "thread-1", - message: { - messageId: "msg-ws-runtime-1", - role: "user", - text: "hello", - attachments: [], - }, - runtimeMode: "approval-required", - interactionMode: "default", - createdAt, - }); - expect(startTurnResponse.error).toBeUndefined(); - - await waitForPush(ws, ORCHESTRATION_WS_CHANNELS.domainEvent, (push) => { - const event = push.data as { type?: string }; - return event.type === "thread.session-set"; - }); - - emitRuntimeEvent({ - type: "content.delta", - eventId: asEventId("evt-ws-runtime-message-delta"), - provider: "codex", - threadId: asThreadId("thread-1"), - createdAt: new Date().toISOString(), - turnId: asTurnId("turn-1"), - itemId: asProviderItemId("item-1"), - payload: { - streamKind: "assistant_text", - delta: "hello from runtime", - }, - } as unknown as ProviderRuntimeEvent); - - const domainPush = await waitForPush(ws, ORCHESTRATION_WS_CHANNELS.domainEvent, (push) => { - const event = push.data as { type?: string; payload?: { messageId?: string; text?: string } }; - return ( - event.type === "thread.message-sent" && event.payload?.messageId === "assistant:item-1" - ); - }); - - const domainEvent = domainPush.data as { - type: string; - payload: { messageId: string; text: string }; - }; - expect(domainEvent.type).toBe("thread.message-sent"); - expect(domainEvent.payload.messageId).toBe("assistant:item-1"); - expect(domainEvent.payload.text).toBe("hello from runtime"); - }); - - it("routes terminal RPC methods and broadcasts terminal events", async () => { - const cwd = makeTempDir("t3code-ws-terminal-cwd-"); - const terminalManager = new MockTerminalManager(); - server = await createTestServer({ - cwd: "/test", - terminalManager, - }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const open = await sendRequest(ws, WS_METHODS.terminalOpen, { - threadId: "thread-1", - cwd, - cols: 100, - rows: 24, - }); - expect(open.error).toBeUndefined(); - expect((open.result as TerminalSessionSnapshot).threadId).toBe("thread-1"); - expect((open.result as TerminalSessionSnapshot).terminalId).toBe(DEFAULT_TERMINAL_ID); - - const write = await sendRequest(ws, WS_METHODS.terminalWrite, { - threadId: "thread-1", - data: "echo hello\n", - }); - expect(write.error).toBeUndefined(); - - const resize = await sendRequest(ws, WS_METHODS.terminalResize, { - threadId: "thread-1", - cols: 120, - rows: 30, - }); - expect(resize.error).toBeUndefined(); - - const clear = await sendRequest(ws, WS_METHODS.terminalClear, { - threadId: "thread-1", - }); - expect(clear.error).toBeUndefined(); - - const restart = await sendRequest(ws, WS_METHODS.terminalRestart, { - threadId: "thread-1", - cwd, - cols: 120, - rows: 30, - }); - expect(restart.error).toBeUndefined(); - - const close = await sendRequest(ws, WS_METHODS.terminalClose, { - threadId: "thread-1", - deleteHistory: true, - }); - expect(close.error).toBeUndefined(); - - const manualEvent: TerminalEvent = { - type: "output", - threadId: "thread-1", - terminalId: DEFAULT_TERMINAL_ID, - createdAt: new Date().toISOString(), - data: "manual test output\n", - }; - terminalManager.emitEvent(manualEvent); - - const push = await waitForPush( - ws, - WS_CHANNELS.terminalEvent, - (candidate) => (candidate.data as TerminalEvent).type === "output", - ); - expect(push.type).toBe("push"); - expect(push.channel).toBe(WS_CHANNELS.terminalEvent); - }); - - it("shuts down cleanly for injected terminal managers", async () => { - const terminalManager = new MockTerminalManager(); - server = await createTestServer({ - cwd: "/test", - terminalManager, - }); - - await closeTestServer(); - server = null; - - expect(() => - terminalManager.emitEvent({ - type: "output", - threadId: "thread-1", - terminalId: DEFAULT_TERMINAL_ID, - createdAt: new Date().toISOString(), - data: "after shutdown\n", - }), - ).not.toThrow(); - }); - - it("returns validation errors for invalid terminal open params", async () => { - server = await createTestServer({ cwd: "/test" }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const response = await sendRequest(ws, WS_METHODS.terminalOpen, { - threadId: "", - cwd: "", - cols: 1, - rows: 1, - }); - expect(response.error).toBeDefined(); - }); - - it("handles invalid JSON gracefully", async () => { - server = await createTestServer({ cwd: "/test" }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - // Send garbage - ws.send("not json at all"); - - // Error response goes to the response channel - const channels = channelsBySocket.get(ws)!; - let response: WebSocketResponse | null = null; - for (let attempt = 0; attempt < 5; attempt += 1) { - const message = await dequeue(channels.response, 5_000); - if (message.id === "unknown") { - response = message; - break; - } - if (message.error) { - response = message; - break; - } - } - expect(response).toBeDefined(); - expect(response!.error).toBeDefined(); - expect(response!.error!.message).toContain("Invalid request format"); - }); - - it("catches websocket message handler rejections and keeps the socket usable", async () => { - const unhandledRejections: unknown[] = []; - const onUnhandledRejection = (reason: unknown) => { - unhandledRejections.push(reason); - }; - process.on("unhandledRejection", onUnhandledRejection); - - const brokenDesktopLauncherService: DesktopLauncherShape = { - getAvailableEditors: Effect.succeed([]), - openExternal: () => Effect.void, - openBrowser: () => Effect.void, - openInEditor: () => - Effect.sync(() => BigInt(1)).pipe(Effect.map((result) => result as unknown as void)), - }; - - try { - server = await createTestServer({ - cwd: "/test", - desktopLauncher: brokenDesktopLauncherService, - }); - 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("invalidates workspace entry search cache after projects.writeFile", async () => { - const workspace = makeTempDir("t3code-ws-write-file-invalidate-"); - fs.mkdirSync(path.join(workspace, "src"), { recursive: true }); - fs.writeFileSync(path.join(workspace, "src", "existing.ts"), "export {};\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 beforeWrite = await sendRequest(ws, WS_METHODS.projectsSearchEntries, { - cwd: workspace, - query: "rpc", - limit: 10, - }); - expect(beforeWrite.error).toBeUndefined(); - expect(beforeWrite.result).toEqual({ - entries: [], - truncated: false, - }); - - const writeResponse = await sendRequest(ws, WS_METHODS.projectsWriteFile, { - cwd: workspace, - relativePath: "plans/effect-rpc.md", - contents: "# Plan\n", - }); - expect(writeResponse.error).toBeUndefined(); - - const afterWrite = await sendRequest(ws, WS_METHODS.projectsSearchEntries, { - cwd: workspace, - query: "rpc", - limit: 10, - }); - expect(afterWrite.error).toBeUndefined(); - expect(afterWrite.result).toEqual({ - entries: expect.arrayContaining([ - expect.objectContaining({ path: "plans/effect-rpc.md", kind: "file" }), - ]), - truncated: false, - }); - }); - - 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 be relative to the project root: ../escape.md", - ); - 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 abe7956e18..0000000000 --- a/apps/server/src/wsServer.ts +++ /dev/null @@ -1,1000 +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 { 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 { DesktopLauncher } from "./process/Services/DesktopLauncher"; -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 { makeServerPushBus } from "./wsServer/pushBus.ts"; -import { makeServerReadiness } from "./wsServer/readiness.ts"; -import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson"; -import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver.ts"; -import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries.ts"; -import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem.ts"; -import { WorkspacePaths } from "./workspace/Services/WorkspacePaths.ts"; - -/** - * 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 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 - | DesktopLauncher - | ProjectFaviconResolver - | WorkspaceEntries - | WorkspaceFileSystem - | WorkspacePaths - | 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 desktopLauncher = yield* DesktopLauncher; - const availableEditors = yield* desktopLauncher.getAvailableEditors.pipe( - Effect.mapError((cause) => new ServerLifecycleError({ operation: "availableEditors", cause })), - ); - - const runtimeServices = yield* Effect.services< - ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path - >(); - const runPromise = Effect.runPromiseWith(runtimeServices); - - const gitManager = yield* GitManager; - const terminalManager = yield* TerminalManager; - const keybindingsManager = yield* Keybindings; - const serverSettingsManager = yield* ServerSettingsService; - const providerRegistry = yield* ProviderRegistry; - const git = yield* GitCore; - const workspaceEntries = yield* WorkspaceEntries; - const workspaceFileSystem = yield* WorkspaceFileSystem; - const workspacePaths = yield* WorkspacePaths; - 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; - }) { - if (input.command.type === "project.create") { - return { - ...input.command, - workspaceRoot: yield* workspacePaths - .normalizeWorkspaceRoot(input.command.workspaceRoot) - .pipe(Effect.mapError((cause) => new RouteRequestError({ message: cause.message }))), - } satisfies OrchestrationCommand; - } - - if (input.command.type === "project.meta.update" && input.command.workspaceRoot !== undefined) { - return { - ...input.command, - workspaceRoot: yield* workspacePaths - .normalizeWorkspaceRoot(input.command.workspaceRoot) - .pipe(Effect.mapError((cause) => new RouteRequestError({ message: cause.message }))), - } satisfies OrchestrationCommand; - } - - if (input.command.type !== "thread.turn.start") { - return input.command as OrchestrationCommand; - } - const turnStartCommand = input.command; - - const normalizedAttachments = yield* Effect.forEach( - turnStartCommand.message.attachments, - (attachment) => - Effect.gen(function* () { - const parsed = parseBase64DataUrl(attachment.dataUrl); - if (!parsed || !parsed.mimeType.startsWith("image/")) { - return yield* new RouteRequestError({ - message: `Invalid image attachment payload for '${attachment.name}'.`, - }); - } - - const bytes = Buffer.from(parsed.base64, "base64"); - if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { - return yield* new RouteRequestError({ - message: `Image attachment '${attachment.name}' is empty or too large.`, - }); - } - - const attachmentId = createAttachmentId(turnStartCommand.threadId); - if (!attachmentId) { - return yield* new RouteRequestError({ - message: "Failed to create a safe attachment id.", - }); - } - - const persistedAttachment = { - type: "image" as const, - id: attachmentId, - name: attachment.name, - mimeType: parsed.mimeType.toLowerCase(), - sizeBytes: bytes.byteLength, - }; - - const attachmentPath = resolveAttachmentPath({ - attachmentsDir: serverConfig.attachmentsDir, - attachment: persistedAttachment, - }); - if (!attachmentPath) { - return yield* new RouteRequestError({ - message: `Failed to resolve persisted path for '${attachment.name}'.`, - }); - } - - yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe( - Effect.mapError( - () => - new RouteRequestError({ - message: `Failed to create attachment directory for '${attachment.name}'.`, - }), - ), - ); - yield* fileSystem.writeFile(attachmentPath, bytes).pipe( - Effect.mapError( - () => - new RouteRequestError({ - message: `Failed to persist attachment '${attachment.name}'.`, - }), - ), - ); - - return persistedAttachment; - }), - { concurrency: 1 }, - ); - - return { - ...turnStartCommand, - message: { - ...turnStartCommand.message, - attachments: normalizedAttachments, - }, - } satisfies OrchestrationCommand; - }); - - // HTTP server — serves static files or redirects to Vite dev server - const httpServer = http.createServer((req, res) => { - const respond = ( - statusCode: number, - headers: Record, - body?: string | Uint8Array, - ) => { - res.writeHead(statusCode, headers); - res.end(body); - }; - - void runPromise( - Effect.gen(function* () { - const url = new URL(req.url ?? "/", `http://localhost:${port}`); - if (yield* 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 subscriptionsScope = yield* Scope.make("sequential"); - yield* Effect.addFinalizer(() => Scope.close(subscriptionsScope, Exit.void)); - - yield* Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => - pushBus.publishAll(ORCHESTRATION_WS_CHANNELS.domainEvent, event), - ).pipe(Effect.forkIn(subscriptionsScope)); - - yield* Stream.runForEach(keybindingsManager.streamChanges, (event) => - pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, { - issues: event.issues, - }), - ).pipe(Effect.forkIn(subscriptionsScope)); - - yield* Stream.runForEach(serverSettingsManager.streamChanges, (settings) => - pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, { - issues: [], - settings, - }), - ).pipe(Effect.forkIn(subscriptionsScope)); - - yield* Stream.runForEach(providerRegistry.streamChanges, (providers) => - Effect.gen(function* () { - yield* Ref.set(providersRef, providers); - yield* pushBus.publishAll(WS_CHANNELS.serverProvidersUpdated, { - providers, - }); - }), - ).pipe(Effect.forkIn(subscriptionsScope)); - - yield* Scope.provide(orchestrationReactor.start(), subscriptionsScope); - yield* readiness.markOrchestrationSubscriptionsReady; - - let welcomeBootstrapProjectId: ProjectId | undefined; - let welcomeBootstrapThreadId: ThreadId | undefined; - - if (autoBootstrapProjectFromCwd) { - yield* Effect.gen(function* () { - const snapshot = yield* projectionReadModelQuery.getSnapshot(); - const existingProject = snapshot.projects.find( - (project) => project.workspaceRoot === cwd && project.deletedAt === null, - ); - let bootstrapProjectId: ProjectId; - let bootstrapProjectDefaultModelSelection; - - if (!existingProject) { - const createdAt = new Date().toISOString(); - bootstrapProjectId = ProjectId.makeUnsafe(crypto.randomUUID()); - const bootstrapProjectTitle = path.basename(cwd) || "project"; - bootstrapProjectDefaultModelSelection = { - provider: "codex" as const, - model: "gpt-5-codex", - }; - yield* orchestrationEngine.dispatch({ - type: "project.create", - commandId: CommandId.makeUnsafe(crypto.randomUUID()), - projectId: bootstrapProjectId, - title: bootstrapProjectTitle, - workspaceRoot: cwd, - defaultModelSelection: bootstrapProjectDefaultModelSelection, - createdAt, - }); - } else { - bootstrapProjectId = existingProject.id; - bootstrapProjectDefaultModelSelection = existingProject.defaultModelSelection ?? { - provider: "codex" as const, - model: "gpt-5-codex", - }; - } - - const existingThread = snapshot.threads.find( - (thread) => thread.projectId === bootstrapProjectId && thread.deletedAt === null, - ); - if (!existingThread) { - const createdAt = new Date().toISOString(); - const threadId = ThreadId.makeUnsafe(crypto.randomUUID()); - yield* orchestrationEngine.dispatch({ - type: "thread.create", - commandId: CommandId.makeUnsafe(crypto.randomUUID()), - threadId, - projectId: bootstrapProjectId, - title: "New thread", - modelSelection: bootstrapProjectDefaultModelSelection, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt, - }); - welcomeBootstrapProjectId = bootstrapProjectId; - welcomeBootstrapThreadId = threadId; - } else { - welcomeBootstrapProjectId = bootstrapProjectId; - welcomeBootstrapThreadId = existingThread.id; - } - }).pipe( - Effect.mapError( - (cause) => new ServerLifecycleError({ operation: "autoBootstrapProject", cause }), - ), - ); - } - - const unsubscribeTerminalEvents = yield* terminalManager.subscribe((event) => - pushBus.publishAll(WS_CHANNELS.terminalEvent, event), - ); - yield* Scope.addFinalizer(subscriptionsScope, Effect.sync(unsubscribeTerminalEvents)); - yield* readiness.markTerminalSubscriptionsReady; - - yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe( - Effect.mapError((cause) => new ServerLifecycleError({ operation: "httpServerListen", cause })), - ); - yield* readiness.markHttpListening; - - yield* Effect.addFinalizer(() => - Effect.all([closeAllClients, closeWebSocketServer.pipe(Effect.ignoreCause({ log: true }))]), - ); - - const routeRequest = Effect.fnUntraced(function* (ws: WebSocket, request: WebSocketRequest) { - switch (request.body._tag) { - case ORCHESTRATION_WS_METHODS.getSnapshot: - return yield* projectionReadModelQuery.getSnapshot(); - - case ORCHESTRATION_WS_METHODS.dispatchCommand: { - const { command } = request.body; - const normalizedCommand = yield* normalizeDispatchCommand({ command }); - return yield* orchestrationEngine.dispatch(normalizedCommand); - } - - case ORCHESTRATION_WS_METHODS.getTurnDiff: { - const body = stripRequestTag(request.body); - return yield* checkpointDiffQuery.getTurnDiff(body); - } - - case ORCHESTRATION_WS_METHODS.getFullThreadDiff: { - const body = stripRequestTag(request.body); - return yield* checkpointDiffQuery.getFullThreadDiff(body); - } - - case ORCHESTRATION_WS_METHODS.replayEvents: { - const { fromSequenceExclusive } = request.body; - return yield* Stream.runCollect( - orchestrationEngine.readEvents( - clamp(fromSequenceExclusive, { - maximum: Number.MAX_SAFE_INTEGER, - minimum: 0, - }), - ), - ).pipe(Effect.map((events) => Array.from(events))); - } - - case WS_METHODS.projectsSearchEntries: { - const body = stripRequestTag(request.body); - return yield* workspaceEntries.search(body).pipe( - Effect.mapError( - (cause) => - new RouteRequestError({ - message: `Failed to search workspace entries: ${cause.detail}`, - }), - ), - ); - } - - case WS_METHODS.projectsWriteFile: { - const body = stripRequestTag(request.body); - return yield* workspaceFileSystem.writeFile(body).pipe( - Effect.mapError( - (cause) => - new RouteRequestError({ - message: `Failed to write workspace file: ${cause.message}`, - }), - ), - ); - } - - case WS_METHODS.shellOpenInEditor: { - const body = stripRequestTag(request.body); - return yield* desktopLauncher.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/index.html b/apps/web/index.html index 0322f2d019..9f0329b602 100644 --- a/apps/web/index.html +++ b/apps/web/index.html @@ -2,9 +2,84 @@ - + + + + + + T3 Code (Alpha) -
+
+
+
+ +
+
+
diff --git a/apps/web/package.json b/apps/web/package.json index bd0fb9e0ac..a447b3e0ef 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/web", - "version": "0.0.15", + "version": "0.0.17", "private": true, "type": "module", "scripts": { @@ -19,9 +19,11 @@ "@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", + "@t3tools/client-runtime": "workspace:*", "@t3tools/contracts": "workspace:*", "@t3tools/shared": "workspace:*", "@tanstack/react-pacer": "^0.19.4", diff --git a/apps/web/src/authBootstrap.test.ts b/apps/web/src/authBootstrap.test.ts new file mode 100644 index 0000000000..f86d7c5a79 --- /dev/null +++ b/apps/web/src/authBootstrap.test.ts @@ -0,0 +1,501 @@ +import type { DesktopBridge } from "@t3tools/contracts"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +function jsonResponse(body: unknown, init?: ResponseInit) { + return new Response(JSON.stringify(body), { + headers: { + "content-type": "application/json", + }, + status: 200, + ...init, + }); +} + +type TestWindow = { + location: URL; + history: { + replaceState: (_data: unknown, _unused: string, url: string) => void; + }; + desktopBridge?: DesktopBridge; +}; + +function installTestBrowser(url: string) { + const testWindow: TestWindow = { + location: new URL(url), + history: { + replaceState: (_data, _unused, nextUrl) => { + testWindow.location = new URL(nextUrl, testWindow.location.href); + }, + }, + }; + + vi.stubGlobal("window", testWindow); + vi.stubGlobal("document", { title: "T3 Code" }); + + return testWindow; +} + +function sessionResponse(body: unknown, init?: ResponseInit) { + return jsonResponse(body, init); +} + +describe("resolveInitialServerAuthGateState", () => { + beforeEach(() => { + vi.restoreAllMocks(); + vi.useRealTimers(); + installTestBrowser("http://localhost/"); + }); + + afterEach(async () => { + const { __resetServerAuthBootstrapForTests } = await import("./environments/primary"); + __resetServerAuthBootstrapForTests(); + vi.unstubAllEnvs(); + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it("reuses an in-flight silent bootstrap attempt", async () => { + const fetchMock = vi + .fn() + .mockResolvedValueOnce( + sessionResponse({ + authenticated: false, + auth: { + policy: "desktop-managed-local", + bootstrapMethods: ["desktop-bootstrap"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }), + ) + .mockResolvedValueOnce( + jsonResponse({ + authenticated: true, + sessionMethod: "browser-session-cookie", + expiresAt: "2026-04-05T00:00:00.000Z", + }), + ) + .mockResolvedValueOnce( + sessionResponse({ + authenticated: true, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + sessionMethod: "browser-session-cookie", + expiresAt: "2026-04-05T00:00:00.000Z", + }), + ); + vi.stubGlobal("fetch", fetchMock); + + const testWindow = installTestBrowser("http://localhost/"); + testWindow.desktopBridge = { + getLocalEnvironmentBootstrap: () => ({ + label: "Local environment", + httpBaseUrl: "http://localhost:3773", + wsBaseUrl: "ws://localhost:3773", + bootstrapToken: "desktop-bootstrap-token", + }), + } as DesktopBridge; + + const { resolveInitialServerAuthGateState } = await import("./environments/primary"); + + await Promise.all([resolveInitialServerAuthGateState(), resolveInitialServerAuthGateState()]); + + expect(fetchMock).toHaveBeenCalledTimes(3); + expect(fetchMock.mock.calls[0]?.[0]).toBe("http://localhost:3773/api/auth/session"); + expect(fetchMock.mock.calls[1]?.[0]).toBe("http://localhost:3773/api/auth/bootstrap"); + expect(fetchMock.mock.calls[2]?.[0]).toBe("http://localhost:3773/api/auth/session"); + }); + + it("uses https fetch urls when the primary environment uses wss", async () => { + const fetchMock = vi.fn().mockResolvedValueOnce( + sessionResponse({ + authenticated: false, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }), + ); + vi.stubGlobal("fetch", fetchMock); + vi.stubEnv("VITE_HTTP_URL", "https://remote.example.com"); + vi.stubEnv("VITE_WS_URL", "wss://remote.example.com"); + + const { resolveInitialServerAuthGateState } = await import("./environments/primary"); + + await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ + status: "requires-auth", + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }); + + expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/api/auth/session", { + credentials: "include", + }); + }); + + it("uses the current origin as an auth proxy base for local dev environments", async () => { + const fetchMock = vi.fn().mockResolvedValueOnce( + sessionResponse({ + authenticated: false, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }), + ); + vi.stubGlobal("fetch", fetchMock); + installTestBrowser("http://localhost:5735/"); + + const { resolveInitialServerAuthGateState } = await import("./environments/primary"); + + await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ + status: "requires-auth", + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }); + + expect(fetchMock).toHaveBeenCalledWith("http://localhost:5735/api/auth/session", { + credentials: "include", + }); + }); + + it("uses the vite proxy for desktop-managed loopback auth requests during local dev", async () => { + const fetchMock = vi.fn().mockResolvedValueOnce( + sessionResponse({ + authenticated: false, + auth: { + policy: "desktop-managed-local", + bootstrapMethods: ["desktop-bootstrap"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }), + ); + vi.stubGlobal("fetch", fetchMock); + vi.stubEnv("VITE_DEV_SERVER_URL", "http://127.0.0.1:5733"); + + const testWindow = installTestBrowser("http://127.0.0.1:5733/"); + testWindow.desktopBridge = { + getLocalEnvironmentBootstrap: () => ({ + label: "Local environment", + httpBaseUrl: "http://127.0.0.1:3773", + wsBaseUrl: "ws://127.0.0.1:3773", + }), + } as DesktopBridge; + + const { resolveInitialServerAuthGateState } = await import("./environments/primary"); + + await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ + status: "requires-auth", + auth: { + policy: "desktop-managed-local", + bootstrapMethods: ["desktop-bootstrap"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }); + + expect(fetchMock).toHaveBeenCalledWith("http://127.0.0.1:5733/api/auth/session", { + credentials: "include", + }); + }); + + it("returns a requires-auth state instead of throwing when no bootstrap credential exists", async () => { + const fetchMock = vi.fn().mockResolvedValueOnce( + sessionResponse({ + authenticated: false, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }), + ); + vi.stubGlobal("fetch", fetchMock); + + const { resolveInitialServerAuthGateState } = await import("./environments/primary"); + + await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ + status: "requires-auth", + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }); + }); + + it("retries transient auth session bootstrap failures after restart", async () => { + vi.useFakeTimers(); + const fetchMock = vi + .fn() + .mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 })) + .mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 })) + .mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 })) + .mockResolvedValueOnce( + sessionResponse({ + authenticated: false, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }), + ); + vi.stubGlobal("fetch", fetchMock); + + const { resolveInitialServerAuthGateState } = await import("./environments/primary"); + + const gateStatePromise = resolveInitialServerAuthGateState(); + await vi.advanceTimersByTimeAsync(2_000); + + await expect(gateStatePromise).resolves.toEqual({ + status: "requires-auth", + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }); + expect(fetchMock).toHaveBeenCalledTimes(4); + }); + + it("takes a pairing token from the location hash and strips it immediately", async () => { + const testWindow = installTestBrowser("http://localhost/#token=pairing-token"); + const { takePairingTokenFromUrl } = await import("./environments/primary"); + + expect(takePairingTokenFromUrl()).toBe("pairing-token"); + expect(testWindow.location.hash).toBe(""); + expect(testWindow.location.searchParams.get("token")).toBeNull(); + }); + + it("accepts query-string pairing tokens as a backward-compatible fallback", async () => { + const testWindow = installTestBrowser("http://localhost/?token=pairing-token"); + const { takePairingTokenFromUrl } = await import("./environments/primary"); + + expect(takePairingTokenFromUrl()).toBe("pairing-token"); + expect(testWindow.location.searchParams.get("token")).toBeNull(); + }); + + it("allows manual token submission after the initial auth check requires pairing", async () => { + const fetchMock = vi + .fn() + .mockResolvedValueOnce( + sessionResponse({ + authenticated: false, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }), + ) + .mockResolvedValueOnce( + jsonResponse({ + authenticated: true, + sessionMethod: "browser-session-cookie", + expiresAt: "2026-04-05T00:00:00.000Z", + }), + ) + .mockResolvedValueOnce( + sessionResponse({ + authenticated: true, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + sessionMethod: "browser-session-cookie", + expiresAt: "2026-04-05T00:00:00.000Z", + }), + ); + vi.stubGlobal("fetch", fetchMock); + installTestBrowser("http://localhost/"); + + const { resolveInitialServerAuthGateState, submitServerAuthCredential } = + await import("./environments/primary"); + + await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ + status: "requires-auth", + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }); + await expect(submitServerAuthCredential("retry-token")).resolves.toBeUndefined(); + await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ + status: "authenticated", + }); + expect(fetchMock).toHaveBeenCalledTimes(3); + }); + + it("waits for the authenticated session to become observable after silent desktop bootstrap", async () => { + vi.useFakeTimers(); + const fetchMock = vi + .fn() + .mockResolvedValueOnce( + sessionResponse({ + authenticated: false, + auth: { + policy: "desktop-managed-local", + bootstrapMethods: ["desktop-bootstrap"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }), + ) + .mockResolvedValueOnce( + jsonResponse({ + authenticated: true, + sessionMethod: "browser-session-cookie", + expiresAt: "2026-04-05T00:00:00.000Z", + }), + ) + .mockResolvedValueOnce( + sessionResponse({ + authenticated: false, + auth: { + policy: "desktop-managed-local", + bootstrapMethods: ["desktop-bootstrap"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }), + ) + .mockResolvedValueOnce( + sessionResponse({ + authenticated: true, + auth: { + policy: "desktop-managed-local", + bootstrapMethods: ["desktop-bootstrap"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + sessionMethod: "browser-session-cookie", + expiresAt: "2026-04-05T00:00:00.000Z", + }), + ); + vi.stubGlobal("fetch", fetchMock); + + const testWindow = installTestBrowser("http://localhost/"); + testWindow.desktopBridge = { + getLocalEnvironmentBootstrap: () => ({ + label: "Local environment", + httpBaseUrl: "http://localhost:3773", + wsBaseUrl: "ws://localhost:3773", + bootstrapToken: "desktop-bootstrap-token", + }), + } as DesktopBridge; + + const { resolveInitialServerAuthGateState } = await import("./environments/primary"); + + const gateStatePromise = resolveInitialServerAuthGateState(); + await vi.advanceTimersByTimeAsync(100); + + await expect(gateStatePromise).resolves.toEqual({ + status: "authenticated", + }); + expect(fetchMock).toHaveBeenCalledTimes(4); + expect(fetchMock.mock.calls[2]?.[0]).toBe("http://localhost:3773/api/auth/session"); + expect(fetchMock.mock.calls[3]?.[0]).toBe("http://localhost:3773/api/auth/session"); + }); + + it("revalidates the server session state after a previous authenticated result", async () => { + const fetchMock = vi + .fn() + .mockResolvedValueOnce( + sessionResponse({ + authenticated: true, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + sessionMethod: "browser-session-cookie", + expiresAt: "2026-04-05T00:00:00.000Z", + }), + ) + .mockResolvedValueOnce( + sessionResponse({ + authenticated: false, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }), + ); + vi.stubGlobal("fetch", fetchMock); + + const { resolveInitialServerAuthGateState } = await import("./environments/primary"); + + await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ + status: "authenticated", + }); + await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ + status: "requires-auth", + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + it("creates a pairing credential from the authenticated auth endpoint", async () => { + const fetchMock = vi.fn().mockResolvedValueOnce( + jsonResponse({ + id: "pairing-link-1", + credential: "pairing-token", + label: "Julius iPhone", + expiresAt: "2026-04-05T00:00:00.000Z", + }), + ); + vi.stubGlobal("fetch", fetchMock); + + const { createServerPairingCredential } = await import("./environments/primary"); + + await expect(createServerPairingCredential("Julius iPhone")).resolves.toEqual({ + id: "pairing-link-1", + credential: "pairing-token", + label: "Julius iPhone", + expiresAt: "2026-04-05T00:00:00.000Z", + }); + expect(fetchMock).toHaveBeenCalledWith("http://localhost/api/auth/pairing-token", { + body: JSON.stringify({ label: "Julius iPhone" }), + credentials: "include", + headers: { + "content-type": "application/json", + }, + method: "POST", + }); + }); +}); diff --git a/apps/web/src/clientPersistenceStorage.test.ts b/apps/web/src/clientPersistenceStorage.test.ts new file mode 100644 index 0000000000..a74ce18ac3 --- /dev/null +++ b/apps/web/src/clientPersistenceStorage.test.ts @@ -0,0 +1,80 @@ +import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +const testEnvironmentId = EnvironmentId.make("environment-1"); + +const savedRegistryRecord: PersistedSavedEnvironmentRecord = { + environmentId: testEnvironmentId, + label: "Remote environment", + httpBaseUrl: "https://remote.example.com/", + wsBaseUrl: "wss://remote.example.com/", + createdAt: "2026-04-09T00:00:00.000Z", + lastConnectedAt: null, +}; + +function createLocalStorageStub(): Storage { + const store = new Map(); + return { + getItem: (key) => store.get(key) ?? null, + setItem: (key, value) => { + store.set(key, value); + }, + removeItem: (key) => { + store.delete(key); + }, + clear: () => { + store.clear(); + }, + key: (index) => [...store.keys()][index] ?? null, + get length() { + return store.size; + }, + }; +} + +function getTestWindow(): Window & typeof globalThis { + const localStorage = createLocalStorageStub(); + const testWindow = { + localStorage, + } as Window & typeof globalThis; + vi.stubGlobal("window", testWindow); + vi.stubGlobal("localStorage", localStorage); + return testWindow; +} + +afterEach(() => { + vi.resetModules(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe("clientPersistenceStorage", () => { + it("stores browser secrets inline with the saved environment record", async () => { + const testWindow = getTestWindow(); + const { + SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY, + readBrowserSavedEnvironmentRegistry, + readBrowserSavedEnvironmentSecret, + writeBrowserSavedEnvironmentRegistry, + writeBrowserSavedEnvironmentSecret, + } = await import("./clientPersistenceStorage"); + + writeBrowserSavedEnvironmentRegistry([savedRegistryRecord]); + expect(writeBrowserSavedEnvironmentSecret(testEnvironmentId, "bearer-token")).toBe(true); + writeBrowserSavedEnvironmentRegistry([savedRegistryRecord]); + + expect(readBrowserSavedEnvironmentRegistry()).toEqual([savedRegistryRecord]); + expect(readBrowserSavedEnvironmentSecret(testEnvironmentId)).toBe("bearer-token"); + expect( + JSON.parse(testWindow.localStorage.getItem(SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY)!), + ).toEqual({ + version: 1, + records: [ + { + ...savedRegistryRecord, + bearerToken: "bearer-token", + }, + ], + }); + }); +}); diff --git a/apps/web/src/clientPersistenceStorage.ts b/apps/web/src/clientPersistenceStorage.ts new file mode 100644 index 0000000000..70f51d5c30 --- /dev/null +++ b/apps/web/src/clientPersistenceStorage.ts @@ -0,0 +1,194 @@ +import { + ClientSettingsSchema, + EnvironmentId, + type ClientSettings, + type EnvironmentId as EnvironmentIdValue, + type PersistedSavedEnvironmentRecord, +} from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; + +import { getLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorage"; + +export const CLIENT_SETTINGS_STORAGE_KEY = "t3code:client-settings:v1"; +export const SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY = "t3code:saved-environment-registry:v1"; + +const BrowserSavedEnvironmentRecordSchema = Schema.Struct({ + environmentId: EnvironmentId, + label: Schema.String, + httpBaseUrl: Schema.String, + wsBaseUrl: Schema.String, + createdAt: Schema.String, + lastConnectedAt: Schema.NullOr(Schema.String), + bearerToken: Schema.optionalKey(Schema.String), +}); +type BrowserSavedEnvironmentRecord = typeof BrowserSavedEnvironmentRecordSchema.Type; + +const BrowserSavedEnvironmentRegistryDocumentSchema = Schema.Struct({ + version: Schema.optionalKey(Schema.Number), + records: Schema.optionalKey(Schema.Array(BrowserSavedEnvironmentRecordSchema)), +}); +type BrowserSavedEnvironmentRegistryDocument = + typeof BrowserSavedEnvironmentRegistryDocumentSchema.Type; + +function hasWindow(): boolean { + return typeof window !== "undefined"; +} + +function toPersistedSavedEnvironmentRecord( + record: PersistedSavedEnvironmentRecord, +): PersistedSavedEnvironmentRecord { + return { + environmentId: record.environmentId, + label: record.label, + httpBaseUrl: record.httpBaseUrl, + wsBaseUrl: record.wsBaseUrl, + createdAt: record.createdAt, + lastConnectedAt: record.lastConnectedAt, + }; +} + +export function readBrowserClientSettings(): ClientSettings | null { + if (!hasWindow()) { + return null; + } + + try { + return getLocalStorageItem(CLIENT_SETTINGS_STORAGE_KEY, ClientSettingsSchema); + } catch { + return null; + } +} + +export function writeBrowserClientSettings(settings: ClientSettings): void { + if (!hasWindow()) { + return; + } + + setLocalStorageItem(CLIENT_SETTINGS_STORAGE_KEY, settings, ClientSettingsSchema); +} + +function readBrowserSavedEnvironmentRegistryDocument(): BrowserSavedEnvironmentRegistryDocument { + if (!hasWindow()) { + return {}; + } + + try { + const parsed = getLocalStorageItem( + SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY, + BrowserSavedEnvironmentRegistryDocumentSchema, + ); + return parsed ?? {}; + } catch { + return {}; + } +} + +function writeBrowserSavedEnvironmentRegistryDocument( + document: BrowserSavedEnvironmentRegistryDocument, +): void { + if (!hasWindow()) { + return; + } + + setLocalStorageItem( + SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY, + document, + BrowserSavedEnvironmentRegistryDocumentSchema, + ); +} + +function readBrowserSavedEnvironmentRecordsWithSecrets(): ReadonlyArray { + return readBrowserSavedEnvironmentRegistryDocument().records ?? []; +} + +function writeBrowserSavedEnvironmentRecords( + records: ReadonlyArray, +): void { + writeBrowserSavedEnvironmentRegistryDocument({ + version: 1, + records, + }); +} + +export function readBrowserSavedEnvironmentRegistry(): ReadonlyArray { + return readBrowserSavedEnvironmentRecordsWithSecrets().map((record) => + toPersistedSavedEnvironmentRecord(record), + ); +} + +export function writeBrowserSavedEnvironmentRegistry( + records: ReadonlyArray, +): void { + const existing = new Map( + readBrowserSavedEnvironmentRecordsWithSecrets().map( + (record) => [record.environmentId, record] as const, + ), + ); + writeBrowserSavedEnvironmentRecords( + records.map((record) => { + const bearerToken = existing.get(record.environmentId)?.bearerToken; + return bearerToken + ? { + environmentId: record.environmentId, + label: record.label, + httpBaseUrl: record.httpBaseUrl, + wsBaseUrl: record.wsBaseUrl, + createdAt: record.createdAt, + lastConnectedAt: record.lastConnectedAt, + bearerToken, + } + : toPersistedSavedEnvironmentRecord(record); + }), + ); +} + +export function readBrowserSavedEnvironmentSecret( + environmentId: EnvironmentIdValue, +): string | null { + return ( + readBrowserSavedEnvironmentRecordsWithSecrets().find( + (record) => record.environmentId === environmentId, + )?.bearerToken ?? null + ); +} + +export function writeBrowserSavedEnvironmentSecret( + environmentId: EnvironmentIdValue, + secret: string, +): boolean { + const document = readBrowserSavedEnvironmentRegistryDocument(); + const records = document.records ?? []; + let found = false; + writeBrowserSavedEnvironmentRegistryDocument({ + version: document.version ?? 1, + records: records.map((record) => { + if (record.environmentId !== environmentId) { + return record; + } + found = true; + return { + environmentId: record.environmentId, + label: record.label, + httpBaseUrl: record.httpBaseUrl, + wsBaseUrl: record.wsBaseUrl, + createdAt: record.createdAt, + lastConnectedAt: record.lastConnectedAt, + bearerToken: secret, + } satisfies BrowserSavedEnvironmentRecord; + }), + }); + return found; +} + +export function removeBrowserSavedEnvironmentSecret(environmentId: EnvironmentIdValue): void { + const document = readBrowserSavedEnvironmentRegistryDocument(); + writeBrowserSavedEnvironmentRegistryDocument({ + version: document.version ?? 1, + records: (document.records ?? []).map((record) => { + if (record.environmentId !== environmentId) { + return record; + } + return toPersistedSavedEnvironmentRecord(record); + }), + }); +} diff --git a/apps/web/src/components/BranchToolbar.logic.test.ts b/apps/web/src/components/BranchToolbar.logic.test.ts index 2f66e063ad..faf21d636c 100644 --- a/apps/web/src/components/BranchToolbar.logic.test.ts +++ b/apps/web/src/components/BranchToolbar.logic.test.ts @@ -1,14 +1,21 @@ -import type { GitBranch } from "@t3tools/contracts"; +import { EnvironmentId, type GitBranch } from "@t3tools/contracts"; import { describe, expect, it } from "vitest"; import { dedupeRemoteBranchesWithLocalMatches, deriveLocalBranchNameFromRemoteRef, + resolveEnvironmentOptionLabel, resolveBranchSelectionTarget, + resolveCurrentWorkspaceLabel, resolveDraftEnvModeAfterBranchChange, + resolveEffectiveEnvMode, + resolveEnvModeLabel, resolveBranchToolbarValue, shouldIncludeBranchPickerItem, } from "./BranchToolbar.logic"; +const localEnvironmentId = EnvironmentId.make("environment-local"); +const remoteEnvironmentId = EnvironmentId.make("environment-remote"); + describe("resolveDraftEnvModeAfterBranchChange", () => { it("switches to local mode when returning from an existing worktree to the main worktree", () => { expect( @@ -76,6 +83,80 @@ describe("resolveBranchToolbarValue", () => { }); }); +describe("resolveEnvironmentOptionLabel", () => { + it("prefers the primary environment's machine label", () => { + expect( + resolveEnvironmentOptionLabel({ + isPrimary: true, + environmentId: localEnvironmentId, + runtimeLabel: "Julius's Mac mini", + savedLabel: "Local environment", + }), + ).toBe("Julius's Mac mini"); + }); + + it("falls back to 'This device' for generic primary labels", () => { + expect( + resolveEnvironmentOptionLabel({ + isPrimary: true, + environmentId: localEnvironmentId, + runtimeLabel: "Local environment", + savedLabel: "Local", + }), + ).toBe("This device"); + }); + + it("keeps configured labels for non-primary environments", () => { + expect( + resolveEnvironmentOptionLabel({ + isPrimary: false, + environmentId: remoteEnvironmentId, + runtimeLabel: null, + savedLabel: "Build box", + }), + ).toBe("Build box"); + }); +}); + +describe("resolveEffectiveEnvMode", () => { + it("treats draft threads already attached to a worktree as current-checkout mode", () => { + expect( + resolveEffectiveEnvMode({ + activeWorktreePath: "/repo/.t3/worktrees/feature-a", + hasServerThread: false, + draftThreadEnvMode: "worktree", + }), + ).toBe("local"); + }); + + it("keeps explicit new-worktree mode for draft threads without a worktree path", () => { + expect( + resolveEffectiveEnvMode({ + activeWorktreePath: null, + hasServerThread: false, + draftThreadEnvMode: "worktree", + }), + ).toBe("worktree"); + }); +}); + +describe("resolveEnvModeLabel", () => { + it("uses explicit workspace labels", () => { + expect(resolveEnvModeLabel("local")).toBe("Current checkout"); + expect(resolveEnvModeLabel("worktree")).toBe("New worktree"); + }); +}); + +describe("resolveCurrentWorkspaceLabel", () => { + it("describes the main repo checkout when no worktree path is active", () => { + expect(resolveCurrentWorkspaceLabel(null)).toBe("Current checkout"); + }); + + it("describes the active checkout as a worktree when one is attached", () => { + expect(resolveCurrentWorkspaceLabel("/repo/.t3/worktrees/feature-a")).toBe("Current worktree"); + }); +}); + describe("deriveLocalBranchNameFromRemoteRef", () => { it("strips the remote prefix from a remote ref", () => { expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo"); diff --git a/apps/web/src/components/BranchToolbar.logic.ts b/apps/web/src/components/BranchToolbar.logic.ts index 99928441c7..54ec4370f4 100644 --- a/apps/web/src/components/BranchToolbar.logic.ts +++ b/apps/web/src/components/BranchToolbar.logic.ts @@ -1,18 +1,68 @@ -import type { GitBranch } from "@t3tools/contracts"; +import type { EnvironmentId, GitBranch, ProjectId } from "@t3tools/contracts"; import { Schema } from "effect"; +export { + dedupeRemoteBranchesWithLocalMatches, + deriveLocalBranchNameFromRemoteRef, +} from "@t3tools/shared/git"; + +export interface EnvironmentOption { + environmentId: EnvironmentId; + projectId: ProjectId; + label: string; + isPrimary: boolean; +} export const EnvMode = Schema.Literals(["local", "worktree"]); export type EnvMode = typeof EnvMode.Type; +const GENERIC_LOCAL_ENVIRONMENT_LABELS = new Set(["local", "local environment"]); + +function normalizeDisplayLabel(value: string | null | undefined): string | null { + const trimmed = value?.trim(); + return trimmed && trimmed.length > 0 ? trimmed : null; +} + +export function resolveEnvironmentOptionLabel(input: { + isPrimary: boolean; + environmentId: EnvironmentId; + runtimeLabel?: string | null; + savedLabel?: string | null; +}): string { + const runtimeLabel = normalizeDisplayLabel(input.runtimeLabel); + const savedLabel = normalizeDisplayLabel(input.savedLabel); + + if (input.isPrimary) { + const preferredLocalLabel = [runtimeLabel, savedLabel].find((label) => { + if (!label) return false; + return !GENERIC_LOCAL_ENVIRONMENT_LABELS.has(label.toLowerCase()); + }); + return preferredLocalLabel ?? "This device"; + } + + return runtimeLabel ?? savedLabel ?? input.environmentId; +} + +export function resolveEnvModeLabel(mode: EnvMode): string { + return mode === "worktree" ? "New worktree" : "Current checkout"; +} + +export function resolveCurrentWorkspaceLabel(activeWorktreePath: string | null): string { + return activeWorktreePath ? "Current worktree" : resolveEnvModeLabel("local"); +} + export function resolveEffectiveEnvMode(input: { activeWorktreePath: string | null; hasServerThread: boolean; draftThreadEnvMode: EnvMode | undefined; }): EnvMode { const { activeWorktreePath, hasServerThread, draftThreadEnvMode } = input; - return activeWorktreePath || (!hasServerThread && draftThreadEnvMode === "worktree") - ? "worktree" - : "local"; + if (!hasServerThread) { + if (activeWorktreePath) { + return "local"; + } + return draftThreadEnvMode === "worktree" ? "worktree" : "local"; + } + return activeWorktreePath ? "worktree" : "local"; } export function resolveDraftEnvModeAfterBranchChange(input: { @@ -43,58 +93,6 @@ export function resolveBranchToolbarValue(input: { return currentGitBranch ?? activeThreadBranch; } -export function deriveLocalBranchNameFromRemoteRef(branchName: string): string { - const firstSeparatorIndex = branchName.indexOf("/"); - if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) { - return branchName; - } - return branchName.slice(firstSeparatorIndex + 1); -} - -function deriveLocalBranchNameCandidatesFromRemoteRef( - branchName: string, - remoteName?: string, -): ReadonlyArray { - const candidates = new Set(); - const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName); - if (firstSlashCandidate.length > 0) { - candidates.add(firstSlashCandidate); - } - - if (remoteName) { - const remotePrefix = `${remoteName}/`; - if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) { - candidates.add(branchName.slice(remotePrefix.length)); - } - } - - return [...candidates]; -} - -export function dedupeRemoteBranchesWithLocalMatches( - branches: ReadonlyArray, -): ReadonlyArray { - const localBranchNames = new Set( - branches.filter((branch) => !branch.isRemote).map((branch) => branch.name), - ); - - return branches.filter((branch) => { - if (!branch.isRemote) { - return true; - } - - if (branch.remoteName !== "origin") { - return true; - } - - const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef( - branch.name, - branch.remoteName, - ); - return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate)); - }); -} - export function resolveBranchSelectionTarget(input: { activeProjectCwd: string; activeWorktreePath: string | null; diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx index 79c453c0f5..e91266d65f 100644 --- a/apps/web/src/components/BranchToolbar.tsx +++ b/apps/web/src/components/BranchToolbar.tsx @@ -1,171 +1,106 @@ -import type { ThreadId } from "@t3tools/contracts"; -import { FolderIcon, GitForkIcon } from "lucide-react"; -import { useCallback } from "react"; +import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime"; +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { memo, useMemo } from "react"; -import { newCommandId } from "../lib/utils"; -import { readNativeApi } from "../nativeApi"; -import { useComposerDraftStore } from "../composerDraftStore"; +import { useComposerDraftStore, type DraftId } from "../composerDraftStore"; import { useStore } from "../store"; +import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors"; import { - EnvMode, - resolveDraftEnvModeAfterBranchChange, + type EnvMode, + type EnvironmentOption, resolveEffectiveEnvMode, } from "./BranchToolbar.logic"; import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector"; -import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select"; - -const envModeItems = [ - { value: "local", label: "Local" }, - { value: "worktree", label: "New worktree" }, -] as const; +import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector"; +import { BranchToolbarEnvModeSelector } from "./BranchToolbarEnvModeSelector"; +import { Separator } from "./ui/separator"; interface BranchToolbarProps { + environmentId: EnvironmentId; threadId: ThreadId; + draftId?: DraftId; onEnvModeChange: (mode: EnvMode) => void; envLocked: boolean; onCheckoutPullRequestRequest?: (reference: string) => void; onComposerFocusRequest?: () => void; + availableEnvironments?: readonly EnvironmentOption[]; + onEnvironmentChange?: (environmentId: EnvironmentId) => void; } -export default function BranchToolbar({ +export const BranchToolbar = memo(function BranchToolbar({ + environmentId, threadId, + draftId, onEnvModeChange, envLocked, onCheckoutPullRequestRequest, onComposerFocusRequest, + availableEnvironments, + onEnvironmentChange, }: BranchToolbarProps) { - const threads = useStore((store) => store.threads); - const projects = useStore((store) => store.projects); - const setThreadBranchAction = useStore((store) => store.setThreadBranch); - const draftThread = useComposerDraftStore((store) => store.getDraftThread(threadId)); - const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); - - const serverThread = threads.find((thread) => thread.id === threadId); - const activeProjectId = serverThread?.projectId ?? draftThread?.projectId ?? null; - const activeProject = projects.find((project) => project.id === activeProjectId); - const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined); - const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null; + const threadRef = useMemo( + () => scopeThreadRef(environmentId, threadId), + [environmentId, threadId], + ); + const serverThreadSelector = useMemo(() => createThreadSelectorByRef(threadRef), [threadRef]); + const serverThread = useStore(serverThreadSelector); + const draftThread = useComposerDraftStore((store) => + draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef), + ); + const activeProjectRef = serverThread + ? scopeProjectRef(serverThread.environmentId, serverThread.projectId) + : draftThread + ? scopeProjectRef(draftThread.environmentId, draftThread.projectId) + : null; + const activeProjectSelector = useMemo( + () => createProjectSelectorByRef(activeProjectRef), + [activeProjectRef], + ); + const activeProject = useStore(activeProjectSelector); + const hasActiveThread = serverThread !== undefined || draftThread !== null; const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null; - const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null; - const hasServerThread = serverThread !== undefined; const effectiveEnvMode = resolveEffectiveEnvMode({ activeWorktreePath, - hasServerThread, + hasServerThread: serverThread !== undefined, draftThreadEnvMode: draftThread?.envMode, }); + const envModeLocked = envLocked || (serverThread !== undefined && activeWorktreePath !== null); - const setThreadBranch = useCallback( - (branch: string | null, worktreePath: string | null) => { - if (!activeThreadId) return; - const api = readNativeApi(); - // If the effective cwd is about to change, stop the running session so the - // next message creates a new one with the correct cwd. - if (serverThread?.session && worktreePath !== activeWorktreePath && api) { - void api.orchestration - .dispatchCommand({ - type: "thread.session.stop", - commandId: newCommandId(), - threadId: activeThreadId, - createdAt: new Date().toISOString(), - }) - .catch(() => undefined); - } - if (api && hasServerThread) { - void api.orchestration.dispatchCommand({ - type: "thread.meta.update", - commandId: newCommandId(), - threadId: activeThreadId, - branch, - worktreePath, - }); - } - if (hasServerThread) { - setThreadBranchAction(activeThreadId, branch, worktreePath); - return; - } - const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({ - nextWorktreePath: worktreePath, - currentWorktreePath: activeWorktreePath, - effectiveEnvMode, - }); - setDraftThreadContext(threadId, { - branch, - worktreePath, - envMode: nextDraftEnvMode, - }); - }, - [ - activeThreadId, - serverThread?.session, - activeWorktreePath, - hasServerThread, - setThreadBranchAction, - setDraftThreadContext, - threadId, - effectiveEnvMode, - ], - ); + const showEnvironmentPicker = + availableEnvironments && availableEnvironments.length > 1 && onEnvironmentChange; - if (!activeThreadId || !activeProject) return null; + if (!hasActiveThread || !activeProject) return null; return ( -
- {envLocked || activeWorktreePath ? ( - - {activeWorktreePath ? ( - <> - - Worktree - - ) : ( - <> - - Local - - )} - - ) : ( - - )} +
+
+ {showEnvironmentPicker && ( + <> + + + + )} + +
); -} +}); diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index c1a43adc90..76f64d93fe 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -1,5 +1,6 @@ -import type { GitBranch } from "@t3tools/contracts"; -import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime"; +import type { EnvironmentId, GitBranch, ThreadId } from "@t3tools/contracts"; +import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query"; import { useVirtualizer } from "@tanstack/react-virtual"; import { ChevronDownIcon } from "lucide-react"; import { @@ -14,20 +15,20 @@ import { useTransition, } from "react"; -import { - gitBranchesQueryOptions, - gitQueryKeys, - gitStatusQueryOptions, - invalidateGitQueries, -} from "../lib/gitReactQuery"; -import { readNativeApi } from "../nativeApi"; +import { useComposerDraftStore, type DraftId } from "../composerDraftStore"; +import { readEnvironmentApi } from "../environmentApi"; +import { gitBranchSearchInfiniteQueryOptions, gitQueryKeys } from "../lib/gitReactQuery"; +import { useGitStatus } from "../lib/gitStatusState"; +import { newCommandId } from "../lib/utils"; import { parsePullRequestReference } from "../pullRequestReference"; +import { useStore } from "../store"; +import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors"; import { - dedupeRemoteBranchesWithLocalMatches, deriveLocalBranchNameFromRemoteRef, - EnvMode, resolveBranchSelectionTarget, resolveBranchToolbarValue, + resolveDraftEnvModeAfterBranchChange, + resolveEffectiveEnvMode, shouldIncludeBranchPickerItem, } from "./BranchToolbar.logic"; import { Button } from "./ui/button"; @@ -38,18 +39,16 @@ import { ComboboxItem, ComboboxList, ComboboxPopup, + ComboboxStatus, ComboboxTrigger, } from "./ui/combobox"; import { toastManager } from "./ui/toast"; interface BranchToolbarBranchSelectorProps { - activeProjectCwd: string; - activeThreadBranch: string | null; - activeWorktreePath: string | null; - branchCwd: string | null; - effectiveEnvMode: EnvMode; + environmentId: EnvironmentId; + threadId: ThreadId; + draftId?: DraftId; envLocked: boolean; - onSetThreadBranch: (branch: string | null, worktreePath: string | null) => void; onCheckoutPullRequestRequest?: (reference: string) => void; onComposerFocusRequest?: () => void; } @@ -60,7 +59,7 @@ function toBranchActionErrorMessage(error: unknown): string { function getBranchTriggerLabel(input: { activeWorktreePath: string | null; - effectiveEnvMode: EnvMode; + effectiveEnvMode: "local" | "worktree"; resolvedActiveBranch: string | null; }): string { const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch } = input; @@ -74,26 +73,144 @@ function getBranchTriggerLabel(input: { } export function BranchToolbarBranchSelector({ - activeProjectCwd, - activeThreadBranch, - activeWorktreePath, - branchCwd, - effectiveEnvMode, + environmentId, + threadId, + draftId, envLocked, - onSetThreadBranch, onCheckoutPullRequestRequest, onComposerFocusRequest, }: BranchToolbarBranchSelectorProps) { + // --------------------------------------------------------------------------- + // Thread / project state (pushed down from parent to colocate with mutation) + // --------------------------------------------------------------------------- + const threadRef = useMemo( + () => scopeThreadRef(environmentId, threadId), + [environmentId, threadId], + ); + const serverThreadSelector = useMemo(() => createThreadSelectorByRef(threadRef), [threadRef]); + const serverThread = useStore(serverThreadSelector); + const serverSession = serverThread?.session ?? null; + const setThreadBranchAction = useStore((store) => store.setThreadBranch); + const draftThread = useComposerDraftStore((store) => + draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef), + ); + const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); + + const activeProjectRef = serverThread + ? scopeProjectRef(serverThread.environmentId, serverThread.projectId) + : draftThread + ? scopeProjectRef(draftThread.environmentId, draftThread.projectId) + : null; + const activeProjectSelector = useMemo( + () => createProjectSelectorByRef(activeProjectRef), + [activeProjectRef], + ); + const activeProject = useStore(activeProjectSelector); + + const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined); + const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null; + const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null; + const activeProjectCwd = activeProject?.cwd ?? null; + const branchCwd = activeWorktreePath ?? activeProjectCwd; + const hasServerThread = serverThread !== undefined; + const effectiveEnvMode = resolveEffectiveEnvMode({ + activeWorktreePath, + hasServerThread, + draftThreadEnvMode: draftThread?.envMode, + }); + + // --------------------------------------------------------------------------- + // Thread branch mutation (colocated — only this component calls it) + // --------------------------------------------------------------------------- + const setThreadBranch = useCallback( + (branch: string | null, worktreePath: string | null) => { + if (!activeThreadId || !activeProject) return; + const api = readEnvironmentApi(environmentId); + if (serverSession && worktreePath !== activeWorktreePath && api) { + void api.orchestration + .dispatchCommand({ + type: "thread.session.stop", + commandId: newCommandId(), + threadId: activeThreadId, + createdAt: new Date().toISOString(), + }) + .catch(() => undefined); + } + if (api && hasServerThread) { + void api.orchestration.dispatchCommand({ + type: "thread.meta.update", + commandId: newCommandId(), + threadId: activeThreadId, + branch, + worktreePath, + }); + } + if (hasServerThread) { + setThreadBranchAction(threadRef, branch, worktreePath); + return; + } + const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({ + nextWorktreePath: worktreePath, + currentWorktreePath: activeWorktreePath, + effectiveEnvMode, + }); + setDraftThreadContext(draftId ?? threadRef, { + branch, + worktreePath, + envMode: nextDraftEnvMode, + projectRef: scopeProjectRef(environmentId, activeProject.id), + }); + }, + [ + activeThreadId, + activeProject, + serverSession, + activeWorktreePath, + hasServerThread, + setThreadBranchAction, + setDraftThreadContext, + draftId, + threadRef, + environmentId, + effectiveEnvMode, + ], + ); + + // --------------------------------------------------------------------------- + // Git branch queries + // --------------------------------------------------------------------------- const queryClient = useQueryClient(); const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false); const [branchQuery, setBranchQuery] = useState(""); const deferredBranchQuery = useDeferredValue(branchQuery); - const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd)); - const branchStatusQuery = useQuery(gitStatusQueryOptions(branchCwd)); + const branchStatusQuery = useGitStatus({ environmentId, cwd: branchCwd }); + const trimmedBranchQuery = branchQuery.trim(); + const deferredTrimmedBranchQuery = deferredBranchQuery.trim(); + + useEffect(() => { + if (!branchCwd) return; + void queryClient.prefetchInfiniteQuery( + gitBranchSearchInfiniteQueryOptions({ environmentId, cwd: branchCwd, query: "" }), + ); + }, [branchCwd, environmentId, queryClient]); + + const { + data: branchesSearchData, + fetchNextPage, + hasNextPage, + isFetchingNextPage, + isPending: isBranchesSearchPending, + } = useInfiniteQuery( + gitBranchSearchInfiniteQueryOptions({ + environmentId, + cwd: branchCwd, + query: deferredTrimmedBranchQuery, + }), + ); const branches = useMemo( - () => dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []), - [branchesQuery.data?.branches], + () => branchesSearchData?.pages.flatMap((page) => page.branches) ?? [], + [branchesSearchData?.pages], ); const currentGitBranch = branchStatusQuery.data?.branch ?? branches.find((branch) => branch.current)?.name ?? null; @@ -108,8 +225,6 @@ export function BranchToolbarBranchSelector({ () => new Map(branches.map((branch) => [branch.name, branch] as const)), [branches], ); - const trimmedBranchQuery = branchQuery.trim(); - const deferredTrimmedBranchQuery = deferredBranchQuery.trim(); const normalizedDeferredBranchQuery = deferredTrimmedBranchQuery.toLowerCase(); const prReference = parsePullRequestReference(trimmedBranchQuery); const isSelectingWorktreeBase = @@ -156,21 +271,33 @@ export function BranchToolbarBranchSelector({ ); const [isBranchActionPending, startBranchActionTransition] = useTransition(); const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40; + const totalBranchCount = branchesSearchData?.pages[0]?.totalCount ?? 0; + const branchStatusText = isBranchesSearchPending + ? "Loading branches..." + : isFetchingNextPage + ? "Loading more branches..." + : hasNextPage + ? `Showing ${branches.length} of ${totalBranchCount} branches` + : null; + // --------------------------------------------------------------------------- + // Branch actions + // --------------------------------------------------------------------------- const runBranchAction = (action: () => Promise) => { startBranchActionTransition(async () => { await action().catch(() => undefined); - await invalidateGitQueries(queryClient).catch(() => undefined); + await queryClient + .invalidateQueries({ queryKey: gitQueryKeys.branches(environmentId, branchCwd) }) + .catch(() => undefined); }); }; const selectBranch = (branch: GitBranch) => { - const api = readNativeApi(); - if (!api || !branchCwd || isBranchActionPending) return; + const api = readEnvironmentApi(environmentId); + if (!api || !branchCwd || !activeProjectCwd || isBranchActionPending) return; - // In new-worktree mode, selecting a branch sets the base branch. if (isSelectingWorktreeBase) { - onSetThreadBranch(branch.name, null); + setThreadBranch(branch.name, null); setIsBranchMenuOpen(false); onComposerFocusRequest?.(); return; @@ -182,9 +309,8 @@ export function BranchToolbarBranchSelector({ branch, }); - // If the branch already lives in a worktree, point the thread there. if (selectionTarget.reuseExistingWorktree) { - onSetThreadBranch(branch.name, selectionTarget.nextWorktreePath); + setThreadBranch(branch.name, selectionTarget.nextWorktreePath); setIsBranchMenuOpen(false); onComposerFocusRequest?.(); return; @@ -198,67 +324,56 @@ export function BranchToolbarBranchSelector({ onComposerFocusRequest?.(); runBranchAction(async () => { + const previousBranch = resolvedActiveBranch; setOptimisticBranch(selectedBranchName); try { - await api.git.checkout({ cwd: selectionTarget.checkoutCwd, branch: branch.name }); - await invalidateGitQueries(queryClient); + const checkoutResult = await api.git.checkout({ + cwd: selectionTarget.checkoutCwd, + branch: branch.name, + }); + const nextBranchName = branch.isRemote + ? (checkoutResult.branch ?? selectedBranchName) + : selectedBranchName; + setOptimisticBranch(nextBranchName); + setThreadBranch(nextBranchName, selectionTarget.nextWorktreePath); } catch (error) { + setOptimisticBranch(previousBranch); toastManager.add({ type: "error", title: "Failed to checkout branch.", description: toBranchActionErrorMessage(error), }); - return; } - - let nextBranchName = selectedBranchName; - if (branch.isRemote) { - const status = await api.git.status({ cwd: branchCwd }).catch(() => null); - if (status?.branch) { - nextBranchName = status.branch; - } - } - - setOptimisticBranch(nextBranchName); - onSetThreadBranch(nextBranchName, selectionTarget.nextWorktreePath); }); }; const createBranch = (rawName: string) => { const name = rawName.trim(); - const api = readNativeApi(); + const api = readEnvironmentApi(environmentId); if (!api || !branchCwd || !name || isBranchActionPending) return; setIsBranchMenuOpen(false); onComposerFocusRequest?.(); runBranchAction(async () => { + const previousBranch = resolvedActiveBranch; setOptimisticBranch(name); - try { - await api.git.createBranch({ cwd: branchCwd, branch: name }); - try { - await api.git.checkout({ cwd: branchCwd, branch: name }); - } catch (error) { - toastManager.add({ - type: "error", - title: "Failed to checkout branch.", - description: toBranchActionErrorMessage(error), - }); - return; - } + const createBranchResult = await api.git.createBranch({ + cwd: branchCwd, + branch: name, + checkout: true, + }); + setOptimisticBranch(createBranchResult.branch); + setThreadBranch(createBranchResult.branch, activeWorktreePath); } catch (error) { + setOptimisticBranch(previousBranch); toastManager.add({ type: "error", - title: "Failed to create branch.", + title: "Failed to create and checkout branch.", description: toBranchActionErrorMessage(error), }); - return; } - - setOptimisticBranch(name); - onSetThreadBranch(name, activeWorktreePath); - setBranchQuery(""); }); }; @@ -271,15 +386,12 @@ export function BranchToolbarBranchSelector({ ) { return; } - onSetThreadBranch(currentGitBranch, null); - }, [ - activeThreadBranch, - activeWorktreePath, - currentGitBranch, - effectiveEnvMode, - onSetThreadBranch, - ]); + setThreadBranch(currentGitBranch, null); + }, [activeThreadBranch, activeWorktreePath, currentGitBranch, effectiveEnvMode, setThreadBranch]); + // --------------------------------------------------------------------------- + // Combobox / virtualizer plumbing + // --------------------------------------------------------------------------- const handleOpenChange = useCallback( (open: boolean) => { setIsBranchMenuOpen(open); @@ -288,13 +400,31 @@ export function BranchToolbarBranchSelector({ return; } void queryClient.invalidateQueries({ - queryKey: gitQueryKeys.branches(branchCwd), + queryKey: gitQueryKeys.branches(environmentId, branchCwd), }); }, - [branchCwd, queryClient], + [branchCwd, environmentId, queryClient], ); const branchListScrollElementRef = useRef(null); + const maybeFetchNextBranchPage = useCallback(() => { + if (!isBranchMenuOpen || !hasNextPage || isFetchingNextPage) { + return; + } + + const scrollElement = branchListScrollElementRef.current; + if (!scrollElement) { + return; + } + + const distanceFromBottom = + scrollElement.scrollHeight - scrollElement.scrollTop - scrollElement.clientHeight; + if (distanceFromBottom > 96) { + return; + } + + void fetchNextPage().catch(() => undefined); + }, [fetchNextPage, hasNextPage, isBranchMenuOpen, isFetchingNextPage]); const branchListVirtualizer = useVirtualizer({ count: filteredBranchPickerItems.length, estimateSize: (index) => @@ -331,6 +461,35 @@ export function BranchToolbarBranchSelector({ shouldVirtualizeBranchList, ]); + useEffect(() => { + if (!isBranchMenuOpen) { + return; + } + + branchListScrollElementRef.current?.scrollTo({ top: 0 }); + }, [deferredTrimmedBranchQuery, isBranchMenuOpen]); + + useEffect(() => { + const scrollElement = branchListScrollElementRef.current; + if (!scrollElement || !isBranchMenuOpen) { + return; + } + + const handleScroll = () => { + maybeFetchNextBranchPage(); + }; + + scrollElement.addEventListener("scroll", handleScroll, { passive: true }); + handleScroll(); + return () => { + scrollElement.removeEventListener("scroll", handleScroll); + }; + }, [isBranchMenuOpen, maybeFetchNextBranchPage]); + + useEffect(() => { + maybeFetchNextBranchPage(); + }, [branches.length, maybeFetchNextBranchPage]); + const triggerLabel = getBranchTriggerLabel({ activeWorktreePath, effectiveEnvMode, @@ -373,7 +532,7 @@ export function BranchToolbarBranchSelector({ style={style} onClick={() => createBranch(trimmedBranchQuery)} > - Create new branch "{trimmedBranchQuery}" + Create new branch "{trimmedBranchQuery}" ); } @@ -381,7 +540,8 @@ export function BranchToolbarBranchSelector({ const branch = branchByName.get(itemValue); if (!branch) return null; - const hasSecondaryWorktree = branch.worktreePath && branch.worktreePath !== activeProjectCwd; + const hasSecondaryWorktree = + branch.worktreePath && activeProjectCwd && branch.worktreePath !== activeProjectCwd; const badge = branch.current ? "current" : hasSecondaryWorktree @@ -425,7 +585,7 @@ export function BranchToolbarBranchSelector({ } className="text-muted-foreground/70 hover:text-foreground/80" - disabled={(branchesQuery.isLoading && branches.length === 0) || isBranchActionPending} + disabled={(isBranchesSearchPending && branches.length === 0) || isBranchActionPending} > {triggerLabel} @@ -468,6 +628,7 @@ export function BranchToolbarBranchSelector({ filteredBranchPickerItems.map((itemValue, index) => renderPickerItem(itemValue, index)) )} + {branchStatusText ? {branchStatusText} : null} ); diff --git a/apps/web/src/components/BranchToolbarEnvModeSelector.tsx b/apps/web/src/components/BranchToolbarEnvModeSelector.tsx new file mode 100644 index 0000000000..39bf50359d --- /dev/null +++ b/apps/web/src/components/BranchToolbarEnvModeSelector.tsx @@ -0,0 +1,97 @@ +import { FolderGit2Icon, FolderGitIcon, FolderIcon } from "lucide-react"; +import { memo, useMemo } from "react"; + +import { + resolveCurrentWorkspaceLabel, + resolveEnvModeLabel, + type EnvMode, +} from "./BranchToolbar.logic"; +import { + Select, + SelectGroup, + SelectGroupLabel, + SelectItem, + SelectPopup, + SelectTrigger, + SelectValue, +} from "./ui/select"; + +interface BranchToolbarEnvModeSelectorProps { + envLocked: boolean; + effectiveEnvMode: EnvMode; + activeWorktreePath: string | null; + onEnvModeChange: (mode: EnvMode) => void; +} + +export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSelector({ + envLocked, + effectiveEnvMode, + activeWorktreePath, + onEnvModeChange, +}: BranchToolbarEnvModeSelectorProps) { + const envModeItems = useMemo( + () => [ + { value: "local", label: resolveCurrentWorkspaceLabel(activeWorktreePath) }, + { value: "worktree", label: resolveEnvModeLabel("worktree") }, + ], + [activeWorktreePath], + ); + + if (envLocked) { + return ( + + {activeWorktreePath ? ( + <> + + {resolveCurrentWorkspaceLabel(activeWorktreePath)} + + ) : ( + <> + + {resolveCurrentWorkspaceLabel(activeWorktreePath)} + + )} + + ); + } + + return ( + + ); +}); diff --git a/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx b/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx new file mode 100644 index 0000000000..abfa21365e --- /dev/null +++ b/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx @@ -0,0 +1,88 @@ +import type { EnvironmentId } from "@t3tools/contracts"; +import { CloudIcon, MonitorIcon } from "lucide-react"; +import { memo, useMemo } from "react"; + +import type { EnvironmentOption } from "./BranchToolbar.logic"; +import { + Select, + SelectGroup, + SelectGroupLabel, + SelectItem, + SelectPopup, + SelectTrigger, + SelectValue, +} from "./ui/select"; + +interface BranchToolbarEnvironmentSelectorProps { + envLocked: boolean; + environmentId: EnvironmentId; + availableEnvironments: readonly EnvironmentOption[]; + onEnvironmentChange: (environmentId: EnvironmentId) => void; +} + +export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvironmentSelector({ + envLocked, + environmentId, + availableEnvironments, + onEnvironmentChange, +}: BranchToolbarEnvironmentSelectorProps) { + const activeEnvironment = useMemo(() => { + return availableEnvironments.find((env) => env.environmentId === environmentId) ?? null; + }, [availableEnvironments, environmentId]); + + const environmentItems = useMemo( + () => + availableEnvironments.map((env) => ({ + value: env.environmentId, + label: env.label, + })), + [availableEnvironments], + ); + + if (envLocked) { + return ( + + {activeEnvironment?.isPrimary ? ( + + ) : ( + + )} + {activeEnvironment?.label ?? "Run on"} + + ); + } + + return ( + + ); +}); diff --git a/apps/web/src/components/ChatMarkdown.browser.tsx b/apps/web/src/components/ChatMarkdown.browser.tsx new file mode 100644 index 0000000000..48f345bd2f --- /dev/null +++ b/apps/web/src/components/ChatMarkdown.browser.tsx @@ -0,0 +1,79 @@ +import "../index.css"; + +import { page } from "vitest/browser"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { render } from "vitest-browser-react"; + +const { openInPreferredEditorMock, readLocalApiMock } = vi.hoisted(() => ({ + openInPreferredEditorMock: vi.fn(async () => "vscode"), + readLocalApiMock: vi.fn(() => ({ + server: { getConfig: vi.fn(async () => ({ availableEditors: ["vscode"] })) }, + shell: { openInEditor: vi.fn(async () => undefined) }, + })), +})); + +vi.mock("../editorPreferences", () => ({ + openInPreferredEditor: openInPreferredEditorMock, +})); + +vi.mock("../localApi", () => ({ + ensureLocalApi: vi.fn(() => { + throw new Error("ensureLocalApi not implemented in browser test"); + }), + readLocalApi: readLocalApiMock, +})); + +import ChatMarkdown from "./ChatMarkdown"; + +describe("ChatMarkdown", () => { + afterEach(() => { + openInPreferredEditorMock.mockClear(); + readLocalApiMock.mockClear(); + localStorage.clear(); + document.body.innerHTML = ""; + }); + + it("rewrites file uri hrefs into direct paths before rendering", async () => { + const filePath = + "/Users/yashsingh/p/sco/claude-code-extract/src/utils/permissions/PermissionRule.ts"; + const screen = await render( + , + ); + + try { + const link = page.getByRole("link", { name: "PermissionRule.ts" }); + await expect.element(link).toBeInTheDocument(); + await expect.element(link).toHaveAttribute("href", filePath); + + await link.click(); + + await vi.waitFor(() => { + expect(openInPreferredEditorMock).toHaveBeenCalledWith(expect.anything(), filePath); + }); + } finally { + await screen.unmount(); + } + }); + + it("keeps line anchors working after rewriting file uri hrefs", async () => { + const filePath = + "/Users/yashsingh/p/sco/claude-code-extract/src/utils/permissions/PermissionRule.ts"; + const screen = await render( + , + ); + + try { + const link = page.getByRole("link", { name: "PermissionRule.ts:1" }); + await expect.element(link).toBeInTheDocument(); + await expect.element(link).toHaveAttribute("href", `${filePath}#L1`); + + await link.click(); + + await vi.waitFor(() => { + expect(openInPreferredEditorMock).toHaveBeenCalledWith(expect.anything(), `${filePath}:1`); + }); + } finally { + await screen.unmount(); + } + }); +}); diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index b364a8e3a1..366f923157 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -15,14 +15,15 @@ import React, { } from "react"; import type { Components } from "react-markdown"; import ReactMarkdown from "react-markdown"; +import { defaultUrlTransform } from "react-markdown"; import remarkGfm from "remark-gfm"; import { openInPreferredEditor } from "../editorPreferences"; import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering"; import { fnv1a32 } from "../lib/diffRendering"; import { LRUCache } from "../lib/lruCache"; import { useTheme } from "../hooks/useTheme"; -import { resolveMarkdownFileLinkTarget } from "../markdown-links"; -import { readNativeApi } from "../nativeApi"; +import { resolveMarkdownFileLinkTarget, rewriteMarkdownFileUriHref } from "../markdown-links"; +import { readLocalApi } from "../localApi"; class CodeHighlightErrorBoundary extends React.Component< { fallback: ReactNode; children: ReactNode }, @@ -164,7 +165,7 @@ function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNo ); return ( -
+
@@ -3785,518 +3395,98 @@ export default function ChatView({ threadId }: ChatViewProps) { {/* Input bar */}
-
-
-
- {activePendingApproval ? ( -
- -
- ) : pendingUserInputs.length > 0 ? ( -
- -
- ) : showPlanFollowUpPrompt && activeProposedPlan ? ( -
- -
- ) : null} -
- {composerMenuOpen && !isComposerApprovalState && ( -
- -
- )} - - {!isComposerApprovalState && - pendingUserInputs.length === 0 && - composerImages.length > 0 && ( -
- {composerImages.map((image) => ( -
- {image.previewUrl ? ( - - ) : ( -
- {image.name} -
- )} - {nonPersistedComposerImageIdSet.has(image.id) && ( - - - - - } - /> - - Draft attachment could not be saved locally and may be lost on - navigation. - - - )} - -
- ))} -
- )} - -
- - {/* Bottom toolbar */} - {activePendingApproval ? ( -
- -
- ) : ( -
-
- {/* Provider/model picker */} - - - {isComposerFooterCompact ? ( - - ) : ( - <> - {providerTraitsPicker ? ( - <> - - {providerTraitsPicker} - - ) : null} - - - - - - - - - - {activePlan || sidebarProposedPlan || planSidebarOpen ? ( - <> - - - - ) : null} - - )} -
- - {/* Right side: send / stop button */} -
- {activeContextWindow ? ( - - ) : null} - {isPreparingWorktree ? ( - - 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} -
-
- )} -
-
-
+
{isGitRepo && ( )} {pullRequestDialogState ? ( { @@ -4315,8 +3505,9 @@ export default function ChatView({ threadId }: ChatViewProps) { { setPlanSidebarOpen(false); @@ -4331,101 +3522,25 @@ export default function ChatView({ threadId }: ChatViewProps) {
{/* end horizontal flex container */} - {(() => { - if (!terminalState.terminalOpen || !activeProject) { - return null; - } - return ( - - ); - })()} + {mountedTerminalThreadRefs.map(({ key: mountedThreadKey, threadRef: mountedThreadRef }) => ( + + ))} - {expandedImage && expandedImageItem && ( -
- - )} -
- - {expandedImageItem.name} -

- {expandedImageItem.name} - {expandedImage.images.length > 1 - ? ` (${expandedImage.index + 1}/${expandedImage.images.length})` - : ""} -

-
- {expandedImage.images.length > 1 && ( - - )} -
+ {expandedImage && ( + )}
); diff --git a/apps/web/src/components/ComposerPromptEditor.tsx b/apps/web/src/components/ComposerPromptEditor.tsx index 338d9f7bf1..95157d787f 100644 --- a/apps/web/src/components/ComposerPromptEditor.tsx +++ b/apps/web/src/components/ComposerPromptEditor.tsx @@ -5,6 +5,7 @@ import { LexicalErrorBoundary } from "@lexical/react/LexicalErrorBoundary"; import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin"; import { OnChangePlugin } from "@lexical/react/LexicalOnChangePlugin"; import { PlainTextPlugin } from "@lexical/react/LexicalPlainTextPlugin"; +import { type ServerProviderSkill } from "@t3tools/contracts"; import { $applyNodeReplacement, $createRangeSelection, @@ -26,6 +27,7 @@ import { COMMAND_PRIORITY_HIGH, KEY_BACKSPACE_COMMAND, $getRoot, + HISTORY_MERGE_TAG, DecoratorNode, type ElementNode, type LexicalNode, @@ -58,7 +60,10 @@ import { expandCollapsedComposerCursor, isCollapsedCursorAdjacentToInlineToken, } from "~/composer-logic"; -import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions"; +import { + selectionTouchesMentionBoundary, + splitPromptIntoComposerSegments, +} from "~/composer-editor-mentions"; import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER, type TerminalContextDraft, @@ -69,10 +74,28 @@ import { COMPOSER_INLINE_CHIP_CLASS_NAME, COMPOSER_INLINE_CHIP_ICON_CLASS_NAME, COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME, + COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME, } from "./composerInlineChip"; import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts"; +import { formatProviderSkillDisplayName } from "~/providerSkillPresentation"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; const COMPOSER_EDITOR_HMR_KEY = `composer-editor-${Math.random().toString(36).slice(2)}`; +const SURROUND_SYMBOLS: [string, string][] = [ + ["(", ")"], + ["[", "]"], + ["{", "}"], + ["'", "'"], + ['"', '"'], + ["“", "”"], + ["`", "`"], + ["<", ">"], + ["«", "»"], + ["*", "*"], + ["_", "_"], +]; +const SURROUND_SYMBOLS_MAP = new Map(SURROUND_SYMBOLS); +const BACKTICK_SURROUND_CLOSE_SYMBOL = SURROUND_SYMBOLS_MAP.get("`") ?? null; type SerializedComposerMentionNode = Spread< { @@ -83,6 +106,17 @@ type SerializedComposerMentionNode = Spread< SerializedTextNode >; +type SerializedComposerSkillNode = Spread< + { + skillName: string; + skillLabel?: string; + skillDescription?: string; + type: "composer-skill"; + version: 1; + }, + SerializedLexicalNode +>; + type SerializedComposerTerminalContextNode = Spread< { context: TerminalContextDraft; @@ -170,6 +204,155 @@ function $createComposerMentionNode(path: string): ComposerMentionNode { return $applyNodeReplacement(new ComposerMentionNode(path)); } +const SKILL_CHIP_ICON_SVG = ``; + +function resolveSkillDescription( + skill: Pick, +): string | null { + const shortDescription = skill.shortDescription?.trim(); + if (shortDescription) { + return shortDescription; + } + const description = skill.description?.trim(); + return description || null; +} + +type ComposerSkillMetadata = { + label: string; + description: string | null; +}; + +function skillMetadataByName( + skills: ReadonlyArray, +): ReadonlyMap { + return new Map( + skills.map((skill) => [ + skill.name, + { + label: formatProviderSkillDisplayName(skill), + description: resolveSkillDescription(skill), + }, + ]), + ); +} + +function ComposerSkillDecorator(props: { skillLabel: string; skillDescription: string | null }) { + const chip = ( + + + ); + + if (!props.skillDescription) { + return chip; + } + + return ( + + + + {props.skillDescription} + + + ); +} + +class ComposerSkillNode extends DecoratorNode { + __skillName: string; + __skillLabel: string; + __skillDescription: string | null; + + static override getType(): string { + return "composer-skill"; + } + + static override clone(node: ComposerSkillNode): ComposerSkillNode { + return new ComposerSkillNode( + node.__skillName, + node.__skillLabel, + node.__skillDescription, + node.__key, + ); + } + + static override importJSON(serializedNode: SerializedComposerSkillNode): ComposerSkillNode { + return $createComposerSkillNode( + serializedNode.skillName, + serializedNode.skillLabel ?? serializedNode.skillName, + serializedNode.skillDescription ?? null, + ).updateFromJSON(serializedNode); + } + + constructor( + skillName: string, + skillLabel: string, + skillDescription: string | null, + key?: NodeKey, + ) { + super(key); + const normalizedSkillName = skillName.startsWith("$") ? skillName.slice(1) : skillName; + this.__skillName = normalizedSkillName; + this.__skillLabel = skillLabel; + this.__skillDescription = skillDescription; + } + + override exportJSON(): SerializedComposerSkillNode { + return { + ...super.exportJSON(), + skillName: this.__skillName, + skillLabel: this.__skillLabel, + ...(this.__skillDescription ? { skillDescription: this.__skillDescription } : {}), + type: "composer-skill", + version: 1, + }; + } + + override createDOM(): HTMLElement { + const dom = document.createElement("span"); + dom.className = "inline-flex align-middle leading-none"; + return dom; + } + + override updateDOM(): false { + return false; + } + + override getTextContent(): string { + return `$${this.__skillName}`; + } + + override isInline(): true { + return true; + } + + override decorate(): ReactElement { + return ( + + ); + } +} + +function $createComposerSkillNode( + skillName: string, + skillLabel: string, + skillDescription: string | null, +): ComposerSkillNode { + return $applyNodeReplacement(new ComposerSkillNode(skillName, skillLabel, skillDescription)); +} + function ComposerTerminalContextDecorator(props: { context: TerminalContextDraft }) { return ; } @@ -234,11 +417,16 @@ function $createComposerTerminalContextNode( return $applyNodeReplacement(new ComposerTerminalContextNode(context)); } -type ComposerInlineTokenNode = ComposerMentionNode | ComposerTerminalContextNode; +type ComposerInlineTokenNode = + | ComposerMentionNode + | ComposerSkillNode + | ComposerTerminalContextNode; function isComposerInlineTokenNode(candidate: unknown): candidate is ComposerInlineTokenNode { return ( - candidate instanceof ComposerMentionNode || candidate instanceof ComposerTerminalContextNode + candidate instanceof ComposerMentionNode || + candidate instanceof ComposerSkillNode || + candidate instanceof ComposerTerminalContextNode ); } @@ -283,6 +471,22 @@ function terminalContextSignature(contexts: ReadonlyArray) .join("\u001e"); } +function skillSignature(skills: ReadonlyArray): string { + return skills + .map((skill) => + [ + skill.name, + skill.displayName ?? "", + skill.shortDescription ?? "", + skill.description ?? "", + skill.path, + skill.scope ?? "", + skill.enabled ? "1" : "0", + ].join("\u001f"), + ) + .join("\u001e"); +} + function clampExpandedCursor(value: string, cursor: number): number { if (!Number.isFinite(cursor)) return value.length; return Math.max(0, Math.min(value.length, Math.floor(cursor))); @@ -396,7 +600,7 @@ function getAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): numb } return offset + Math.min(pointOffset, node.getTextContentSize()); } - if (node instanceof ComposerTerminalContextNode) { + if (node instanceof ComposerSkillNode || node instanceof ComposerTerminalContextNode) { return getAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset); } @@ -443,7 +647,7 @@ function getExpandedAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: numbe } return offset + Math.min(pointOffset, node.getTextContentSize()); } - if (node instanceof ComposerTerminalContextNode) { + if (node instanceof ComposerSkillNode || node instanceof ComposerTerminalContextNode) { return getExpandedAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset); } @@ -469,7 +673,7 @@ function findSelectionPointAtOffset( node: LexicalNode, remainingRef: { value: number }, ): { key: string; offset: number; type: "text" | "element" } | null { - if (node instanceof ComposerMentionNode) { + if (node instanceof ComposerMentionNode || node instanceof ComposerSkillNode) { return findSelectionPointForInlineToken(node, remainingRef); } if (node instanceof ComposerTerminalContextNode) { @@ -553,6 +757,53 @@ function $setSelectionAtComposerOffset(nextOffset: number): void { $setSelection(selection); } +function $setSelectionRangeAtComposerOffsets(startOffset: number, endOffset: number): void { + const root = $getRoot(); + const composerLength = $getComposerRootLength(); + const boundedStart = Math.max(0, Math.min(startOffset, composerLength)); + const boundedEnd = Math.max(0, Math.min(endOffset, composerLength)); + const anchorRemainingRef = { value: boundedStart }; + const focusRemainingRef = { value: boundedEnd }; + const anchorPoint = findSelectionPointAtOffset(root, anchorRemainingRef) ?? { + key: root.getKey(), + offset: root.getChildren().length, + type: "element" as const, + }; + const focusPoint = findSelectionPointAtOffset(root, focusRemainingRef) ?? { + key: root.getKey(), + offset: root.getChildren().length, + type: "element" as const, + }; + const selection = $createRangeSelection(); + selection.anchor.set(anchorPoint.key, anchorPoint.offset, anchorPoint.type); + selection.focus.set(focusPoint.key, focusPoint.offset, focusPoint.type); + $setSelection(selection); +} + +function getSelectionRangeForExpandedComposerOffsets(selection: ReturnType): { + start: number; + end: number; +} | null { + if (!$isRangeSelection(selection)) { + return null; + } + const anchorNode = selection.anchor.getNode(); + const focusNode = selection.focus.getNode(); + const anchorOffset = getExpandedAbsoluteOffsetForPoint(anchorNode, selection.anchor.offset); + const focusOffset = getExpandedAbsoluteOffsetForPoint(focusNode, selection.focus.offset); + return { + start: Math.min(anchorOffset, focusOffset), + end: Math.max(anchorOffset, focusOffset), + }; +} + +function $selectionTouchesInlineToken(selection: ReturnType): boolean { + if (!$isRangeSelection(selection)) { + return false; + } + return selection.getNodes().some((node) => isComposerInlineTokenNode(node)); +} + function $readSelectionOffsetFromEditorState(fallback: number): number { const selection = $getSelection(); if (!$isRangeSelection(selection) || !selection.isCollapsed()) { @@ -591,6 +842,7 @@ function $appendTextWithLineBreaks(parent: ElementNode, text: string): void { function $setComposerEditorPrompt( prompt: string, terminalContexts: ReadonlyArray, + skillMetadata: ReadonlyMap, ): void { const root = $getRoot(); root.clear(); @@ -603,6 +855,17 @@ function $setComposerEditorPrompt( paragraph.append($createComposerMentionNode(segment.path)); continue; } + if (segment.type === "skill") { + const metadata = skillMetadata.get(segment.name); + paragraph.append( + $createComposerSkillNode( + segment.name, + metadata?.label ?? formatProviderSkillDisplayName({ name: segment.name }), + metadata?.description ?? null, + ), + ); + continue; + } if (segment.type === "terminal-context") { if (segment.context) { paragraph.append($createComposerTerminalContextNode(segment.context)); @@ -639,6 +902,7 @@ interface ComposerPromptEditorProps { value: string; cursor: number; terminalContexts: ReadonlyArray; + skills: ReadonlyArray; disabled: boolean; placeholder: string; className?: string; @@ -878,10 +1142,280 @@ function ComposerInlineTokenBackspacePlugin() { return null; } +function ComposerSurroundSelectionPlugin(props: { + terminalContexts: ReadonlyArray; + skills: ReadonlyArray; +}) { + const [editor] = useLexicalComposerContext(); + const terminalContextsRef = useRef(props.terminalContexts); + const skillMetadataRef = useRef(skillMetadataByName(props.skills)); + const pendingSurroundSelectionRef = useRef<{ + value: string; + expandedStart: number; + expandedEnd: number; + } | null>(null); + const pendingDeadKeySelectionRef = useRef<{ + value: string; + expandedStart: number; + expandedEnd: number; + } | null>(null); + + useEffect(() => { + terminalContextsRef.current = props.terminalContexts; + }, [props.terminalContexts]); + + useEffect(() => { + skillMetadataRef.current = skillMetadataByName(props.skills); + }, [props.skills]); + + const applySurroundInsertion = useCallback( + (inputData: string): boolean => { + const surroundCloseSymbol = SURROUND_SYMBOLS_MAP.get(inputData); + const pendingSurroundSelection = pendingSurroundSelectionRef.current; + if (!surroundCloseSymbol) { + pendingSurroundSelectionRef.current = null; + return false; + } + + let handled = false; + editor.update(() => { + const selectionSnapshot = + pendingSurroundSelection ?? + (() => { + const selection = $getSelection(); + if (!$isRangeSelection(selection) || selection.isCollapsed()) { + return null; + } + if ($selectionTouchesInlineToken(selection)) { + return null; + } + const range = getSelectionRangeForExpandedComposerOffsets(selection); + if (!range || range.start === range.end) { + return null; + } + const value = $getRoot().getTextContent(); + if (selectionTouchesMentionBoundary(value, range.start, range.end)) { + return null; + } + return { + value, + expandedStart: range.start, + expandedEnd: range.end, + }; + })(); + + if (!selectionSnapshot || !surroundCloseSymbol) { + return; + } + + const selectedText = selectionSnapshot.value.slice( + selectionSnapshot.expandedStart, + selectionSnapshot.expandedEnd, + ); + const nextValue = `${selectionSnapshot.value.slice(0, selectionSnapshot.expandedStart)}${inputData}${selectedText}${surroundCloseSymbol}${selectionSnapshot.value.slice(selectionSnapshot.expandedEnd)}`; + $setComposerEditorPrompt(nextValue, terminalContextsRef.current, skillMetadataRef.current); + const selectionStart = collapseExpandedComposerCursor( + nextValue, + selectionSnapshot.expandedStart, + ); + $setSelectionRangeAtComposerOffsets( + selectionStart + inputData.length, + selectionStart + inputData.length + selectedText.length, + ); + handled = true; + pendingSurroundSelectionRef.current = null; + }); + + return handled; + }, + [editor], + ); + + useEffect(() => { + const onKeyDown = (event: KeyboardEvent) => { + if (pendingDeadKeySelectionRef.current) { + if (event.key === "Dead" || event.key === " " || event.code === "Space") { + return; + } + pendingDeadKeySelectionRef.current = null; + } + + if (event.defaultPrevented || event.isComposing || event.metaKey || event.ctrlKey) { + pendingSurroundSelectionRef.current = null; + pendingDeadKeySelectionRef.current = null; + return; + } + + editor.getEditorState().read(() => { + const selection = $getSelection(); + if (!$isRangeSelection(selection) || selection.isCollapsed()) { + pendingSurroundSelectionRef.current = null; + pendingDeadKeySelectionRef.current = null; + return; + } + if ($selectionTouchesInlineToken(selection)) { + pendingSurroundSelectionRef.current = null; + pendingDeadKeySelectionRef.current = null; + return; + } + const range = getSelectionRangeForExpandedComposerOffsets(selection); + if (!range || range.start === range.end) { + pendingSurroundSelectionRef.current = null; + pendingDeadKeySelectionRef.current = null; + return; + } + const value = $getRoot().getTextContent(); + if (selectionTouchesMentionBoundary(value, range.start, range.end)) { + pendingSurroundSelectionRef.current = null; + pendingDeadKeySelectionRef.current = null; + return; + } + const snapshot = { + value, + expandedStart: range.start, + expandedEnd: range.end, + }; + pendingSurroundSelectionRef.current = snapshot; + pendingDeadKeySelectionRef.current = null; + }); + }; + + const onBeforeInput = (event: InputEvent) => { + if ( + event.inputType === "insertCompositionText" && + event.data === "`" && + BACKTICK_SURROUND_CLOSE_SYMBOL !== null && + pendingSurroundSelectionRef.current + ) { + pendingDeadKeySelectionRef.current = pendingSurroundSelectionRef.current; + return; + } + + if (pendingDeadKeySelectionRef.current) { + return; + } + + if (event.inputType === "insertCompositionText") { + return; + } + + if (typeof event.data !== "string") { + pendingSurroundSelectionRef.current = null; + return; + } + const inputData = event.inputType === "insertText" ? event.data : null; + if (!inputData || inputData.length !== 1) { + pendingSurroundSelectionRef.current = null; + return; + } + if (!applySurroundInsertion(inputData)) { + return; + } + + event.preventDefault(); + event.stopPropagation(); + event.stopImmediatePropagation(); + }; + + const tryApplyDeadKeyBacktickSurround = (options?: { finalAttempt?: boolean }) => { + queueMicrotask(() => { + editor.update( + () => { + const pendingDeadKeySelection = pendingDeadKeySelectionRef.current; + if (!pendingDeadKeySelection) { + return; + } + + const currentValue = $getRoot().getTextContent(); + const backtickCloseSymbol = BACKTICK_SURROUND_CLOSE_SYMBOL; + if (backtickCloseSymbol === null) { + pendingDeadKeySelectionRef.current = null; + return; + } + + const expectedResolvedValue = `${pendingDeadKeySelection.value.slice(0, pendingDeadKeySelection.expandedStart)}\`${pendingDeadKeySelection.value.slice(pendingDeadKeySelection.expandedEnd)}`; + if (currentValue !== expectedResolvedValue) { + if (options?.finalAttempt) { + pendingSurroundSelectionRef.current = null; + pendingDeadKeySelectionRef.current = null; + } + return; + } + + const selectedText = pendingDeadKeySelection.value.slice( + pendingDeadKeySelection.expandedStart, + pendingDeadKeySelection.expandedEnd, + ); + const replacementStart = collapseExpandedComposerCursor( + currentValue, + pendingDeadKeySelection.expandedStart, + ); + $setSelectionRangeAtComposerOffsets(replacementStart, replacementStart + 1); + const replacementSelection = $getSelection(); + if (!$isRangeSelection(replacementSelection)) { + pendingSurroundSelectionRef.current = null; + pendingDeadKeySelectionRef.current = null; + return; + } + replacementSelection.insertText(`\`${selectedText}${backtickCloseSymbol}`); + $setSelectionRangeAtComposerOffsets( + replacementStart + 1, + replacementStart + 1 + selectedText.length, + ); + pendingSurroundSelectionRef.current = null; + pendingDeadKeySelectionRef.current = null; + }, + { tag: HISTORY_MERGE_TAG }, + ); + }); + }; + + const onInput = (event: Event) => { + const inputEvent = event as InputEvent; + if ( + inputEvent.inputType === "insertText" || + inputEvent.inputType === "insertCompositionText" + ) { + tryApplyDeadKeyBacktickSurround(); + } + }; + + const onCompositionEnd = () => { + tryApplyDeadKeyBacktickSurround({ finalAttempt: true }); + }; + + let activeRootElement: HTMLElement | null = null; + const unregisterRootListener = editor.registerRootListener((rootElement, prevRootElement) => { + prevRootElement?.removeEventListener("keydown", onKeyDown); + prevRootElement?.removeEventListener("beforeinput", onBeforeInput, true); + prevRootElement?.removeEventListener("input", onInput); + prevRootElement?.removeEventListener("compositionend", onCompositionEnd); + rootElement?.addEventListener("keydown", onKeyDown); + rootElement?.addEventListener("beforeinput", onBeforeInput, true); + rootElement?.addEventListener("input", onInput); + rootElement?.addEventListener("compositionend", onCompositionEnd); + activeRootElement = rootElement; + }); + + return () => { + if (activeRootElement) { + activeRootElement.removeEventListener("keydown", onKeyDown); + activeRootElement.removeEventListener("beforeinput", onBeforeInput, true); + activeRootElement.removeEventListener("input", onInput); + activeRootElement.removeEventListener("compositionend", onCompositionEnd); + } + unregisterRootListener(); + }; + }, [applySurroundInsertion, editor]); + + return null; +} + function ComposerPromptEditorInner({ value, cursor, terminalContexts, + skills, disabled, placeholder, className, @@ -896,6 +1430,9 @@ function ComposerPromptEditorInner({ const initialCursor = clampCollapsedComposerCursor(value, cursor); const terminalContextsSignature = terminalContextSignature(terminalContexts); const terminalContextsSignatureRef = useRef(terminalContextsSignature); + const skillsSignature = skillSignature(skills); + const skillsSignatureRef = useRef(skillsSignature); + const skillMetadataRef = useRef(skillMetadataByName(skills)); const snapshotRef = useRef({ value, cursor: initialCursor, @@ -912,6 +1449,10 @@ function ComposerPromptEditorInner({ onChangeRef.current = onChange; }, [onChange]); + useLayoutEffect(() => { + skillMetadataRef.current = skillMetadataByName(skills); + }, [skills]); + useEffect(() => { editor.setEditable(!disabled); }, [disabled, editor]); @@ -920,10 +1461,12 @@ function ComposerPromptEditorInner({ const normalizedCursor = clampCollapsedComposerCursor(value, cursor); const previousSnapshot = snapshotRef.current; const contextsChanged = terminalContextsSignatureRef.current !== terminalContextsSignature; + const skillsChanged = skillsSignatureRef.current !== skillsSignature; if ( previousSnapshot.value === value && previousSnapshot.cursor === normalizedCursor && - !contextsChanged + !contextsChanged && + !skillsChanged ) { return; } @@ -935,18 +1478,20 @@ function ComposerPromptEditorInner({ terminalContextIds: terminalContexts.map((context) => context.id), }; terminalContextsSignatureRef.current = terminalContextsSignature; + skillsSignatureRef.current = skillsSignature; const rootElement = editor.getRootElement(); const isFocused = Boolean(rootElement && document.activeElement === rootElement); - if (previousSnapshot.value === value && !contextsChanged && !isFocused) { + if (previousSnapshot.value === value && !contextsChanged && !skillsChanged && !isFocused) { return; } isApplyingControlledUpdateRef.current = true; editor.update(() => { - const shouldRewriteEditorState = previousSnapshot.value !== value || contextsChanged; + const shouldRewriteEditorState = + previousSnapshot.value !== value || contextsChanged || skillsChanged; if (shouldRewriteEditorState) { - $setComposerEditorPrompt(value, terminalContexts); + $setComposerEditorPrompt(value, terminalContexts, skillMetadataRef.current); } if (shouldRewriteEditorState || isFocused) { $setSelectionAtComposerOffset(normalizedCursor); @@ -955,7 +1500,7 @@ function ComposerPromptEditorInner({ queueMicrotask(() => { isApplyingControlledUpdateRef.current = false; }); - }, [cursor, editor, terminalContexts, terminalContextsSignature, value]); + }, [cursor, editor, skillsSignature, terminalContexts, terminalContextsSignature, value]); const focusAt = useCallback( (nextCursor: number) => { @@ -1113,6 +1658,7 @@ function ComposerPromptEditorInner({ /> + @@ -1130,6 +1676,7 @@ export const ComposerPromptEditor = forwardRef< value, cursor, terminalContexts, + skills, disabled, placeholder, className, @@ -1142,13 +1689,18 @@ export const ComposerPromptEditor = forwardRef< ) { const initialValueRef = useRef(value); const initialTerminalContextsRef = useRef(terminalContexts); + const initialSkillMetadataRef = useRef(skillMetadataByName(skills)); const initialConfig = useMemo( () => ({ namespace: "t3tools-composer-editor", editable: true, - nodes: [ComposerMentionNode, ComposerTerminalContextNode], + nodes: [ComposerMentionNode, ComposerSkillNode, ComposerTerminalContextNode], editorState: () => { - $setComposerEditorPrompt(initialValueRef.current, initialTerminalContextsRef.current); + $setComposerEditorPrompt( + initialValueRef.current, + initialTerminalContextsRef.current, + initialSkillMetadataRef.current, + ); }, onError: (error) => { throw error; @@ -1163,6 +1715,7 @@ export const ComposerPromptEditor = forwardRef< value={value} cursor={cursor} terminalContexts={terminalContexts} + skills={skills} disabled={disabled} placeholder={placeholder} onRemoveTerminalContext={onRemoveTerminalContext} diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index fadb8cb69d..63a5231f73 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -2,7 +2,8 @@ import { parsePatchFiles } from "@pierre/diffs"; import { FileDiff, type FileDiffMetadata, Virtualizer } from "@pierre/diffs/react"; import { useQuery } from "@tanstack/react-query"; import { useNavigate, useParams, useSearch } from "@tanstack/react-router"; -import { ThreadId, type TurnId } from "@t3tools/contracts"; +import { scopeThreadRef } from "@t3tools/client-runtime"; +import type { TurnId } from "@t3tools/contracts"; import { ChevronLeftIcon, ChevronRightIcon, @@ -19,17 +20,19 @@ import { useState, } from "react"; import { openInPreferredEditor } from "../editorPreferences"; -import { gitBranchesQueryOptions } from "~/lib/gitReactQuery"; +import { useGitStatus } from "~/lib/gitStatusState"; import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery"; import { cn } from "~/lib/utils"; -import { readNativeApi } from "../nativeApi"; +import { readLocalApi } from "../localApi"; import { resolvePathLinkTarget } from "../terminal-links"; import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch"; import { useTheme } from "../hooks/useTheme"; import { buildPatchCacheKey } from "../lib/diffRendering"; import { resolveDiffThemeName } from "../lib/diffRendering"; import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries"; -import { useStore } from "../store"; +import { selectProjectByRef, useStore } from "../store"; +import { createThreadSelectorByRef } from "../storeSelectors"; +import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes"; import { useSettings } from "../hooks/useSettings"; import { formatShortTimestamp } from "../timestampFormat"; import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell"; @@ -174,23 +177,31 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) { const previousDiffOpenRef = useRef(false); const [canScrollTurnStripLeft, setCanScrollTurnStripLeft] = useState(false); const [canScrollTurnStripRight, setCanScrollTurnStripRight] = useState(false); - const routeThreadId = useParams({ + const routeThreadRef = useParams({ strict: false, - select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null), + select: (params) => resolveThreadRouteRef(params), }); const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) }); const diffOpen = diffSearch.diff === "1"; - const activeThreadId = routeThreadId; - const activeThread = useStore((store) => - activeThreadId ? store.threads.find((thread) => thread.id === activeThreadId) : undefined, + const activeThreadId = routeThreadRef?.threadId ?? null; + const activeThread = useStore( + useMemo(() => createThreadSelectorByRef(routeThreadRef), [routeThreadRef]), ); const activeProjectId = activeThread?.projectId ?? null; const activeProject = useStore((store) => - activeProjectId ? store.projects.find((project) => project.id === activeProjectId) : undefined, + activeThread && activeProjectId + ? selectProjectByRef(store, { + environmentId: activeThread.environmentId, + projectId: activeProjectId, + }) + : undefined, ); const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd; - const gitBranchesQuery = useQuery(gitBranchesQueryOptions(activeCwd ?? null)); - const isGitRepo = gitBranchesQuery.data?.isRepo ?? true; + const gitStatusQuery = useGitStatus({ + environmentId: activeThread?.environmentId ?? null, + cwd: activeCwd ?? null, + }); + const isGitRepo = gitStatusQuery.data?.isRepo ?? true; const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } = useTurnDiffSummaries(activeThread); const orderedTurnDiffSummaries = useMemo( @@ -262,6 +273,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) { }, [orderedTurnDiffSummaries, selectedTurn]); const activeCheckpointDiffQuery = useQuery( checkpointDiffQueryOptions({ + environmentId: activeThread?.environmentId ?? null, threadId: activeThreadId, fromTurnCount: activeCheckpointRange?.fromTurnCount ?? null, toTurnCount: activeCheckpointRange?.toTurnCount ?? null, @@ -321,7 +333,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) { const openDiffFileInEditor = useCallback( (filePath: string) => { - const api = readNativeApi(); + const api = readLocalApi(); if (!api) return; const targetPath = activeCwd ? resolvePathLinkTarget(filePath, activeCwd) : filePath; void openInPreferredEditor(api, targetPath).catch((error) => { @@ -334,8 +346,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) { const selectTurn = (turnId: TurnId) => { if (!activeThread) return; void navigate({ - to: "/$threadId", - params: { threadId: activeThread.id }, + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(scopeThreadRef(activeThread.environmentId, activeThread.id)), search: (previous) => { const rest = stripDiffSearchParams(previous); return { ...rest, diff: "1", diffTurnId: turnId }; @@ -345,8 +357,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) { const selectWholeConversation = () => { if (!activeThread) return; void navigate({ - to: "/$threadId", - params: { threadId: activeThread.id }, + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(scopeThreadRef(activeThread.environmentId, activeThread.id)), search: (previous) => { const rest = stripDiffSearchParams(previous); return { ...rest, diff: "1" }; diff --git a/apps/web/src/components/GitActionsControl.browser.tsx b/apps/web/src/components/GitActionsControl.browser.tsx new file mode 100644 index 0000000000..651b383fa0 --- /dev/null +++ b/apps/web/src/components/GitActionsControl.browser.tsx @@ -0,0 +1,462 @@ +import { scopeThreadRef } from "@t3tools/client-runtime"; +import { ThreadId } from "@t3tools/contracts"; +import { useState } from "react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { render } from "vitest-browser-react"; + +const SHARED_THREAD_ID = ThreadId.make("thread-shared"); +const ENVIRONMENT_A = "environment-local" as never; +const ENVIRONMENT_B = "environment-remote" as never; +const GIT_CWD = "/repo/project"; +const BRANCH_NAME = "feature/toast-scope"; + +function createDeferredPromise() { + let resolve!: (value: T) => void; + let reject!: (reason?: unknown) => void; + + const promise = new Promise((nextResolve, nextReject) => { + resolve = nextResolve; + reject = nextReject; + }); + + return { promise, resolve, reject }; +} + +const { + activeRunStackedActionDeferredRef, + activeDraftThreadRef, + hasServerThreadRef, + invalidateGitQueriesSpy, + refreshGitStatusSpy, + runStackedActionMutateAsyncSpy, + setDraftThreadContextSpy, + setThreadBranchSpy, + toastAddSpy, + toastCloseSpy, + toastPromiseSpy, + toastUpdateSpy, +} = vi.hoisted(() => ({ + activeRunStackedActionDeferredRef: { current: createDeferredPromise() }, + activeDraftThreadRef: { current: null as unknown }, + hasServerThreadRef: { current: true }, + invalidateGitQueriesSpy: vi.fn(() => Promise.resolve()), + refreshGitStatusSpy: vi.fn(() => Promise.resolve(null)), + runStackedActionMutateAsyncSpy: vi.fn(() => activeRunStackedActionDeferredRef.current.promise), + setDraftThreadContextSpy: vi.fn(), + setThreadBranchSpy: vi.fn(), + toastAddSpy: vi.fn(() => "toast-1"), + toastCloseSpy: vi.fn(), + toastPromiseSpy: vi.fn(), + toastUpdateSpy: vi.fn(), +})); + +vi.mock("@tanstack/react-query", async () => { + const actual = + await vi.importActual("@tanstack/react-query"); + + return { + ...actual, + useIsMutating: vi.fn(() => 0), + useMutation: vi.fn((options: { __kind?: string }) => { + if (options.__kind === "run-stacked-action") { + return { + mutateAsync: runStackedActionMutateAsyncSpy, + isPending: false, + }; + } + + if (options.__kind === "pull") { + return { + mutateAsync: vi.fn(), + isPending: false, + }; + } + + return { + mutate: vi.fn(), + mutateAsync: vi.fn(), + isPending: false, + }; + }), + useQuery: vi.fn(() => ({ data: null, error: null })), + useQueryClient: vi.fn(() => ({})), + }; +}); + +vi.mock("~/components/ui/toast", () => ({ + toastManager: { + add: toastAddSpy, + close: toastCloseSpy, + promise: toastPromiseSpy, + update: toastUpdateSpy, + }, +})); + +vi.mock("~/editorPreferences", () => ({ + openInPreferredEditor: vi.fn(), +})); + +vi.mock("~/lib/gitReactQuery", () => ({ + gitInitMutationOptions: vi.fn(() => ({ __kind: "init" })), + gitMutationKeys: { + pull: vi.fn(() => ["pull"]), + runStackedAction: vi.fn(() => ["run-stacked-action"]), + }, + gitPullMutationOptions: vi.fn(() => ({ __kind: "pull" })), + gitRunStackedActionMutationOptions: vi.fn(() => ({ __kind: "run-stacked-action" })), + invalidateGitQueries: invalidateGitQueriesSpy, +})); + +vi.mock("~/lib/gitStatusState", () => ({ + refreshGitStatus: refreshGitStatusSpy, + resetGitStatusStateForTests: () => undefined, + useGitStatus: vi.fn(() => ({ + data: { + branch: BRANCH_NAME, + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + hasUpstream: true, + aheadCount: 1, + behindCount: 0, + pr: null, + }, + error: null, + isPending: false, + })), +})); + +vi.mock("~/localApi", () => ({ + ensureLocalApi: vi.fn(() => { + throw new Error("ensureLocalApi not implemented in browser test"); + }), + readLocalApi: vi.fn(() => null), +})); + +vi.mock("~/composerDraftStore", async () => { + const draftStoreState = { + getDraftThreadByRef: () => activeDraftThreadRef.current, + getDraftSession: () => activeDraftThreadRef.current, + getDraftThread: () => activeDraftThreadRef.current, + getDraftSessionByLogicalProjectKey: () => null, + setDraftThreadContext: setDraftThreadContextSpy, + setLogicalProjectDraftThreadId: vi.fn(), + setProjectDraftThreadId: vi.fn(), + hasDraftThreadsInEnvironment: () => false, + clearDraftThread: vi.fn(), + }; + + return { + DraftId: { + makeUnsafe: (value: string) => value, + }, + useComposerDraftStore: Object.assign( + (selector: (state: unknown) => unknown) => selector(draftStoreState), + { getState: () => draftStoreState }, + ), + markPromotedDraftThread: vi.fn(), + markPromotedDraftThreadByRef: vi.fn(), + markPromotedDraftThreads: vi.fn(), + markPromotedDraftThreadsByRef: vi.fn(), + finalizePromotedDraftThreadByRef: vi.fn(), + finalizePromotedDraftThreadsByRef: vi.fn(), + }; +}); + +vi.mock("~/store", () => ({ + selectEnvironmentState: ( + state: { environmentStateById: Record }, + environmentId: string | null, + ) => { + if (!environmentId) { + throw new Error("Missing environment id"); + } + const environmentState = state.environmentStateById[environmentId]; + if (!environmentState) { + throw new Error(`Unknown environment: ${environmentId}`); + } + return environmentState; + }, + selectProjectsForEnvironment: () => [], + selectProjectsAcrossEnvironments: () => [], + selectThreadsForEnvironment: () => [], + selectThreadsAcrossEnvironments: () => [], + selectThreadShellsAcrossEnvironments: () => [], + selectSidebarThreadsAcrossEnvironments: () => [], + selectSidebarThreadsForProjectRef: () => [], + selectSidebarThreadsForProjectRefs: () => [], + selectBootstrapCompleteForActiveEnvironment: () => true, + selectProjectByRef: () => null, + selectThreadByRef: () => null, + selectSidebarThreadSummaryByRef: () => null, + selectThreadIdsByProjectRef: () => [], + useStore: (selector: (state: unknown) => unknown) => + selector({ + setThreadBranch: setThreadBranchSpy, + environmentStateById: { + [ENVIRONMENT_A]: { + threadShellById: hasServerThreadRef.current + ? { + [SHARED_THREAD_ID]: { + id: SHARED_THREAD_ID, + branch: BRANCH_NAME, + worktreePath: null, + }, + } + : {}, + threadSessionById: {}, + threadTurnStateById: {}, + messageIdsByThreadId: {}, + messageByThreadId: {}, + activityIdsByThreadId: {}, + activityByThreadId: {}, + proposedPlanIdsByThreadId: {}, + proposedPlanByThreadId: {}, + turnDiffIdsByThreadId: {}, + turnDiffSummaryByThreadId: {}, + }, + [ENVIRONMENT_B]: { + threadShellById: hasServerThreadRef.current + ? { + [SHARED_THREAD_ID]: { + id: SHARED_THREAD_ID, + branch: BRANCH_NAME, + worktreePath: null, + }, + } + : {}, + threadSessionById: {}, + threadTurnStateById: {}, + messageIdsByThreadId: {}, + messageByThreadId: {}, + activityIdsByThreadId: {}, + activityByThreadId: {}, + proposedPlanIdsByThreadId: {}, + proposedPlanByThreadId: {}, + turnDiffIdsByThreadId: {}, + turnDiffSummaryByThreadId: {}, + }, + }, + }), +})); + +vi.mock("~/terminal-links", () => ({ + resolvePathLinkTarget: vi.fn(), +})); + +import GitActionsControl from "./GitActionsControl"; + +function findButtonByText(text: string): HTMLButtonElement | null { + return (Array.from(document.querySelectorAll("button")).find((button) => + button.textContent?.includes(text), + ) ?? null) as HTMLButtonElement | null; +} + +function Harness() { + const [activeThreadRef, setActiveThreadRef] = useState( + scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID), + ); + + return ( + <> + + + + ); +} + +describe("GitActionsControl thread-scoped progress toast", () => { + afterEach(() => { + vi.useRealTimers(); + vi.clearAllMocks(); + activeRunStackedActionDeferredRef.current = createDeferredPromise(); + activeDraftThreadRef.current = null; + hasServerThreadRef.current = true; + document.body.innerHTML = ""; + }); + + it("keeps an in-flight git action toast pinned to the thread ref that started it", async () => { + vi.useFakeTimers(); + + const host = document.createElement("div"); + document.body.append(host); + const screen = await render(, { container: host }); + + try { + const quickActionButton = findButtonByText("Push & create PR"); + expect(quickActionButton, 'Unable to find button containing "Push & create PR"').toBeTruthy(); + if (!(quickActionButton instanceof HTMLButtonElement)) { + throw new Error('Unable to find button containing "Push & create PR"'); + } + quickActionButton.click(); + + expect(toastAddSpy).toHaveBeenCalledWith( + expect.objectContaining({ + data: { threadRef: scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID) }, + title: "Pushing...", + type: "loading", + }), + ); + + await vi.advanceTimersByTimeAsync(1_000); + + expect(toastUpdateSpy).toHaveBeenLastCalledWith( + "toast-1", + expect.objectContaining({ + data: { threadRef: scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID) }, + title: "Pushing...", + type: "loading", + }), + ); + + const switchEnvironmentButton = findButtonByText("Switch environment"); + expect( + switchEnvironmentButton, + 'Unable to find button containing "Switch environment"', + ).toBeTruthy(); + if (!(switchEnvironmentButton instanceof HTMLButtonElement)) { + throw new Error('Unable to find button containing "Switch environment"'); + } + switchEnvironmentButton.click(); + await vi.advanceTimersByTimeAsync(1_000); + + expect(toastUpdateSpy).toHaveBeenLastCalledWith( + "toast-1", + expect.objectContaining({ + data: { threadRef: scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID) }, + title: "Pushing...", + type: "loading", + }), + ); + } finally { + activeRunStackedActionDeferredRef.current.reject(new Error("test cleanup")); + await Promise.resolve(); + vi.useRealTimers(); + await screen.unmount(); + host.remove(); + } + }); + + it("debounces focus-driven git status refreshes", async () => { + vi.useFakeTimers(); + + const originalVisibilityState = Object.getOwnPropertyDescriptor(document, "visibilityState"); + let visibilityState: DocumentVisibilityState = "hidden"; + Object.defineProperty(document, "visibilityState", { + configurable: true, + get: () => visibilityState, + }); + + const host = document.createElement("div"); + document.body.append(host); + const screen = await render( + , + { + container: host, + }, + ); + + try { + window.dispatchEvent(new Event("focus")); + visibilityState = "visible"; + document.dispatchEvent(new Event("visibilitychange")); + + expect(refreshGitStatusSpy).not.toHaveBeenCalled(); + + await vi.advanceTimersByTimeAsync(249); + expect(refreshGitStatusSpy).not.toHaveBeenCalled(); + + await vi.advanceTimersByTimeAsync(1); + expect(refreshGitStatusSpy).toHaveBeenCalledTimes(1); + expect(refreshGitStatusSpy).toHaveBeenCalledWith({ + environmentId: ENVIRONMENT_A, + cwd: GIT_CWD, + }); + } finally { + if (originalVisibilityState) { + Object.defineProperty(document, "visibilityState", originalVisibilityState); + } + vi.useRealTimers(); + await screen.unmount(); + host.remove(); + } + }); + + it("syncs the live branch into the active draft thread when no server thread exists", async () => { + hasServerThreadRef.current = false; + activeDraftThreadRef.current = { + threadId: SHARED_THREAD_ID, + environmentId: ENVIRONMENT_A, + branch: null, + worktreePath: null, + }; + + const host = document.createElement("div"); + document.body.append(host); + const screen = await render( + , + { + container: host, + }, + ); + + try { + await Promise.resolve(); + + expect(setDraftThreadContextSpy).toHaveBeenCalledWith( + scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID), + { + branch: BRANCH_NAME, + worktreePath: null, + }, + ); + expect(setThreadBranchSpy).not.toHaveBeenCalled(); + } finally { + await screen.unmount(); + host.remove(); + } + }); + + it("does not overwrite a selected base branch while a new worktree draft is being configured", async () => { + hasServerThreadRef.current = false; + activeDraftThreadRef.current = { + threadId: SHARED_THREAD_ID, + environmentId: ENVIRONMENT_A, + branch: "feature/base-branch", + worktreePath: null, + envMode: "worktree", + }; + + const host = document.createElement("div"); + document.body.append(host); + const screen = await render( + , + { + container: host, + }, + ); + + try { + await Promise.resolve(); + + expect(setDraftThreadContextSpy).not.toHaveBeenCalled(); + expect(setThreadBranchSpy).not.toHaveBeenCalled(); + } finally { + await screen.unmount(); + host.remove(); + } + }); +}); diff --git a/apps/web/src/components/GitActionsControl.logic.test.ts b/apps/web/src/components/GitActionsControl.logic.test.ts index 44ad29efac..267cbec180 100644 --- a/apps/web/src/components/GitActionsControl.logic.test.ts +++ b/apps/web/src/components/GitActionsControl.logic.test.ts @@ -6,12 +6,16 @@ import { requiresDefaultBranchConfirmation, resolveAutoFeatureBranchName, resolveDefaultBranchActionDialogCopy, + resolveLiveThreadBranchUpdate, resolveQuickAction, - summarizeGitResult, + resolveThreadBranchUpdate, } from "./GitActionsControl.logic"; function status(overrides: Partial = {}): GitStatusResult { return { + isRepo: true, + hasOriginRemote: true, + isDefaultBranch: false, branch: "feature/test", hasWorkingTreeChanges: false, workingTree: { @@ -162,7 +166,7 @@ describe("when: branch is clean, ahead, and has an open PR", () => { }), false, ); - assert.deepInclude(quick, { kind: "run_action", action: "commit_push", label: "Push" }); + assert.deepInclude(quick, { kind: "run_action", action: "push", label: "Push" }); }); it("buildMenuItems enables push and keeps open PR available", () => { @@ -213,7 +217,7 @@ describe("when: branch is clean, ahead, and has no open PR", () => { const quick = resolveQuickAction(status({ aheadCount: 2, pr: null }), false); assert.deepInclude(quick, { kind: "run_action", - action: "commit_push_pr", + action: "create_pr", label: "Push & create PR", }); }); @@ -585,7 +589,7 @@ describe("when: branch has no upstream configured", () => { ); assert.deepInclude(quick, { kind: "run_action", - action: "commit_push", + action: "push", label: "Push", disabled: false, }); @@ -632,7 +636,7 @@ describe("when: branch has no upstream configured", () => { ); assert.deepInclude(quick, { kind: "run_action", - action: "commit_push_pr", + action: "create_pr", label: "Push & create PR", disabled: false, }); @@ -801,9 +805,12 @@ describe("when: branch has no upstream configured", () => { describe("requiresDefaultBranchConfirmation", () => { it("requires confirmation for push actions on default branch", () => { assert.isFalse(requiresDefaultBranchConfirmation("commit", true)); + assert.isTrue(requiresDefaultBranchConfirmation("push", true)); + assert.isTrue(requiresDefaultBranchConfirmation("create_pr", true)); assert.isTrue(requiresDefaultBranchConfirmation("commit_push", true)); assert.isTrue(requiresDefaultBranchConfirmation("commit_push_pr", true)); assert.isFalse(requiresDefaultBranchConfirmation("commit_push", false)); + assert.isFalse(requiresDefaultBranchConfirmation("push", false)); }); }); @@ -855,26 +862,44 @@ describe("resolveDefaultBranchActionDialogCopy", () => { }); describe("buildGitActionProgressStages", () => { - it("shows only push progress when push-only is forced", () => { + it("shows only push progress for explicit push actions", () => { const stages = buildGitActionProgressStages({ - action: "commit_push", + action: "push", hasCustomCommitMessage: false, - hasWorkingTreeChanges: true, - forcePushOnly: true, + hasWorkingTreeChanges: false, pushTarget: "origin/feature/test", }); assert.deepEqual(stages, ["Pushing to origin/feature/test..."]); }); - it("skips commit stages for create-pr flow when push-only is forced", () => { + it("shows push and PR progress for create-pr actions that still need a push", () => { const stages = buildGitActionProgressStages({ - action: "commit_push_pr", + action: "create_pr", hasCustomCommitMessage: false, - hasWorkingTreeChanges: true, - forcePushOnly: true, + hasWorkingTreeChanges: false, pushTarget: "origin/feature/test", + shouldPushBeforePr: true, }); - assert.deepEqual(stages, ["Pushing to origin/feature/test...", "Creating PR..."]); + assert.deepEqual(stages, [ + "Pushing to origin/feature/test...", + "Preparing PR...", + "Generating PR content...", + "Creating GitHub pull request...", + ]); + }); + + it("shows only PR progress when create-pr can skip the push", () => { + const stages = buildGitActionProgressStages({ + action: "create_pr", + hasCustomCommitMessage: false, + hasWorkingTreeChanges: false, + shouldPushBeforePr: false, + }); + assert.deepEqual(stages, [ + "Preparing PR...", + "Generating PR content...", + "Creating GitHub pull request...", + ]); }); it("includes commit stages for commit+push when working tree is dirty", () => { @@ -890,99 +915,110 @@ describe("buildGitActionProgressStages", () => { "Pushing to origin/feature/test...", ]); }); + + it("includes granular PR stages for commit+push+PR actions", () => { + const stages = buildGitActionProgressStages({ + action: "commit_push_pr", + hasCustomCommitMessage: true, + hasWorkingTreeChanges: true, + pushTarget: "origin/feature/test", + }); + assert.deepEqual(stages, [ + "Committing...", + "Pushing to origin/feature/test...", + "Preparing PR...", + "Generating PR content...", + "Creating GitHub pull request...", + ]); + }); }); -describe("summarizeGitResult", () => { - it("returns commit-focused toast for commit action", () => { - const result = summarizeGitResult({ - action: "commit", - branch: { status: "skipped_not_requested" }, +describe("resolveThreadBranchUpdate", () => { + it("returns a branch update when the action created a new branch", () => { + const update = resolveThreadBranchUpdate({ + action: "commit_push_pr", + branch: { + status: "created", + name: "feature/fix-toast-copy", + }, commit: { status: "created", - commitSha: "0123456789abcdef", - subject: "feat: add optimistic UI for git action button", + commitSha: "89abcdef01234567", + subject: "feat: add branch sync", }, - push: { status: "skipped_not_requested" }, + push: { status: "pushed", branch: "feature/fix-toast-copy" }, pr: { status: "skipped_not_requested" }, + toast: { + title: "Pushed 89abcde to origin/feature/fix-toast-copy", + cta: { kind: "none" }, + }, }); - assert.deepEqual(result, { - title: "Committed 0123456", - description: "feat: add optimistic UI for git action button", + assert.deepEqual(update, { + branch: "feature/fix-toast-copy", }); }); - it("returns push-focused toast for push action", () => { - const result = summarizeGitResult({ + it("returns null when the action stayed on the existing branch", () => { + const update = resolveThreadBranchUpdate({ action: "commit_push", - branch: { status: "skipped_not_requested" }, + branch: { + status: "skipped_not_requested", + }, commit: { status: "created", - commitSha: "abcdef0123456789", - subject: "fix: tighten quick action tooltip hover handling", - }, - push: { - status: "pushed", - branch: "foo", - upstreamBranch: "origin/foo", + commitSha: "89abcdef01234567", + subject: "feat: add branch sync", }, + push: { status: "pushed", branch: "feature/fix-toast-copy" }, pr: { status: "skipped_not_requested" }, + toast: { + title: "Pushed 89abcde to origin/feature/fix-toast-copy", + cta: { kind: "none" }, + }, }); - assert.deepEqual(result, { - title: "Pushed abcdef0 to origin/foo", - description: "fix: tighten quick action tooltip hover handling", + assert.equal(update, null); + }); +}); + +describe("resolveLiveThreadBranchUpdate", () => { + it("returns a branch update when live git status differs from stored thread metadata", () => { + const update = resolveLiveThreadBranchUpdate({ + threadBranch: "feature/old-branch", + gitStatus: status({ branch: "effect-atom" }), + }); + + assert.deepEqual(update, { + branch: "effect-atom", }); }); - it("returns PR-focused toast for created PR action", () => { - const result = summarizeGitResult({ - action: "commit_push_pr", - branch: { status: "skipped_not_requested" }, - commit: { - status: "created", - commitSha: "89abcdef01234567", - subject: "feat: ship github shortcuts", - }, - push: { - status: "pushed", - branch: "foo", - }, - pr: { - status: "created", - number: 42, - title: "feat: ship github shortcuts and improve PR CTA in success toast", - }, + it("returns null when live git status is unavailable", () => { + const update = resolveLiveThreadBranchUpdate({ + threadBranch: "feature/old-branch", + gitStatus: null, }); - assert.deepEqual(result, { - title: "Created PR #42", - description: "feat: ship github shortcuts and improve PR CTA in success toast", - }); + assert.equal(update, null); }); - it("truncates long description text", () => { - const result = summarizeGitResult({ - action: "commit_push_pr", - branch: { status: "skipped_not_requested" }, - commit: { - status: "created", - commitSha: "89abcdef01234567", - subject: "short subject", - }, - push: { status: "pushed", branch: "foo" }, - pr: { - status: "created", - number: 99, - title: - "feat: this title is intentionally extremely long so we can validate that toast descriptions are truncated with an ellipsis suffix", - }, + it("returns null when the stored thread branch already matches git status", () => { + const update = resolveLiveThreadBranchUpdate({ + threadBranch: "effect-atom", + gitStatus: status({ branch: "effect-atom" }), }); - assert.deepEqual(result, { - title: "Created PR #99", - description: "feat: this title is intentionally extremely long so we can validate t...", + assert.equal(update, null); + }); + + it("returns null when git status is detached HEAD but the thread already has a branch", () => { + const update = resolveLiveThreadBranchUpdate({ + threadBranch: "effect-atom", + gitStatus: status({ branch: null }), }); + + assert.equal(update, null); }); }); diff --git a/apps/web/src/components/GitActionsControl.logic.ts b/apps/web/src/components/GitActionsControl.logic.ts index 8f7f023ef7..b4b0b98b0b 100644 --- a/apps/web/src/components/GitActionsControl.logic.ts +++ b/apps/web/src/components/GitActionsControl.logic.ts @@ -31,83 +31,48 @@ export interface DefaultBranchActionDialogCopy { continueLabel: string; } -export type DefaultBranchConfirmableAction = "commit_push" | "commit_push_pr"; - -const SHORT_SHA_LENGTH = 7; -const TOAST_DESCRIPTION_MAX = 72; - -function shortenSha(sha: string | undefined): string | null { - if (!sha) return null; - return sha.slice(0, SHORT_SHA_LENGTH); -} - -function truncateText( - value: string | undefined, - maxLength = TOAST_DESCRIPTION_MAX, -): string | undefined { - if (!value) return undefined; - if (value.length <= maxLength) return value; - if (maxLength <= 3) return "...".slice(0, maxLength); - return `${value.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`; -} +export type DefaultBranchConfirmableAction = + | "push" + | "create_pr" + | "commit_push" + | "commit_push_pr"; export function buildGitActionProgressStages(input: { action: GitStackedAction; hasCustomCommitMessage: boolean; hasWorkingTreeChanges: boolean; - forcePushOnly?: boolean; pushTarget?: string; featureBranch?: boolean; + shouldPushBeforePr?: boolean; }): string[] { const branchStages = input.featureBranch ? ["Preparing feature branch..."] : []; - const shouldIncludeCommitStages = - !input.forcePushOnly && (input.action === "commit" || input.hasWorkingTreeChanges); + const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing..."; + const prStages = [ + "Preparing PR...", + "Generating PR content...", + "Creating GitHub pull request...", + ]; + + if (input.action === "push") { + return [pushStage]; + } + if (input.action === "create_pr") { + return input.shouldPushBeforePr ? [pushStage, ...prStages] : prStages; + } + + const shouldIncludeCommitStages = input.action === "commit" || input.hasWorkingTreeChanges; const commitStages = !shouldIncludeCommitStages ? [] : input.hasCustomCommitMessage ? ["Committing..."] : ["Generating commit message...", "Committing..."]; - const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing..."; if (input.action === "commit") { return [...branchStages, ...commitStages]; } if (input.action === "commit_push") { return [...branchStages, ...commitStages, pushStage]; } - return [...branchStages, ...commitStages, pushStage, "Creating PR..."]; -} - -const withDescription = (title: string, description: string | undefined) => - description ? { title, description } : { title }; - -export function summarizeGitResult(result: GitRunStackedActionResult): { - title: string; - description?: string; -} { - if (result.pr.status === "created" || result.pr.status === "opened_existing") { - const prNumber = result.pr.number ? ` #${result.pr.number}` : ""; - const title = `${result.pr.status === "created" ? "Created PR" : "Opened PR"}${prNumber}`; - return withDescription(title, truncateText(result.pr.title)); - } - - if (result.push.status === "pushed") { - const shortSha = shortenSha(result.commit.commitSha); - const branch = result.push.upstreamBranch ?? result.push.branch; - const pushedCommitPart = shortSha ? ` ${shortSha}` : ""; - const branchPart = branch ? ` to ${branch}` : ""; - return withDescription( - `Pushed${pushedCommitPart}${branchPart}`, - truncateText(result.commit.subject), - ); - } - - if (result.commit.status === "created") { - const shortSha = shortenSha(result.commit.commitSha); - const title = shortSha ? `Committed ${shortSha}` : "Committed changes"; - return withDescription(title, truncateText(result.commit.subject)); - } - - return { title: "Done" }; + return [...branchStages, ...commitStages, pushStage, ...prStages]; } export function buildMenuItems( @@ -250,13 +215,18 @@ export function resolveQuickAction( }; } if (hasOpenPr || isDefaultBranch) { - return { label: "Push", disabled: false, kind: "run_action", action: "commit_push" }; + return { + label: "Push", + disabled: false, + kind: "run_action", + action: isDefaultBranch ? "commit_push" : "push", + }; } return { label: "Push & create PR", disabled: false, kind: "run_action", - action: "commit_push_pr", + action: "create_pr", }; } @@ -279,13 +249,18 @@ export function resolveQuickAction( if (isAhead) { if (hasOpenPr || isDefaultBranch) { - return { label: "Push", disabled: false, kind: "run_action", action: "commit_push" }; + return { + label: "Push", + disabled: false, + kind: "run_action", + action: isDefaultBranch ? "commit_push" : "push", + }; } return { label: "Push & create PR", disabled: false, kind: "run_action", - action: "commit_push_pr", + action: "create_pr", }; } @@ -306,7 +281,12 @@ export function requiresDefaultBranchConfirmation( isDefaultBranch: boolean, ): boolean { if (!isDefaultBranch) return false; - return action === "commit_push" || action === "commit_push_pr"; + return ( + action === "push" || + action === "create_pr" || + action === "commit_push" || + action === "commit_push_pr" + ); } export function resolveDefaultBranchActionDialogCopy(input: { @@ -317,7 +297,7 @@ export function resolveDefaultBranchActionDialogCopy(input: { const branchLabel = input.branchName; const suffix = ` on "${branchLabel}". You can continue on this branch or create a feature branch and run the same action there.`; - if (input.action === "commit_push") { + if (input.action === "push" || input.action === "commit_push") { if (input.includesCommit) { return { title: "Commit & push to default branch?", @@ -346,5 +326,38 @@ export function resolveDefaultBranchActionDialogCopy(input: { }; } +export function resolveThreadBranchUpdate( + result: GitRunStackedActionResult, +): { branch: string } | null { + if (result.branch.status !== "created" || !result.branch.name) { + return null; + } + + return { + branch: result.branch.name, + }; +} + +export function resolveLiveThreadBranchUpdate(input: { + threadBranch: string | null; + gitStatus: GitStatusResult | null; +}): { branch: string | null } | null { + if (!input.gitStatus) { + return null; + } + + if (input.gitStatus.branch === null && input.threadBranch !== null) { + return null; + } + + if (input.threadBranch === input.gitStatus.branch) { + return null; + } + + return { + branch: input.gitStatus.branch, + }; +} + // Re-export from shared for backwards compatibility in this module's exports export { resolveAutoFeatureBranchName } from "@t3tools/shared/git"; diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index 1593a151da..6d2312e4aa 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -1,10 +1,11 @@ +import { type ScopedThreadRef } from "@t3tools/contracts"; import type { GitActionProgressEvent, + GitRunStackedActionResult, GitStackedAction, GitStatusResult, - ThreadId, } from "@t3tools/contracts"; -import { useIsMutating, useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useIsMutating, useMutation, useQueryClient } from "@tanstack/react-query"; import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react"; import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react"; import { GitHubIcon } from "./Icons"; @@ -17,8 +18,9 @@ import { type DefaultBranchConfirmableAction, requiresDefaultBranchConfirmation, resolveDefaultBranchActionDialogCopy, + resolveLiveThreadBranchUpdate, resolveQuickAction, - summarizeGitResult, + resolveThreadBranchUpdate, } from "./GitActionsControl.logic"; import { Button } from "~/components/ui/button"; import { Checkbox } from "~/components/ui/checkbox"; @@ -36,24 +38,27 @@ import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu"; import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover"; import { ScrollArea } from "~/components/ui/scroll-area"; import { Textarea } from "~/components/ui/textarea"; -import { toastManager } from "~/components/ui/toast"; +import { toastManager, type ThreadToastData } from "~/components/ui/toast"; import { openInPreferredEditor } from "~/editorPreferences"; import { - gitBranchesQueryOptions, gitInitMutationOptions, gitMutationKeys, gitPullMutationOptions, gitRunStackedActionMutationOptions, - gitStatusQueryOptions, - invalidateGitQueries, } from "~/lib/gitReactQuery"; -import { randomUUID } from "~/lib/utils"; +import { refreshGitStatus, useGitStatus } from "~/lib/gitStatusState"; +import { newCommandId, randomUUID } from "~/lib/utils"; import { resolvePathLinkTarget } from "~/terminal-links"; -import { readNativeApi } from "~/nativeApi"; +import { type DraftId, useComposerDraftStore } from "~/composerDraftStore"; +import { readEnvironmentApi } from "~/environmentApi"; +import { readLocalApi } from "~/localApi"; +import { useStore } from "~/store"; +import { createThreadSelectorByRef } from "~/storeSelectors"; interface GitActionsControlProps { gitCwd: string | null; - activeThreadId: ThreadId | null; + activeThreadRef: ScopedThreadRef | null; + draftId?: DraftId; } interface PendingDefaultBranchAction { @@ -61,7 +66,6 @@ interface PendingDefaultBranchAction { branchName: string; includesCommit: boolean; commitMessage?: string; - forcePushOnlyProgress: boolean; onConfirmed?: () => void; filePaths?: string[]; } @@ -70,6 +74,7 @@ type GitActionToastId = ReturnType; interface ActiveGitActionProgress { toastId: GitActionToastId; + toastData: ThreadToastData | undefined; actionId: string; title: string; phaseStartedAtMs: number | null; @@ -82,16 +87,16 @@ interface ActiveGitActionProgress { interface RunGitActionWithToastInput { action: GitStackedAction; commitMessage?: string; - forcePushOnlyProgress?: boolean; onConfirmed?: () => void; skipDefaultBranchPrompt?: boolean; statusOverride?: GitStatusResult | null; featureBranch?: boolean; - isDefaultBranchOverride?: boolean; progressToastId?: GitActionToastId; filePaths?: string[]; } +const GIT_STATUS_WINDOW_REFRESH_DEBOUNCE_MS = 250; + function formatElapsedDescription(startedAtMs: number | null): string | undefined { if (startedAtMs === null) { return undefined; @@ -196,18 +201,39 @@ function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) { if (quickAction.kind === "run_pull") return ; if (quickAction.kind === "run_action") { if (quickAction.action === "commit") return ; - if (quickAction.action === "commit_push") return ; + if (quickAction.action === "push" || quickAction.action === "commit_push") { + return ; + } return ; } if (quickAction.label === "Commit") return ; return ; } -export default function GitActionsControl({ gitCwd, activeThreadId }: GitActionsControlProps) { +export default function GitActionsControl({ + gitCwd, + activeThreadRef, + draftId, +}: GitActionsControlProps) { + const activeEnvironmentId = activeThreadRef?.environmentId ?? null; const threadToastData = useMemo( - () => (activeThreadId ? { threadId: activeThreadId } : undefined), - [activeThreadId], + () => (activeThreadRef ? { threadRef: activeThreadRef } : undefined), + [activeThreadRef], ); + const activeServerThreadSelector = useMemo( + () => createThreadSelectorByRef(activeThreadRef), + [activeThreadRef], + ); + const activeServerThread = useStore(activeServerThreadSelector); + const activeDraftThread = useComposerDraftStore((store) => + draftId + ? store.getDraftSession(draftId) + : activeThreadRef + ? store.getDraftThreadByRef(activeThreadRef) + : null, + ); + const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); + const setThreadBranch = useStore((store) => store.setThreadBranch); const queryClient = useQueryClient(); const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false); const [dialogCommitMessage, setDialogCommitMessage] = useState(""); @@ -216,6 +242,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions const [pendingDefaultBranchAction, setPendingDefaultBranchAction] = useState(null); const activeGitActionProgressRef = useRef(null); + let runGitActionWithToast: (input: RunGitActionWithToastInput) => Promise; const updateActiveProgressToast = useCallback(() => { const progress = activeGitActionProgressRef.current; @@ -227,52 +254,137 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions title: progress.title, description: resolveProgressDescription(progress), timeout: 0, - data: threadToastData, + data: progress.toastData, }); - }, [threadToastData]); + }, []); - const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd)); + const persistThreadBranchSync = useCallback( + (branch: string | null) => { + if (!activeThreadRef) { + return; + } - const { data: branchList = null } = useQuery(gitBranchesQueryOptions(gitCwd)); + if (activeServerThread) { + if (activeServerThread.branch === branch) { + return; + } + + const worktreePath = activeServerThread.worktreePath; + const api = readEnvironmentApi(activeThreadRef.environmentId); + if (api) { + void api.orchestration + .dispatchCommand({ + type: "thread.meta.update", + commandId: newCommandId(), + threadId: activeThreadRef.threadId, + branch, + worktreePath, + }) + .catch(() => undefined); + } + + setThreadBranch(activeThreadRef, branch, worktreePath); + return; + } + + if (!activeDraftThread || activeDraftThread.branch === branch) { + return; + } + + setDraftThreadContext(draftId ?? activeThreadRef, { + branch, + worktreePath: activeDraftThread.worktreePath, + }); + }, + [ + activeDraftThread, + activeServerThread, + activeThreadRef, + draftId, + setDraftThreadContext, + setThreadBranch, + ], + ); + + const syncThreadBranchAfterGitAction = useCallback( + (result: GitRunStackedActionResult) => { + const branchUpdate = resolveThreadBranchUpdate(result); + if (!branchUpdate) { + return; + } + + persistThreadBranchSync(branchUpdate.branch); + }, + [persistThreadBranchSync], + ); + + const { data: gitStatus = null, error: gitStatusError } = useGitStatus({ + environmentId: activeEnvironmentId, + cwd: gitCwd, + }); // Default to true while loading so we don't flash init controls. - const isRepo = branchList?.isRepo ?? true; - const hasOriginRemote = branchList?.hasOriginRemote ?? false; - const currentBranch = branchList?.branches.find((branch) => branch.current)?.name ?? null; - const isGitStatusOutOfSync = - !!gitStatus?.branch && !!currentBranch && gitStatus.branch !== currentBranch; - - useEffect(() => { - if (!isGitStatusOutOfSync) return; - void invalidateGitQueries(queryClient); - }, [isGitStatusOutOfSync, queryClient]); - - const gitStatusForActions = isGitStatusOutOfSync ? null : gitStatus; + const isRepo = gitStatus?.isRepo ?? true; + const hasOriginRemote = gitStatus?.hasOriginRemote ?? false; + const gitStatusForActions = gitStatus; const allFiles = gitStatusForActions?.workingTree.files ?? []; const selectedFiles = allFiles.filter((f) => !excludedFiles.has(f.path)); const allSelected = excludedFiles.size === 0; const noneSelected = selectedFiles.length === 0; - const initMutation = useMutation(gitInitMutationOptions({ cwd: gitCwd, queryClient })); + const initMutation = useMutation( + gitInitMutationOptions({ environmentId: activeEnvironmentId, cwd: gitCwd, queryClient }), + ); const runImmediateGitActionMutation = useMutation( gitRunStackedActionMutationOptions({ + environmentId: activeEnvironmentId, cwd: gitCwd, queryClient, }), ); - const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient })); + const pullMutation = useMutation( + gitPullMutationOptions({ environmentId: activeEnvironmentId, cwd: gitCwd, queryClient }), + ); const isRunStackedActionRunning = - useIsMutating({ mutationKey: gitMutationKeys.runStackedAction(gitCwd) }) > 0; - const isPullRunning = useIsMutating({ mutationKey: gitMutationKeys.pull(gitCwd) }) > 0; + useIsMutating({ + mutationKey: gitMutationKeys.runStackedAction(activeEnvironmentId, gitCwd), + }) > 0; + const isPullRunning = + useIsMutating({ mutationKey: gitMutationKeys.pull(activeEnvironmentId, gitCwd) }) > 0; const isGitActionRunning = isRunStackedActionRunning || isPullRunning; + const isSelectingWorktreeBase = + !activeServerThread && + activeDraftThread?.envMode === "worktree" && + activeDraftThread.worktreePath === null; + + useEffect(() => { + if (isGitActionRunning || isSelectingWorktreeBase) { + return; + } + + const branchUpdate = resolveLiveThreadBranchUpdate({ + threadBranch: activeServerThread?.branch ?? activeDraftThread?.branch ?? null, + gitStatus: gitStatusForActions, + }); + if (!branchUpdate) { + return; + } + + persistThreadBranchSync(branchUpdate.branch); + }, [ + activeServerThread?.branch, + activeDraftThread?.branch, + gitStatusForActions, + isGitActionRunning, + isSelectingWorktreeBase, + persistThreadBranchSync, + ]); + const isDefaultBranch = useMemo(() => { - const branchName = gitStatusForActions?.branch; - if (!branchName) return false; - const current = branchList?.branches.find((branch) => branch.name === branchName); - return current?.isDefault ?? (branchName === "main" || branchName === "master"); - }, [branchList?.branches, gitStatusForActions?.branch]); + return gitStatusForActions?.isDefaultBranch ?? false; + }, [gitStatusForActions?.isDefaultBranch]); const gitActionMenuItems = useMemo( () => buildMenuItems(gitStatusForActions, isGitActionRunning, hasOriginRemote), @@ -294,74 +406,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) { @@ -375,8 +419,43 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions }; }, [updateActiveProgressToast]); + useEffect(() => { + if (gitCwd === null) { + return; + } + + let refreshTimeout: number | null = null; + const scheduleRefreshCurrentGitStatus = () => { + if (refreshTimeout !== null) { + window.clearTimeout(refreshTimeout); + } + refreshTimeout = window.setTimeout(() => { + refreshTimeout = null; + void refreshGitStatus({ environmentId: activeEnvironmentId, cwd: gitCwd }).catch( + () => undefined, + ); + }, GIT_STATUS_WINDOW_REFRESH_DEBOUNCE_MS); + }; + const handleVisibilityChange = () => { + if (document.visibilityState === "visible") { + scheduleRefreshCurrentGitStatus(); + } + }; + + window.addEventListener("focus", scheduleRefreshCurrentGitStatus); + document.addEventListener("visibilitychange", handleVisibilityChange); + + return () => { + if (refreshTimeout !== null) { + window.clearTimeout(refreshTimeout); + } + window.removeEventListener("focus", scheduleRefreshCurrentGitStatus); + document.removeEventListener("visibilitychange", handleVisibilityChange); + }; + }, [activeEnvironmentId, gitCwd]); + const openExistingPr = useCallback(async () => { - const api = readNativeApi(); + const api = readLocalApi(); if (!api) { toastManager.add({ type: "error", @@ -394,7 +473,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions }); return; } - void api.shell.openExternal(prUrl).catch((err) => { + void api.shell.openExternal(prUrl).catch((err: unknown) => { toastManager.add({ type: "error", title: "Unable to open PR link", @@ -404,31 +483,36 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions }); }, [gitStatusForActions, threadToastData]); - const runGitActionWithToast = useEffectEvent( + runGitActionWithToast = useEffectEvent( async ({ action, commitMessage, - forcePushOnlyProgress = false, onConfirmed, skipDefaultBranchPrompt = false, statusOverride, featureBranch = false, - isDefaultBranchOverride, progressToastId, filePaths, }: RunGitActionWithToastInput) => { const actionStatus = statusOverride ?? gitStatusForActions; const actionBranch = actionStatus?.branch ?? null; - const actionIsDefaultBranch = - isDefaultBranchOverride ?? (featureBranch ? false : isDefaultBranch); + const actionIsDefaultBranch = featureBranch ? false : isDefaultBranch; + const actionCanCommit = + action === "commit" || action === "commit_push" || action === "commit_push_pr"; const includesCommit = - !forcePushOnlyProgress && (action === "commit" || !!actionStatus?.hasWorkingTreeChanges); + actionCanCommit && + (action === "commit" || !!actionStatus?.hasWorkingTreeChanges || featureBranch); if ( !skipDefaultBranchPrompt && requiresDefaultBranchConfirmation(action, actionIsDefaultBranch) && actionBranch ) { - if (action !== "commit_push" && action !== "commit_push_pr") { + if ( + action !== "push" && + action !== "create_pr" && + action !== "commit_push" && + action !== "commit_push_pr" + ) { return; } setPendingDefaultBranchAction({ @@ -436,7 +520,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions branchName: actionBranch, includesCommit, ...(commitMessage ? { commitMessage } : {}), - forcePushOnlyProgress, ...(onConfirmed ? { onConfirmed } : {}), ...(filePaths ? { filePaths } : {}), }); @@ -448,9 +531,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions action, hasCustomCommitMessage: !!commitMessage?.trim(), hasWorkingTreeChanges: !!actionStatus?.hasWorkingTreeChanges, - forcePushOnly: forcePushOnlyProgress, featureBranch, + shouldPushBeforePr: + action === "create_pr" && + (!actionStatus?.hasUpstream || (actionStatus?.aheadCount ?? 0) > 0), }); + const scopedToastData = threadToastData ? { ...threadToastData } : undefined; const actionId = randomUUID(); const resolvedProgressToastId = progressToastId ?? @@ -459,11 +545,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions title: progressStages[0] ?? "Running git action...", description: "Waiting for Git...", timeout: 0, - data: threadToastData, + data: scopedToastData, }); activeGitActionProgressRef.current = { toastId: resolvedProgressToastId, + toastData: scopedToastData, actionId, title: progressStages[0] ?? "Running git action...", phaseStartedAtMs: null, @@ -479,139 +566,169 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions title: progressStages[0] ?? "Running git action...", description: "Waiting for Git...", timeout: 0, - data: threadToastData, + data: scopedToastData, }); } + 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 { const result = await promise; activeGitActionProgressRef.current = null; - const resultToast = summarizeGitResult(result); - - const existingOpenPrUrl = - actionStatus?.pr?.state === "open" ? actionStatus.pr.url : undefined; - const prUrl = result.pr.url ?? existingOpenPrUrl; - const shouldOfferPushCta = action === "commit" && result.commit.status === "created"; - const shouldOfferOpenPrCta = - (action === "commit_push" || action === "commit_push_pr") && - !!prUrl && - (!actionIsDefaultBranch || - result.pr.status === "created" || - result.pr.status === "opened_existing"); - const shouldOfferCreatePrCta = - action === "commit_push" && - !prUrl && - result.push.status === "pushed" && - !actionIsDefaultBranch; + syncThreadBranchAfterGitAction(result); const closeResultToast = () => { toastManager.close(resolvedProgressToastId); }; - toastManager.update(resolvedProgressToastId, { + const toastCta = result.toast.cta; + let toastActionProps: { + children: string; + onClick: () => void; + } | null = null; + if (toastCta.kind === "run_action") { + toastActionProps = { + children: toastCta.label, + onClick: () => { + closeResultToast(); + void runGitActionWithToast({ + action: toastCta.action.kind, + }); + }, + }; + } else if (toastCta.kind === "open_pr") { + toastActionProps = { + children: toastCta.label, + onClick: () => { + const api = readLocalApi(); + if (!api) return; + closeResultToast(); + void api.shell.openExternal(toastCta.url); + }, + }; + } + + const successToastBase = { type: "success", - title: resultToast.title, - description: resultToast.description, + title: result.toast.title, + description: result.toast.description, timeout: 0, data: { - ...threadToastData, + ...scopedToastData, dismissAfterVisibleMs: 10_000, }, - ...(shouldOfferPushCta - ? { - actionProps: { - children: "Push", - onClick: () => { - void runGitActionWithToast({ - action: "commit_push", - forcePushOnlyProgress: true, - onConfirmed: closeResultToast, - statusOverride: actionStatus, - isDefaultBranchOverride: actionIsDefaultBranch, - }); - }, - }, - } - : shouldOfferOpenPrCta - ? { - actionProps: { - children: "View PR", - onClick: () => { - const api = readNativeApi(); - if (!api) return; - closeResultToast(); - void api.shell.openExternal(prUrl); - }, - }, - } - : shouldOfferCreatePrCta - ? { - actionProps: { - children: "Create PR", - onClick: () => { - closeResultToast(); - void runGitActionWithToast({ - action: "commit_push_pr", - forcePushOnlyProgress: true, - statusOverride: actionStatus, - isDefaultBranchOverride: actionIsDefaultBranch, - }); - }, - }, - } - : {}), - }); + } as const; + + if (toastActionProps) { + toastManager.update(resolvedProgressToastId, { + ...successToastBase, + actionProps: toastActionProps, + }); + } else { + toastManager.update(resolvedProgressToastId, successToastBase); + } } catch (err) { activeGitActionProgressRef.current = null; toastManager.update(resolvedProgressToastId, { type: "error", title: "Action failed", description: err instanceof Error ? err.message : "An error occurred.", - data: threadToastData, + data: scopedToastData, }); } }, ); - const continuePendingDefaultBranchAction = useCallback(() => { + const continuePendingDefaultBranchAction = () => { if (!pendingDefaultBranchAction) return; - const { action, commitMessage, forcePushOnlyProgress, onConfirmed, filePaths } = - pendingDefaultBranchAction; + const { action, commitMessage, onConfirmed, filePaths } = pendingDefaultBranchAction; setPendingDefaultBranchAction(null); void runGitActionWithToast({ action, ...(commitMessage ? { commitMessage } : {}), - forcePushOnlyProgress, ...(onConfirmed ? { onConfirmed } : {}), ...(filePaths ? { filePaths } : {}), skipDefaultBranchPrompt: true, }); - }, [pendingDefaultBranchAction]); + }; - const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => { + const checkoutFeatureBranchAndContinuePendingAction = () => { if (!pendingDefaultBranchAction) return; - const { action, commitMessage, forcePushOnlyProgress, onConfirmed, filePaths } = - pendingDefaultBranchAction; + const { action, commitMessage, onConfirmed, filePaths } = pendingDefaultBranchAction; setPendingDefaultBranchAction(null); void runGitActionWithToast({ action, ...(commitMessage ? { commitMessage } : {}), - forcePushOnlyProgress, ...(onConfirmed ? { onConfirmed } : {}), ...(filePaths ? { filePaths } : {}), featureBranch: true, skipDefaultBranchPrompt: true, }); - }, [pendingDefaultBranchAction]); + }; - const runDialogActionOnNewBranch = useCallback(() => { + const runDialogActionOnNewBranch = () => { if (!isCommitDialogOpen) return; const commitMessage = dialogCommitMessage.trim(); @@ -627,9 +744,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions featureBranch: true, skipDefaultBranchPrompt: true, }); - }, [allSelected, isCommitDialogOpen, dialogCommitMessage, selectedFiles]); + }; - const runQuickAction = useCallback(() => { + const runQuickAction = () => { if (quickAction.kind === "open_pr") { void openExistingPr(); return; @@ -667,31 +784,28 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions if (quickAction.action) { void runGitActionWithToast({ action: quickAction.action }); } - }, [openExistingPr, pullMutation, quickAction, threadToastData]); + }; - const openDialogForMenuItem = useCallback( - (item: GitActionMenuItem) => { - if (item.disabled) return; - if (item.kind === "open_pr") { - void openExistingPr(); - return; - } - if (item.dialogAction === "push") { - void runGitActionWithToast({ action: "commit_push", forcePushOnlyProgress: true }); - return; - } - if (item.dialogAction === "create_pr") { - void runGitActionWithToast({ action: "commit_push_pr" }); - return; - } - setExcludedFiles(new Set()); - setIsEditingFiles(false); - setIsCommitDialogOpen(true); - }, - [openExistingPr, setIsCommitDialogOpen], - ); + const openDialogForMenuItem = (item: GitActionMenuItem) => { + if (item.disabled) return; + if (item.kind === "open_pr") { + void openExistingPr(); + return; + } + if (item.dialogAction === "push") { + void runGitActionWithToast({ action: "push" }); + return; + } + if (item.dialogAction === "create_pr") { + void runGitActionWithToast({ action: "create_pr" }); + return; + } + setExcludedFiles(new Set()); + setIsEditingFiles(false); + setIsCommitDialogOpen(true); + }; - const runDialogAction = useCallback(() => { + const runDialogAction = () => { if (!isCommitDialogOpen) return; const commitMessage = dialogCommitMessage.trim(); setIsCommitDialogOpen(false); @@ -703,18 +817,11 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions ...(commitMessage ? { commitMessage } : {}), ...(!allSelected ? { filePaths: selectedFiles.map((f) => f.path) } : {}), }); - }, [ - allSelected, - dialogCommitMessage, - isCommitDialogOpen, - selectedFiles, - setDialogCommitMessage, - setIsCommitDialogOpen, - ]); + }; const openChangedFileInEditor = useCallback( (filePath: string) => { - const api = readNativeApi(); + const api = readLocalApi(); if (!api || !gitCwd) { toastManager.add({ type: "error", @@ -789,7 +896,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions { - if (open) void invalidateGitQueries(queryClient); + if (open) { + void refreshGitStatus({ + environmentId: activeEnvironmentId, + cwd: gitCwd, + }).catch(() => undefined); + } }} > )} - {isGitStatusOutOfSync && ( -

- Refreshing git status... -

- )} {gitStatusError && (

{gitStatusError.message}

)} diff --git a/apps/web/src/components/Icons.tsx b/apps/web/src/components/Icons.tsx index 7d210fa173..37a47bb01b 100644 --- a/apps/web/src/components/Icons.tsx +++ b/apps/web/src/components/Icons.tsx @@ -20,6 +20,20 @@ export const CursorIcon: Icon = (props) => ( ); +export const TraeIcon: Icon = (props) => ( + + {/* Back rectangle: left strip + bottom strip drawn separately — empty bottom-left corner is the gap between them */} + + + {/* Front frame: top bar + right bar only — left and bottom are replaced by the back strips above */} + + + {/* Two diamonds, offset slightly to the right within the open area */} + + + +); + export const VisualStudioCode: Icon = (props) => { const id = useId(); const maskId = `${id}-vscode-a`; @@ -114,6 +128,127 @@ export const VisualStudioCode: Icon = (props) => { ); }; +export const VisualStudioCodeInsiders: Icon = (props) => { + const id = useId(); + const maskId = `${id}-vscode-insiders-a`; + const topShadowFilterId = `${id}-vscode-insiders-b`; + const sideShadowFilterId = `${id}-vscode-insiders-c`; + const overlayGradientId = `${id}-vscode-insiders-d`; + + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ); +}; + +export const VSCodium: Icon = (props) => { + const id = useId(); + const gradientId = `${id}-vscodium-gradient`; + + return ( + + + + + + + + + + ); +}; + export const Zed: Icon = (props) => { const id = useId(); const clipPathId = `${id}-zed-logo-a`; @@ -296,6 +431,107 @@ export const AntigravityIcon: Icon = (props) => ( ); +export const IntelliJIdeaIcon: Icon = (props) => { + const id = useId(); + const gradientAId = `${id}-idea-a`; + const gradientBId = `${id}-idea-b`; + const gradientCId = `${id}-idea-c`; + const gradientDId = `${id}-idea-d`; + + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ); +}; + export const OpenCodeIcon: Icon = (props) => ( diff --git a/apps/web/src/components/KeybindingsToast.browser.tsx b/apps/web/src/components/KeybindingsToast.browser.tsx index 224bd2f887..223f5d8ebd 100644 --- a/apps/web/src/components/KeybindingsToast.browser.tsx +++ b/apps/web/src/components/KeybindingsToast.browser.tsx @@ -1,14 +1,15 @@ import "../index.css"; import { + DEFAULT_SERVER_SETTINGS, + EnvironmentId, ORCHESTRATION_WS_METHODS, type MessageId, 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,27 +19,53 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } import { render } from "vitest-browser-react"; import { useComposerDraftStore } from "../composerDraftStore"; +import { __resetLocalApiForTests } from "../localApi"; +import { AppAtomRegistryProvider } from "../rpc/atomRegistry"; +import { getServerConfig, getServerConfigUpdatedNotification } from "../rpc/serverState"; +import { getWsConnectionStatus } from "../rpc/wsConnectionState"; import { getRouter } from "../router"; import { useStore } from "../store"; +import { createAuthenticatedSessionHandlers } from "../../test/authHttpHandlers"; +import { BrowserWsRpcHarness } from "../../test/wsRpcHarness"; + +vi.mock("../lib/gitStatusState", () => ({ + useGitStatus: () => ({ data: null, error: null, cause: null, isPending: false }), + useGitStatuses: () => new Map(), + refreshGitStatus: () => Promise.resolve(null), + resetGitStatusStateForTests: () => undefined, +})); const THREAD_ID = "thread-kb-toast-test" as ThreadId; const PROJECT_ID = "project-1" as ProjectId; +const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local"); 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)?:\/\/.*/); function createBaseServerConfig(): ServerConfig { return { + environment: { + environmentId: LOCAL_ENVIRONMENT_ID, + label: "Local environment", + platform: { os: "darwin" as const, arch: "arm64" as const }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, + }, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie", "bearer-session-token"], + sessionCookieName: "t3_session", + }, cwd: "/repo/project", keybindingsConfigPath: "/repo/project/.t3code-keybindings.json", keybindings: [], @@ -53,10 +80,19 @@ function createBaseServerConfig(): ServerConfig { auth: { status: "authenticated" }, checkedAt: NOW_ISO, models: [], + slashCommands: [], + skills: [], }, ], availableEditors: [], + observability: { + logsDirectoryPath: "/repo/project/.t3/logs", + localTracingEnabled: true, + otlpTracesEnabled: false, + otlpMetricsEnabled: false, + }, settings: { + ...DEFAULT_SERVER_SETTINGS, enableAssistantStreaming: false, defaultThreadEnvMode: "local" as const, textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" }, @@ -138,6 +174,13 @@ function buildFixture(): TestFixture { snapshot: createMinimalSnapshot(), serverConfig: createBaseServerConfig(), welcome: { + environment: { + environmentId: LOCAL_ENVIRONMENT_ID, + label: "Local environment", + platform: { os: "darwin" as const, arch: "arm64" as const }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, + }, cwd: "/repo/project", projectName: "Project", bootstrapProjectId: PROJECT_ID, @@ -157,20 +200,11 @@ function resolveWsRpc(tag: string): unknown { return { isRepo: true, hasOriginRemote: true, + nextCursor: null, + totalCount: 1, branches: [{ name: "main", current: true, isDefault: true, worktreePath: null }], }; } - if (tag === WS_METHODS.gitStatus) { - return { - branch: "main", - hasWorkingTreeChanges: false, - workingTree: { files: [], insertions: 0, deletions: 0 }, - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }; - } if (tag === WS_METHODS.projectsSearchEntries) { return { entries: [], truncated: false }; } @@ -179,52 +213,24 @@ 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); }); }), + ...createAuthenticatedSessionHandlers(() => fixture.serverConfig.auth), 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[] { @@ -255,6 +261,22 @@ async function waitForComposerEditor(): Promise { ); } +async function waitForToastViewport(): Promise { + return waitForElement( + () => document.querySelector('[data-slot="toast-viewport"]'), + "App should render the toast viewport before server config updates are pushed", + ); +} + +async function waitForWsConnection(): Promise { + await vi.waitFor( + () => { + expect(getWsConnectionStatus().phase).toBe("connected"); + }, + { timeout: 8_000, interval: 16 }, + ); +} + async function waitForToast(title: string, count = 1): Promise { await vi.waitFor( () => { @@ -274,6 +296,65 @@ async function waitForNoToast(title: string): Promise { ); } +async function waitForNoToasts(): Promise { + await vi.waitFor( + () => { + expect(queryToastTitles()).toHaveLength(0); + }, + { timeout: 8_000, interval: 16 }, + ); +} + +async function waitForInitialWsSubscriptions(): Promise { + await vi.waitFor( + () => { + expect( + rpcHarness.requests.some((request) => request._tag === WS_METHODS.subscribeServerLifecycle), + ).toBe(true); + expect( + rpcHarness.requests.some((request) => request._tag === WS_METHODS.subscribeServerConfig), + ).toBe(true); + }, + { timeout: 8_000, interval: 16 }, + ); +} + +async function waitForServerConfigSnapshot(): Promise { + await vi.waitFor( + () => { + expect(getServerConfig()).not.toBeNull(); + }, + { timeout: 8_000, interval: 16 }, + ); +} + +async function waitForServerConfigStreamReady(): Promise { + const previousNotificationId = getServerConfigUpdatedNotification()?.id ?? 0; + for (let attempt = 0; attempt < 20; attempt += 1) { + rpcHarness.emitStreamValue(WS_METHODS.subscribeServerConfig, { + version: 1, + type: "settingsUpdated", + payload: { settings: fixture.serverConfig.settings }, + }); + + try { + await vi.waitFor( + () => { + const notification = getServerConfigUpdatedNotification(); + expect(notification?.id).toBeGreaterThan(previousNotificationId); + expect(notification?.source).toBe("settingsUpdated"); + }, + { timeout: 200, interval: 16 }, + ); + return; + } catch { + await new Promise((resolve) => setTimeout(resolve, 25)); + } + } + + throw new Error("Timed out waiting for the server config stream to deliver updates."); +} + async function mountApp(): Promise<{ cleanup: () => Promise }> { const host = document.createElement("div"); host.style.position = "fixed"; @@ -284,10 +365,23 @@ async function mountApp(): Promise<{ cleanup: () => Promise }> { host.style.overflow = "hidden"; document.body.append(host); - const router = getRouter(createMemoryHistory({ initialEntries: [`/${THREAD_ID}`] })); + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${LOCAL_ENVIRONMENT_ID}/${THREAD_ID}`] }), + ); - const screen = await render(, { container: host }); + const screen = await render( + + + , + { container: host }, + ); await waitForComposerEditor(); + await waitForToastViewport(); + await waitForInitialWsSubscriptions(); + await waitForWsConnection(); + await waitForServerConfigSnapshot(); + await waitForServerConfigStreamReady(); + await waitForNoToasts(); return { cleanup: async () => { @@ -308,22 +402,47 @@ 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 []; + }, + }); + await __resetLocalApiForTests(); localStorage.clear(); document.body.innerHTML = ""; - pushSequence = 1; useComposerDraftStore.setState({ - draftsByThreadId: {}, - draftThreadsByThreadId: {}, - projectDraftThreadIdByProjectId: {}, + draftsByThreadKey: {}, + draftThreadsByThreadKey: {}, + logicalProjectDraftThreadKeyByLogicalProjectKey: {}, }); useStore.setState({ - projects: [], - threads: [], - bootstrapComplete: false, + activeEnvironmentId: null, + environmentStateById: {}, }); }); diff --git a/apps/web/src/components/NoActiveThreadState.tsx b/apps/web/src/components/NoActiveThreadState.tsx new file mode 100644 index 0000000000..39aa4e2f72 --- /dev/null +++ b/apps/web/src/components/NoActiveThreadState.tsx @@ -0,0 +1,41 @@ +import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "./ui/empty"; +import { SidebarInset, SidebarTrigger } from "./ui/sidebar"; +import { isElectron } from "../env"; +import { cn } from "~/lib/utils"; + +export function NoActiveThreadState() { + return ( + +
+
+ {isElectron ? ( + No active thread + ) : ( +
+ + + No active thread + +
+ )} +
+ + +
+ + Pick a thread to continue + + Select an existing thread or create a new one to get started. + + +
+
+
+ + ); +} diff --git a/apps/web/src/components/PlanSidebar.tsx b/apps/web/src/components/PlanSidebar.tsx index 01341dc803..134ca2e6f3 100644 --- a/apps/web/src/components/PlanSidebar.tsx +++ b/apps/web/src/components/PlanSidebar.tsx @@ -1,4 +1,5 @@ import { memo, useState, useCallback } from "react"; +import type { EnvironmentId } from "@t3tools/contracts"; import { type TimestampFormat } from "@t3tools/contracts/settings"; import { Badge } from "./ui/badge"; import { Button } from "./ui/button"; @@ -24,7 +25,7 @@ import { stripDisplayedPlanMarkdown, } from "../proposedPlan"; import { Menu, MenuItem, MenuPopup, MenuTrigger } from "./ui/menu"; -import { readNativeApi } from "~/nativeApi"; +import { readEnvironmentApi } from "~/environmentApi"; import { toastManager } from "./ui/toast"; import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; @@ -53,6 +54,7 @@ function stepStatusIcon(status: string): React.ReactNode { interface PlanSidebarProps { activePlan: ActivePlanState | null; activeProposedPlan: LatestProposedPlanState | null; + environmentId: EnvironmentId; markdownCwd: string | undefined; workspaceRoot: string | undefined; timestampFormat: TimestampFormat; @@ -62,6 +64,7 @@ interface PlanSidebarProps { const PlanSidebar = memo(function PlanSidebar({ activePlan, activeProposedPlan, + environmentId, markdownCwd, workspaceRoot, timestampFormat, @@ -87,7 +90,7 @@ const PlanSidebar = memo(function PlanSidebar({ }, [planMarkdown]); const handleSaveToWorkspace = useCallback(() => { - const api = readNativeApi(); + const api = readEnvironmentApi(environmentId); if (!api || !workspaceRoot || !planMarkdown) return; const filename = buildProposedPlanMarkdownFilename(planMarkdown); setIsSavingToWorkspace(true); @@ -115,7 +118,7 @@ const PlanSidebar = memo(function PlanSidebar({ () => setIsSavingToWorkspace(false), () => setIsSavingToWorkspace(false), ); - }, [planMarkdown, workspaceRoot]); + }, [environmentId, planMarkdown, workspaceRoot]); return (
diff --git a/apps/web/src/components/ProjectFavicon.tsx b/apps/web/src/components/ProjectFavicon.tsx index bc0118120f..38e07f59ce 100644 --- a/apps/web/src/components/ProjectFavicon.tsx +++ b/apps/web/src/components/ProjectFavicon.tsx @@ -1,30 +1,20 @@ +import type { EnvironmentId } from "@t3tools/contracts"; import { FolderIcon } from "lucide-react"; import { useState } from "react"; - -function getServerHttpOrigin(): string { - const bridgeUrl = window.desktopBridge?.getWsUrl(); - const envUrl = import.meta.env.VITE_WS_URL as string | undefined; - const wsUrl = - bridgeUrl && bridgeUrl.length > 0 - ? bridgeUrl - : envUrl && envUrl.length > 0 - ? envUrl - : `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.hostname}:${window.location.port}`; - // Parse to extract just the origin, dropping path/query (e.g. ?token=…) - const httpUrl = wsUrl.replace(/^wss:/, "https:").replace(/^ws:/, "http:"); - try { - return new URL(httpUrl).origin; - } catch { - return httpUrl; - } -} - -const serverHttpOrigin = getServerHttpOrigin(); +import { resolveEnvironmentHttpUrl } from "../environments/runtime"; const loadedProjectFaviconSrcs = new Set(); -export function ProjectFavicon({ cwd, className }: { cwd: string; className?: string }) { - const src = `${serverHttpOrigin}/api/project-favicon?cwd=${encodeURIComponent(cwd)}`; +export function ProjectFavicon(input: { + environmentId: EnvironmentId; + cwd: string; + className?: string; +}) { + const src = resolveEnvironmentHttpUrl({ + environmentId: input.environmentId, + pathname: "/api/project-favicon", + searchParams: { cwd: input.cwd }, + }); const [status, setStatus] = useState<"loading" | "loaded" | "error">(() => loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading", ); @@ -32,12 +22,14 @@ export function ProjectFavicon({ cwd, className }: { cwd: string; className?: st return ( <> {status !== "loaded" ? ( - + ) : null} { loadedProjectFaviconSrcs.add(src); setStatus("loaded"); diff --git a/apps/web/src/components/PullRequestThreadDialog.tsx b/apps/web/src/components/PullRequestThreadDialog.tsx index 2a69facd10..6c134f95a0 100644 --- a/apps/web/src/components/PullRequestThreadDialog.tsx +++ b/apps/web/src/components/PullRequestThreadDialog.tsx @@ -1,4 +1,4 @@ -import type { GitResolvePullRequestResult } from "@t3tools/contracts"; +import type { EnvironmentId, GitResolvePullRequestResult, ThreadId } from "@t3tools/contracts"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useDebouncedValue } from "@tanstack/react-pacer"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; @@ -24,6 +24,8 @@ import { Spinner } from "./ui/spinner"; interface PullRequestThreadDialogProps { open: boolean; + environmentId: EnvironmentId; + threadId: ThreadId; cwd: string | null; initialReference: string | null; onOpenChange: (open: boolean) => void; @@ -32,6 +34,8 @@ interface PullRequestThreadDialogProps { export function PullRequestThreadDialog({ open, + environmentId, + threadId, cwd, initialReference, onOpenChange, @@ -70,6 +74,7 @@ export function PullRequestThreadDialog({ const parsedDebouncedReference = parsePullRequestReference(debouncedReference); const resolvePullRequestQuery = useQuery( gitResolvePullRequestQueryOptions({ + environmentId, cwd, reference: open ? parsedDebouncedReference : null, }), @@ -81,13 +86,14 @@ export function PullRequestThreadDialog({ const cached = queryClient.getQueryData([ "git", "pull-request", + environmentId, cwd, parsedReference, ]); return cached?.pullRequest ?? null; - }, [cwd, parsedReference, queryClient]); + }, [cwd, environmentId, parsedReference, queryClient]); const preparePullRequestThreadMutation = useMutation( - gitPreparePullRequestThreadMutationOptions({ cwd, queryClient }), + gitPreparePullRequestThreadMutationOptions({ environmentId, cwd, queryClient }), ); const liveResolvedPullRequest = @@ -130,6 +136,7 @@ export function PullRequestThreadDialog({ const result = await preparePullRequestThreadMutation.mutateAsync({ reference: parsedReference, mode, + ...(mode === "worktree" ? { threadId } : {}), }); await onPrepared({ branch: result.branch, @@ -147,6 +154,7 @@ export function PullRequestThreadDialog({ parsedReference, preparePullRequestThreadMutation, resolvedPullRequest, + threadId, ], ); diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index d4cd25db4c..282d7f9c4d 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -11,6 +11,7 @@ import { isContextMenuPointerDown, orderItemsByPreferredIds, resolveProjectStatusIndicator, + resolveSidebarNewThreadSeedContext, resolveSidebarNewThreadEnvMode, resolveThreadRowClassName, resolveThreadStatusPill, @@ -19,7 +20,7 @@ import { sortThreadsForSidebar, THREAD_JUMP_HINT_SHOW_DELAY_MS, } from "./Sidebar.logic"; -import { OrchestrationLatestTurn, ProjectId, ThreadId } from "@t3tools/contracts"; +import { EnvironmentId, OrchestrationLatestTurn, ProjectId, ThreadId } from "@t3tools/contracts"; import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, @@ -27,6 +28,8 @@ import { type Thread, } from "../types"; +const localEnvironmentId = EnvironmentId.make("environment-local"); + function makeLatestTurn(overrides?: { completedAt?: string | null; startedAt?: string | null; @@ -45,10 +48,12 @@ describe("hasUnseenCompletion", () => { it("returns true when a thread completed after its last visit", () => { expect( hasUnseenCompletion({ + hasActionableProposedPlan: false, + hasPendingApprovals: false, + hasPendingUserInput: false, interactionMode: "default", latestTurn: makeLatestTurn(), lastVisitedAt: "2026-03-09T10:04:00.000Z", - proposedPlans: [], session: null, }), ).toBe(true); @@ -164,46 +169,108 @@ describe("resolveSidebarNewThreadEnvMode", () => { }); }); +describe("resolveSidebarNewThreadSeedContext", () => { + it("inherits the active server thread context when creating a new thread in the same project", () => { + expect( + resolveSidebarNewThreadSeedContext({ + projectId: "project-1", + defaultEnvMode: "local", + activeThread: { + projectId: "project-1", + branch: "effect-atom", + worktreePath: null, + }, + activeDraftThread: null, + }), + ).toEqual({ + branch: "effect-atom", + worktreePath: null, + envMode: "local", + }); + }); + + it("prefers the active draft thread context when it matches the target project", () => { + expect( + resolveSidebarNewThreadSeedContext({ + projectId: "project-1", + defaultEnvMode: "local", + activeThread: { + projectId: "project-1", + branch: "effect-atom", + worktreePath: null, + }, + activeDraftThread: { + projectId: "project-1", + branch: "feature/new-draft", + worktreePath: "/repo/worktree", + envMode: "worktree", + }, + }), + ).toEqual({ + branch: "feature/new-draft", + worktreePath: "/repo/worktree", + envMode: "worktree", + }); + }); + + it("falls back to the default env mode when there is no matching active thread context", () => { + expect( + resolveSidebarNewThreadSeedContext({ + projectId: "project-2", + defaultEnvMode: "worktree", + activeThread: { + projectId: "project-1", + branch: "effect-atom", + worktreePath: null, + }, + activeDraftThread: null, + }), + ).toEqual({ + envMode: "worktree", + }); + }); +}); + 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" }, + { id: ProjectId.make("project-1"), name: "One" }, + { id: ProjectId.make("project-2"), name: "Two" }, + { id: ProjectId.make("project-3"), name: "Three" }, ], preferredIds: [ - ProjectId.makeUnsafe("project-3"), - ProjectId.makeUnsafe("project-missing"), - ProjectId.makeUnsafe("project-1"), + ProjectId.make("project-3"), + ProjectId.make("project-missing"), + ProjectId.make("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"), + ProjectId.make("project-3"), + ProjectId.make("project-1"), + ProjectId.make("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" }, + { id: ProjectId.make("project-1"), name: "One" }, + { id: ProjectId.make("project-2"), name: "Two" }, ], preferredIds: [ - ProjectId.makeUnsafe("project-2"), - ProjectId.makeUnsafe("project-1"), - ProjectId.makeUnsafe("project-2"), + ProjectId.make("project-2"), + ProjectId.make("project-1"), + ProjectId.make("project-2"), ], getId: (project) => project.id, }); expect(ordered.map((project) => project.id)).toEqual([ - ProjectId.makeUnsafe("project-2"), - ProjectId.makeUnsafe("project-1"), + ProjectId.make("project-2"), + ProjectId.make("project-1"), ]); }); }); @@ -211,9 +278,9 @@ describe("orderItemsByPreferredIds", () => { 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"), + ThreadId.make("thread-1"), + ThreadId.make("thread-2"), + ThreadId.make("thread-3"), ]; expect( @@ -259,25 +326,22 @@ describe("getVisibleSidebarThreadIds", () => { expect( getVisibleSidebarThreadIds([ { - renderedThreads: [ - { id: ThreadId.makeUnsafe("thread-12") }, - { id: ThreadId.makeUnsafe("thread-11") }, - { id: ThreadId.makeUnsafe("thread-10") }, + renderedThreadIds: [ + ThreadId.make("thread-12"), + ThreadId.make("thread-11"), + ThreadId.make("thread-10"), ], }, { - renderedThreads: [ - { id: ThreadId.makeUnsafe("thread-8") }, - { id: ThreadId.makeUnsafe("thread-6") }, - ], + renderedThreadIds: [ThreadId.make("thread-8"), ThreadId.make("thread-6")], }, ]), ).toEqual([ - ThreadId.makeUnsafe("thread-12"), - ThreadId.makeUnsafe("thread-11"), - ThreadId.makeUnsafe("thread-10"), - ThreadId.makeUnsafe("thread-8"), - ThreadId.makeUnsafe("thread-6"), + ThreadId.make("thread-12"), + ThreadId.make("thread-11"), + ThreadId.make("thread-10"), + ThreadId.make("thread-8"), + ThreadId.make("thread-6"), ]); }); @@ -286,20 +350,14 @@ describe("getVisibleSidebarThreadIds", () => { getVisibleSidebarThreadIds([ { shouldShowThreadPanel: false, - renderedThreads: [ - { id: ThreadId.makeUnsafe("thread-hidden-2") }, - { id: ThreadId.makeUnsafe("thread-hidden-1") }, - ], + renderedThreadIds: [ThreadId.make("thread-hidden-2"), ThreadId.make("thread-hidden-1")], }, { shouldShowThreadPanel: true, - renderedThreads: [ - { id: ThreadId.makeUnsafe("thread-12") }, - { id: ThreadId.makeUnsafe("thread-11") }, - ], + renderedThreadIds: [ThreadId.make("thread-12"), ThreadId.make("thread-11")], }, ]), - ).toEqual([ThreadId.makeUnsafe("thread-12"), ThreadId.makeUnsafe("thread-11")]); + ).toEqual([ThreadId.make("thread-12"), ThreadId.make("thread-11")]); }); }); @@ -337,10 +395,12 @@ describe("isContextMenuPointerDown", () => { describe("resolveThreadStatusPill", () => { const baseThread = { + hasActionableProposedPlan: false, + hasPendingApprovals: false, + hasPendingUserInput: false, interactionMode: "plan" as const, latestTurn: null, lastVisitedAt: undefined, - proposedPlans: [], session: { provider: "codex" as const, status: "running" as const, @@ -353,9 +413,11 @@ describe("resolveThreadStatusPill", () => { it("shows pending approval before all other statuses", () => { expect( resolveThreadStatusPill({ - thread: baseThread, - hasPendingApprovals: true, - hasPendingUserInput: true, + thread: { + ...baseThread, + hasPendingApprovals: true, + hasPendingUserInput: true, + }, }), ).toMatchObject({ label: "Pending Approval", pulse: false }); }); @@ -363,9 +425,10 @@ describe("resolveThreadStatusPill", () => { it("shows awaiting input when plan mode is blocked on user answers", () => { expect( resolveThreadStatusPill({ - thread: baseThread, - hasPendingApprovals: false, - hasPendingUserInput: true, + thread: { + ...baseThread, + hasPendingUserInput: true, + }, }), ).toMatchObject({ label: "Awaiting Input", pulse: false }); }); @@ -374,8 +437,6 @@ describe("resolveThreadStatusPill", () => { expect( resolveThreadStatusPill({ thread: baseThread, - hasPendingApprovals: false, - hasPendingUserInput: false, }), ).toMatchObject({ label: "Working", pulse: true }); }); @@ -385,26 +446,14 @@ describe("resolveThreadStatusPill", () => { resolveThreadStatusPill({ thread: { ...baseThread, + hasActionableProposedPlan: true, latestTurn: makeLatestTurn(), - proposedPlans: [ - { - id: "plan-1" as never, - turnId: "turn-1" as never, - createdAt: "2026-03-09T10:00:00.000Z", - updatedAt: "2026-03-09T10:05:00.000Z", - planMarkdown: "# Plan", - implementedAt: null, - implementationThreadId: null, - }, - ], session: { ...baseThread.session, status: "ready", orchestrationStatus: "ready", }, }, - hasPendingApprovals: false, - hasPendingUserInput: false, }), ).toMatchObject({ label: "Plan Ready", pulse: false }); }); @@ -415,25 +464,12 @@ describe("resolveThreadStatusPill", () => { thread: { ...baseThread, latestTurn: makeLatestTurn(), - proposedPlans: [ - { - id: "plan-1" as never, - turnId: "turn-1" as never, - createdAt: "2026-03-09T10:00:00.000Z", - updatedAt: "2026-03-09T10:05:00.000Z", - planMarkdown: "# Plan", - implementedAt: "2026-03-09T10:06:00.000Z", - implementationThreadId: "thread-implement" as never, - }, - ], session: { ...baseThread.session, status: "ready", orchestrationStatus: "ready", }, }, - hasPendingApprovals: false, - hasPendingUserInput: false, }), ).toMatchObject({ label: "Completed", pulse: false }); }); @@ -452,8 +488,6 @@ describe("resolveThreadStatusPill", () => { orchestrationStatus: "ready", }, }, - hasPendingApprovals: false, - hasPendingUserInput: false, }), ).toMatchObject({ label: "Completed", pulse: false }); }); @@ -537,43 +571,41 @@ describe("getVisibleThreadsForProject", () => { it("includes the active thread even when it falls below the folded preview", () => { const threads = Array.from({ length: 8 }, (_, index) => makeThread({ - id: ThreadId.makeUnsafe(`thread-${index + 1}`), + id: ThreadId.make(`thread-${index + 1}`), title: `Thread ${index + 1}`, }), ); const result = getVisibleThreadsForProject({ threads, - activeThreadId: ThreadId.makeUnsafe("thread-8"), + activeThreadId: ThreadId.make("thread-8"), isThreadListExpanded: false, previewLimit: 6, }); expect(result.hasHiddenThreads).toBe(true); expect(result.visibleThreads.map((thread) => thread.id)).toEqual([ - ThreadId.makeUnsafe("thread-1"), - ThreadId.makeUnsafe("thread-2"), - ThreadId.makeUnsafe("thread-3"), - ThreadId.makeUnsafe("thread-4"), - ThreadId.makeUnsafe("thread-5"), - ThreadId.makeUnsafe("thread-6"), - ThreadId.makeUnsafe("thread-8"), - ]); - expect(result.hiddenThreads.map((thread) => thread.id)).toEqual([ - ThreadId.makeUnsafe("thread-7"), + ThreadId.make("thread-1"), + ThreadId.make("thread-2"), + ThreadId.make("thread-3"), + ThreadId.make("thread-4"), + ThreadId.make("thread-5"), + ThreadId.make("thread-6"), + ThreadId.make("thread-8"), ]); + expect(result.hiddenThreads.map((thread) => thread.id)).toEqual([ThreadId.make("thread-7")]); }); it("returns all threads when the list is expanded", () => { const threads = Array.from({ length: 8 }, (_, index) => makeThread({ - id: ThreadId.makeUnsafe(`thread-${index + 1}`), + id: ThreadId.make(`thread-${index + 1}`), }), ); const result = getVisibleThreadsForProject({ threads, - activeThreadId: ThreadId.makeUnsafe("thread-8"), + activeThreadId: ThreadId.make("thread-8"), isThreadListExpanded: true, previewLimit: 6, }); @@ -589,7 +621,8 @@ describe("getVisibleThreadsForProject", () => { function makeProject(overrides: Partial = {}): Project { const { defaultModelSelection, ...rest } = overrides; return { - id: ProjectId.makeUnsafe("project-1"), + id: ProjectId.make("project-1"), + environmentId: localEnvironmentId, name: "Project", cwd: "/tmp/project", defaultModelSelection: { @@ -606,9 +639,10 @@ function makeProject(overrides: Partial = {}): Project { function makeThread(overrides: Partial = {}): Thread { return { - id: ThreadId.makeUnsafe("thread-1"), + id: ThreadId.make("thread-1"), + environmentId: localEnvironmentId, codexThreadId: null, - projectId: ProjectId.makeUnsafe("project-1"), + projectId: ProjectId.make("project-1"), title: "Thread", modelSelection: { provider: "codex", @@ -638,7 +672,7 @@ describe("sortThreadsForSidebar", () => { const sorted = sortThreadsForSidebar( [ makeThread({ - id: ThreadId.makeUnsafe("thread-1"), + id: ThreadId.make("thread-1"), createdAt: "2026-03-09T10:00:00.000Z", updatedAt: "2026-03-09T10:10:00.000Z", messages: [ @@ -653,7 +687,7 @@ describe("sortThreadsForSidebar", () => { ], }), makeThread({ - id: ThreadId.makeUnsafe("thread-2"), + id: ThreadId.make("thread-2"), createdAt: "2026-03-09T10:05:00.000Z", updatedAt: "2026-03-09T10:05:00.000Z", messages: [ @@ -672,8 +706,8 @@ describe("sortThreadsForSidebar", () => { ); expect(sorted.map((thread) => thread.id)).toEqual([ - ThreadId.makeUnsafe("thread-2"), - ThreadId.makeUnsafe("thread-1"), + ThreadId.make("thread-2"), + ThreadId.make("thread-1"), ]); }); @@ -681,7 +715,7 @@ describe("sortThreadsForSidebar", () => { const sorted = sortThreadsForSidebar( [ makeThread({ - id: ThreadId.makeUnsafe("thread-1"), + id: ThreadId.make("thread-1"), createdAt: "2026-03-09T10:00:00.000Z", updatedAt: "2026-03-09T10:01:00.000Z", messages: [ @@ -696,7 +730,7 @@ describe("sortThreadsForSidebar", () => { ], }), makeThread({ - id: ThreadId.makeUnsafe("thread-2"), + id: ThreadId.make("thread-2"), createdAt: "2026-03-09T10:05:00.000Z", updatedAt: "2026-03-09T10:05:00.000Z", messages: [], @@ -706,8 +740,8 @@ describe("sortThreadsForSidebar", () => { ); expect(sorted.map((thread) => thread.id)).toEqual([ - ThreadId.makeUnsafe("thread-2"), - ThreadId.makeUnsafe("thread-1"), + ThreadId.make("thread-2"), + ThreadId.make("thread-1"), ]); }); @@ -715,13 +749,13 @@ describe("sortThreadsForSidebar", () => { const sorted = sortThreadsForSidebar( [ makeThread({ - id: ThreadId.makeUnsafe("thread-1"), + id: ThreadId.make("thread-1"), createdAt: "" as never, updatedAt: undefined, messages: [], }), makeThread({ - id: ThreadId.makeUnsafe("thread-2"), + id: ThreadId.make("thread-2"), createdAt: "" as never, updatedAt: undefined, messages: [], @@ -731,8 +765,8 @@ describe("sortThreadsForSidebar", () => { ); expect(sorted.map((thread) => thread.id)).toEqual([ - ThreadId.makeUnsafe("thread-2"), - ThreadId.makeUnsafe("thread-1"), + ThreadId.make("thread-2"), + ThreadId.make("thread-1"), ]); }); @@ -740,12 +774,12 @@ describe("sortThreadsForSidebar", () => { const sorted = sortThreadsForSidebar( [ makeThread({ - id: ThreadId.makeUnsafe("thread-1"), + id: ThreadId.make("thread-1"), createdAt: "2026-03-09T10:05:00.000Z", updatedAt: "2026-03-09T10:05:00.000Z", }), makeThread({ - id: ThreadId.makeUnsafe("thread-2"), + id: ThreadId.make("thread-2"), createdAt: "2026-03-09T10:00:00.000Z", updatedAt: "2026-03-09T10:10:00.000Z", }), @@ -754,8 +788,8 @@ describe("sortThreadsForSidebar", () => { ); expect(sorted.map((thread) => thread.id)).toEqual([ - ThreadId.makeUnsafe("thread-1"), - ThreadId.makeUnsafe("thread-2"), + ThreadId.make("thread-1"), + ThreadId.make("thread-2"), ]); }); }); @@ -765,80 +799,77 @@ describe("getFallbackThreadIdAfterDelete", () => { const fallbackThreadId = getFallbackThreadIdAfterDelete({ threads: [ makeThread({ - id: ThreadId.makeUnsafe("thread-oldest"), - projectId: ProjectId.makeUnsafe("project-1"), + id: ThreadId.make("thread-oldest"), + projectId: ProjectId.make("project-1"), createdAt: "2026-03-09T10:00:00.000Z", messages: [], }), makeThread({ - id: ThreadId.makeUnsafe("thread-active"), - projectId: ProjectId.makeUnsafe("project-1"), + id: ThreadId.make("thread-active"), + projectId: ProjectId.make("project-1"), createdAt: "2026-03-09T10:05:00.000Z", messages: [], }), makeThread({ - id: ThreadId.makeUnsafe("thread-newest"), - projectId: ProjectId.makeUnsafe("project-1"), + id: ThreadId.make("thread-newest"), + projectId: ProjectId.make("project-1"), createdAt: "2026-03-09T10:10:00.000Z", messages: [], }), makeThread({ - id: ThreadId.makeUnsafe("thread-other-project"), - projectId: ProjectId.makeUnsafe("project-2"), + id: ThreadId.make("thread-other-project"), + projectId: ProjectId.make("project-2"), createdAt: "2026-03-09T10:20:00.000Z", messages: [], }), ], - deletedThreadId: ThreadId.makeUnsafe("thread-active"), + deletedThreadId: ThreadId.make("thread-active"), sortOrder: "created_at", }); - expect(fallbackThreadId).toBe(ThreadId.makeUnsafe("thread-newest")); + expect(fallbackThreadId).toBe(ThreadId.make("thread-newest")); }); it("skips other threads being deleted in the same action", () => { const fallbackThreadId = getFallbackThreadIdAfterDelete({ threads: [ makeThread({ - id: ThreadId.makeUnsafe("thread-active"), - projectId: ProjectId.makeUnsafe("project-1"), + id: ThreadId.make("thread-active"), + projectId: ProjectId.make("project-1"), createdAt: "2026-03-09T10:05:00.000Z", messages: [], }), makeThread({ - id: ThreadId.makeUnsafe("thread-newest"), - projectId: ProjectId.makeUnsafe("project-1"), + id: ThreadId.make("thread-newest"), + projectId: ProjectId.make("project-1"), createdAt: "2026-03-09T10:10:00.000Z", messages: [], }), makeThread({ - id: ThreadId.makeUnsafe("thread-next"), - projectId: ProjectId.makeUnsafe("project-1"), + id: ThreadId.make("thread-next"), + projectId: ProjectId.make("project-1"), createdAt: "2026-03-09T10:07:00.000Z", messages: [], }), ], - deletedThreadId: ThreadId.makeUnsafe("thread-active"), - deletedThreadIds: new Set([ - ThreadId.makeUnsafe("thread-active"), - ThreadId.makeUnsafe("thread-newest"), - ]), + deletedThreadId: ThreadId.make("thread-active"), + deletedThreadIds: new Set([ThreadId.make("thread-active"), ThreadId.make("thread-newest")]), sortOrder: "created_at", }); - expect(fallbackThreadId).toBe(ThreadId.makeUnsafe("thread-next")); + expect(fallbackThreadId).toBe(ThreadId.make("thread-next")); }); }); describe("sortProjectsForSidebar", () => { it("sorts projects by the most recent user message across their threads", () => { const projects = [ - makeProject({ id: ProjectId.makeUnsafe("project-1"), name: "Older project" }), - makeProject({ id: ProjectId.makeUnsafe("project-2"), name: "Newer project" }), + makeProject({ id: ProjectId.make("project-1"), name: "Older project" }), + makeProject({ id: ProjectId.make("project-2"), name: "Newer project" }), ]; const threads = [ makeThread({ - projectId: ProjectId.makeUnsafe("project-1"), + projectId: ProjectId.make("project-1"), updatedAt: "2026-03-09T10:20:00.000Z", messages: [ { @@ -852,8 +883,8 @@ describe("sortProjectsForSidebar", () => { ], }), makeThread({ - id: ThreadId.makeUnsafe("thread-2"), - projectId: ProjectId.makeUnsafe("project-2"), + id: ThreadId.make("thread-2"), + projectId: ProjectId.make("project-2"), updatedAt: "2026-03-09T10:05:00.000Z", messages: [ { @@ -871,8 +902,8 @@ describe("sortProjectsForSidebar", () => { const sorted = sortProjectsForSidebar(projects, threads, "updated_at"); expect(sorted.map((project) => project.id)).toEqual([ - ProjectId.makeUnsafe("project-2"), - ProjectId.makeUnsafe("project-1"), + ProjectId.make("project-2"), + ProjectId.make("project-1"), ]); }); @@ -880,12 +911,12 @@ describe("sortProjectsForSidebar", () => { const sorted = sortProjectsForSidebar( [ makeProject({ - id: ProjectId.makeUnsafe("project-1"), + id: ProjectId.make("project-1"), name: "Older project", updatedAt: "2026-03-09T10:01:00.000Z", }), makeProject({ - id: ProjectId.makeUnsafe("project-2"), + id: ProjectId.make("project-2"), name: "Newer project", updatedAt: "2026-03-09T10:05:00.000Z", }), @@ -895,8 +926,8 @@ describe("sortProjectsForSidebar", () => { ); expect(sorted.map((project) => project.id)).toEqual([ - ProjectId.makeUnsafe("project-2"), - ProjectId.makeUnsafe("project-1"), + ProjectId.make("project-2"), + ProjectId.make("project-1"), ]); }); @@ -904,13 +935,13 @@ describe("sortProjectsForSidebar", () => { const sorted = sortProjectsForSidebar( [ makeProject({ - id: ProjectId.makeUnsafe("project-2"), + id: ProjectId.make("project-2"), name: "Beta", createdAt: undefined, updatedAt: undefined, }), makeProject({ - id: ProjectId.makeUnsafe("project-1"), + id: ProjectId.make("project-1"), name: "Alpha", createdAt: undefined, updatedAt: undefined, @@ -921,22 +952,22 @@ describe("sortProjectsForSidebar", () => { ); expect(sorted.map((project) => project.id)).toEqual([ - ProjectId.makeUnsafe("project-1"), - ProjectId.makeUnsafe("project-2"), + ProjectId.make("project-1"), + ProjectId.make("project-2"), ]); }); it("preserves manual project ordering", () => { const projects = [ - makeProject({ id: ProjectId.makeUnsafe("project-2"), name: "Second" }), - makeProject({ id: ProjectId.makeUnsafe("project-1"), name: "First" }), + makeProject({ id: ProjectId.make("project-2"), name: "Second" }), + makeProject({ id: ProjectId.make("project-1"), name: "First" }), ]; const sorted = sortProjectsForSidebar(projects, [], "manual"); expect(sorted.map((project) => project.id)).toEqual([ - ProjectId.makeUnsafe("project-2"), - ProjectId.makeUnsafe("project-1"), + ProjectId.make("project-2"), + ProjectId.make("project-1"), ]); }); @@ -944,26 +975,26 @@ describe("sortProjectsForSidebar", () => { const sorted = sortProjectsForSidebar( [ makeProject({ - id: ProjectId.makeUnsafe("project-1"), + id: ProjectId.make("project-1"), name: "Visible project", updatedAt: "2026-03-09T10:01:00.000Z", }), makeProject({ - id: ProjectId.makeUnsafe("project-2"), + id: ProjectId.make("project-2"), name: "Archived-only project", updatedAt: "2026-03-09T10:00:00.000Z", }), ], [ makeThread({ - id: ThreadId.makeUnsafe("thread-visible"), - projectId: ProjectId.makeUnsafe("project-1"), + id: ThreadId.make("thread-visible"), + projectId: ProjectId.make("project-1"), updatedAt: "2026-03-09T10:02:00.000Z", archivedAt: null, }), makeThread({ - id: ThreadId.makeUnsafe("thread-archived"), - projectId: ProjectId.makeUnsafe("project-2"), + id: ThreadId.make("thread-archived"), + projectId: ProjectId.make("project-2"), updatedAt: "2026-03-09T10:10:00.000Z", archivedAt: "2026-03-09T10:11:00.000Z", }), @@ -972,8 +1003,8 @@ describe("sortProjectsForSidebar", () => { ); expect(sorted.map((project) => project.id)).toEqual([ - ProjectId.makeUnsafe("project-1"), - ProjectId.makeUnsafe("project-2"), + ProjectId.make("project-1"), + ProjectId.make("project-2"), ]); }); diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 16c7752f74..ed151c6da8 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -1,12 +1,8 @@ import * as React from "react"; import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings"; -import type { Thread } from "../types"; +import type { SidebarThreadSummary, Thread } from "../types"; import { cn } from "../lib/utils"; -import { - findLatestProposedPlan, - hasActionableProposedPlan, - isLatestTurnSettled, -} from "../session-logic"; +import { isLatestTurnSettled } 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; @@ -47,8 +43,13 @@ const THREAD_STATUS_PRIORITY: Record = { }; type ThreadStatusInput = Pick< - Thread, - "interactionMode" | "latestTurn" | "proposedPlans" | "session" + SidebarThreadSummary, + | "hasActionableProposedPlan" + | "hasPendingApprovals" + | "hasPendingUserInput" + | "interactionMode" + | "latestTurn" + | "session" > & { lastVisitedAt?: string | undefined; }; @@ -161,6 +162,46 @@ export function resolveSidebarNewThreadEnvMode(input: { return input.requestedEnvMode ?? input.defaultEnvMode; } +export function resolveSidebarNewThreadSeedContext(input: { + projectId: string; + defaultEnvMode: SidebarNewThreadEnvMode; + activeThread?: { + projectId: string; + branch: string | null; + worktreePath: string | null; + } | null; + activeDraftThread?: { + projectId: string; + branch: string | null; + worktreePath: string | null; + envMode: SidebarNewThreadEnvMode; + } | null; +}): { + branch?: string | null; + worktreePath?: string | null; + envMode: SidebarNewThreadEnvMode; +} { + if (input.activeDraftThread?.projectId === input.projectId) { + return { + branch: input.activeDraftThread.branch, + worktreePath: input.activeDraftThread.worktreePath, + envMode: input.activeDraftThread.envMode, + }; + } + + if (input.activeThread?.projectId === input.projectId) { + return { + branch: input.activeThread.branch, + worktreePath: input.activeThread.worktreePath, + envMode: input.activeThread.worktreePath ? "worktree" : "local", + }; + } + + return { + envMode: input.defaultEnvMode, + }; +} + export function orderItemsByPreferredIds(input: { items: readonly TItem[]; preferredIds: readonly TId[]; @@ -192,15 +233,11 @@ export function orderItemsByPreferredIds(input: { export function getVisibleSidebarThreadIds( renderedProjects: readonly { shouldShowThreadPanel?: boolean; - renderedThreads: readonly { - id: TThreadId; - }[]; + renderedThreadIds: readonly TThreadId[]; }[], ): TThreadId[] { return renderedProjects.flatMap((renderedProject) => - renderedProject.shouldShowThreadPanel === false - ? [] - : renderedProject.renderedThreads.map((thread) => thread.id), + renderedProject.shouldShowThreadPanel === false ? [] : renderedProject.renderedThreadIds, ); } @@ -273,12 +310,10 @@ export function resolveThreadRowClassName(input: { export function resolveThreadStatusPill(input: { thread: ThreadStatusInput; - hasPendingApprovals: boolean; - hasPendingUserInput: boolean; }): ThreadStatusPill | null { - const { hasPendingApprovals, hasPendingUserInput, thread } = input; + const { thread } = input; - if (hasPendingApprovals) { + if (thread.hasPendingApprovals) { return { label: "Pending Approval", colorClass: "text-amber-600 dark:text-amber-300/90", @@ -287,7 +322,7 @@ export function resolveThreadStatusPill(input: { }; } - if (hasPendingUserInput) { + if (thread.hasPendingUserInput) { return { label: "Awaiting Input", colorClass: "text-indigo-600 dark:text-indigo-300/90", @@ -315,12 +350,10 @@ export function resolveThreadStatusPill(input: { } const hasPlanReadyPrompt = - !hasPendingUserInput && + !thread.hasPendingUserInput && thread.interactionMode === "plan" && isLatestTurnSettled(thread.latestTurn, thread.session) && - hasActionableProposedPlan( - findLatestProposedPlan(thread.proposedPlans, thread.latestTurn?.turnId ?? null), - ); + thread.hasActionableProposedPlan; if (hasPlanReadyPrompt) { return { label: "Plan Ready", diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index efa5124288..c5725c6d0d 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -2,6 +2,7 @@ import { ArchiveIcon, ArrowUpDownIcon, ChevronRightIcon, + CloudIcon, FolderIcon, GitPullRequestIcon, PlusIcon, @@ -12,15 +13,7 @@ import { } from "lucide-react"; import { ProjectFavicon } from "./ProjectFavicon"; import { autoAnimate } from "@formkit/auto-animate"; -import { - useCallback, - useEffect, - useMemo, - useRef, - useState, - type MouseEvent, - type PointerEvent, -} from "react"; +import React, { useCallback, useEffect, memo, useMemo, useRef, useState } from "react"; import { useShallow } from "zustand/react/shallow"; import { DndContext, @@ -40,22 +33,40 @@ import { CSS } from "@dnd-kit/utilities"; import { DEFAULT_MODEL_BY_PROVIDER, type DesktopUpdateState, + type EnvironmentId, ProjectId, + type ScopedProjectRef, + type ScopedThreadRef, + type ThreadEnvMode, ThreadId, type GitStatusResult, - type ResolvedKeybindingsConfig, } from "@t3tools/contracts"; -import { useQueries, useQuery } from "@tanstack/react-query"; -import { useLocation, useNavigate, useParams } from "@tanstack/react-router"; +import { + scopedProjectKey, + scopedThreadKey, + scopeProjectRef, + scopeThreadRef, +} from "@t3tools/client-runtime"; +import { Link, useLocation, useNavigate, useParams, useRouter } from "@tanstack/react-router"; import { type SidebarProjectSortOrder, type SidebarThreadSortOrder, } from "@t3tools/contracts/settings"; +import { usePrimaryEnvironmentId } from "../environments/primary"; 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 { + selectProjectByRef, + selectProjectsAcrossEnvironments, + selectSidebarThreadsForProjectRef, + selectSidebarThreadsForProjectRefs, + selectSidebarThreadsAcrossEnvironments, + selectThreadByRef, + useStore, +} from "../store"; +import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore"; import { useUiStateStore } from "../uiStateStore"; import { resolveShortcutCommand, @@ -65,15 +76,17 @@ import { threadJumpIndexFromCommand, threadTraversalDirectionFromCommand, } from "../keybindings"; -import { derivePendingApprovals, derivePendingUserInputs } from "../session-logic"; -import { gitStatusQueryOptions } from "../lib/gitReactQuery"; -import { serverConfigQueryOptions } from "../lib/serverReactQuery"; -import { readNativeApi } from "../nativeApi"; +import { useGitStatus } from "../lib/gitStatusState"; +import { readLocalApi } from "../localApi"; import { useComposerDraftStore } from "../composerDraftStore"; -import { useHandleNewThread } from "../hooks/useHandleNewThread"; +import { useNewThreadHandler } from "../hooks/useHandleNewThread"; import { useThreadActions } from "../hooks/useThreadActions"; -import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore"; +import { + buildThreadRouteParams, + resolveThreadRouteRef, + resolveThreadRouteTarget, +} from "../threadRoutes"; import { toastManager } from "./ui/toast"; import { formatRelativeTimeLabel } from "../timestampFormat"; import { SettingsSidebarNav } from "./settings/SettingsSidebarNav"; @@ -95,7 +108,6 @@ import { SidebarFooter, SidebarGroup, SidebarHeader, - SidebarMenuAction, SidebarMenu, SidebarMenuButton, SidebarMenuItem, @@ -108,11 +120,10 @@ import { import { useThreadSelectionStore } from "../threadSelectionStore"; import { isNonEmpty as isNonEmptyString } from "effect/String"; import { - getVisibleSidebarThreadIds, - getVisibleThreadsForProject, resolveAdjacentThreadId, isContextMenuPointerDown, resolveProjectStatusIndicator, + resolveSidebarNewThreadSeedContext, resolveSidebarNewThreadEnvMode, resolveThreadRowClassName, resolveThreadStatusPill, @@ -121,13 +132,19 @@ import { sortProjectsForSidebar, sortThreadsForSidebar, useThreadJumpHintVisibility, + ThreadStatusPill, } from "./Sidebar.logic"; import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill"; import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; +import { readEnvironmentApi } from "../environmentApi"; import { useSettings, useUpdateSettings } from "~/hooks/useSettings"; -import type { Project, Thread } from "../types"; - -const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = []; +import { useServerKeybindings } from "../rpc/serverState"; +import { deriveLogicalProjectKey } from "../logicalProject"; +import { + useSavedEnvironmentRegistryStore, + useSavedEnvironmentRuntimeStore, +} from "../environments/runtime"; +import type { Project, SidebarThreadSummary } from "../types"; const THREAD_PREVIEW_LIMIT = 6; const SIDEBAR_SORT_LABELS: Record = { updated_at: "Last user message", @@ -142,80 +159,65 @@ const SIDEBAR_LIST_ANIMATION_OPTIONS = { duration: 180, easing: "ease-out", } as const; +const EMPTY_THREAD_JUMP_LABELS = new Map(); -type SidebarThreadSnapshot = Pick< - Thread, - | "activities" - | "archivedAt" - | "branch" - | "createdAt" - | "id" - | "interactionMode" - | "latestTurn" - | "projectId" - | "proposedPlans" - | "session" - | "title" - | "updatedAt" - | "worktreePath" -> & { - lastVisitedAt?: string | undefined; - latestUserMessageAt: string | null; -}; +function threadJumpLabelMapsEqual( + left: ReadonlyMap, + right: ReadonlyMap, +): boolean { + if (left === right) { + return true; + } + if (left.size !== right.size) { + return false; + } + for (const [key, value] of left) { + if (right.get(key) !== value) { + return false; + } + } + return true; +} + +function buildThreadJumpLabelMap(input: { + keybindings: ReturnType; + platform: string; + terminalOpen: boolean; + threadJumpCommandByKey: ReadonlyMap< + string, + NonNullable> + >; +}): ReadonlyMap { + if (input.threadJumpCommandByKey.size === 0) { + return EMPTY_THREAD_JUMP_LABELS; + } + + const shortcutLabelOptions = { + platform: input.platform, + context: { + terminalFocus: false, + terminalOpen: input.terminalOpen, + }, + } as const; + const mapping = new Map(); + for (const [threadKey, command] of input.threadJumpCommandByKey) { + const label = shortcutLabelForCommand(input.keybindings, command, shortcutLabelOptions); + if (label) { + mapping.set(threadKey, label); + } + } + return mapping.size > 0 ? mapping : EMPTY_THREAD_JUMP_LABELS; +} + +type EnvironmentPresence = "local-only" | "remote-only" | "mixed"; type SidebarProjectSnapshot = Project & { - expanded: boolean; + projectKey: string; + environmentPresence: EnvironmentPresence; + memberProjectRefs: readonly ScopedProjectRef[]; + /** Labels for remote environments this project lives in. */ + remoteEnvironmentLabels: readonly string[]; }; - -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; @@ -235,7 +237,7 @@ function ThreadStatusLabel({ status, compact = false, }: { - status: NonNullable>; + status: ThreadStatusPill; compact?: boolean; }) { if (compact) { @@ -312,6 +314,1504 @@ function prStatusIndicator(pr: ThreadPr): PrStatusIndicator | null { return null; } +function resolveThreadPr( + threadBranch: string | null, + gitStatus: GitStatusResult | null, +): ThreadPr | null { + if (threadBranch === null || gitStatus === null || gitStatus.branch !== threadBranch) { + return null; + } + + return gitStatus.pr ?? null; +} + +interface SidebarThreadRowProps { + thread: SidebarThreadSummary; + projectCwd: string | null; + orderedProjectThreadKeys: readonly string[]; + isActive: boolean; + jumpLabel: string | null; + appSettingsConfirmThreadArchive: boolean; + renamingThreadKey: string | null; + renamingTitle: string; + setRenamingTitle: (title: string) => void; + renamingInputRef: React.RefObject; + renamingCommittedRef: React.RefObject; + confirmingArchiveThreadKey: string | null; + setConfirmingArchiveThreadKey: React.Dispatch>; + confirmArchiveButtonRefs: React.RefObject>; + handleThreadClick: ( + event: React.MouseEvent, + threadRef: ScopedThreadRef, + orderedProjectThreadKeys: readonly string[], + ) => void; + navigateToThread: (threadRef: ScopedThreadRef) => void; + handleMultiSelectContextMenu: (position: { x: number; y: number }) => Promise; + handleThreadContextMenu: ( + threadRef: ScopedThreadRef, + position: { x: number; y: number }, + ) => Promise; + clearSelection: () => void; + commitRename: ( + threadRef: ScopedThreadRef, + newTitle: string, + originalTitle: string, + ) => Promise; + cancelRename: () => void; + attemptArchiveThread: (threadRef: ScopedThreadRef) => Promise; + openPrLink: (event: React.MouseEvent, prUrl: string) => void; +} + +const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowProps) { + const { + orderedProjectThreadKeys, + isActive, + jumpLabel, + appSettingsConfirmThreadArchive, + renamingThreadKey, + renamingTitle, + setRenamingTitle, + renamingInputRef, + renamingCommittedRef, + confirmingArchiveThreadKey, + setConfirmingArchiveThreadKey, + confirmArchiveButtonRefs, + handleThreadClick, + navigateToThread, + handleMultiSelectContextMenu, + handleThreadContextMenu, + clearSelection, + commitRename, + cancelRename, + attemptArchiveThread, + openPrLink, + thread, + } = props; + const threadRef = scopeThreadRef(thread.environmentId, thread.id); + const threadKey = scopedThreadKey(threadRef); + const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]); + const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey)); + const hasSelection = useThreadSelectionStore((state) => state.selectedThreadKeys.size > 0); + const runningTerminalIds = useTerminalStateStore( + (state) => + selectThreadTerminalState(state.terminalStateByThreadKey, threadRef).runningTerminalIds, + ); + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const isRemoteThread = + primaryEnvironmentId !== null && thread.environmentId !== primaryEnvironmentId; + const remoteEnvLabel = useSavedEnvironmentRuntimeStore( + (s) => s.byId[thread.environmentId]?.descriptor?.label ?? null, + ); + const remoteEnvSavedLabel = useSavedEnvironmentRegistryStore( + (s) => s.byId[thread.environmentId]?.label ?? null, + ); + const threadEnvironmentLabel = isRemoteThread + ? (remoteEnvLabel ?? remoteEnvSavedLabel ?? "Remote") + : null; + // For grouped projects, the thread may belong to a different environment + // than the representative project. Look up the thread's own project cwd + // so git status (and thus PR detection) queries the correct path. + const threadProjectCwd = useStore( + useMemo( + () => (state: import("../store").AppState) => + selectProjectByRef(state, scopeProjectRef(thread.environmentId, thread.projectId))?.cwd ?? + null, + [thread.environmentId, thread.projectId], + ), + ); + const gitCwd = thread.worktreePath ?? threadProjectCwd ?? props.projectCwd; + const gitStatus = useGitStatus({ + environmentId: thread.environmentId, + cwd: thread.branch != null ? gitCwd : null, + }); + const isHighlighted = isActive || isSelected; + const isThreadRunning = + thread.session?.status === "running" && thread.session.activeTurnId != null; + const threadStatus = resolveThreadStatusPill({ + thread: { + ...thread, + lastVisitedAt, + }, + }); + const pr = resolveThreadPr(thread.branch, gitStatus.data); + const prStatus = prStatusIndicator(pr); + const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds); + const isConfirmingArchive = confirmingArchiveThreadKey === threadKey && !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"; + const clearConfirmingArchive = useCallback(() => { + setConfirmingArchiveThreadKey((current) => (current === threadKey ? null : current)); + }, [setConfirmingArchiveThreadKey, threadKey]); + const handleMouseLeave = useCallback(() => { + clearConfirmingArchive(); + }, [clearConfirmingArchive]); + const handleBlurCapture = useCallback( + (event: React.FocusEvent) => { + const currentTarget = event.currentTarget; + requestAnimationFrame(() => { + if (currentTarget.contains(document.activeElement)) { + return; + } + clearConfirmingArchive(); + }); + }, + [clearConfirmingArchive], + ); + const handleRowClick = useCallback( + (event: React.MouseEvent) => { + handleThreadClick(event, threadRef, orderedProjectThreadKeys); + }, + [handleThreadClick, orderedProjectThreadKeys, threadRef], + ); + const handleRowKeyDown = useCallback( + (event: React.KeyboardEvent) => { + if (event.key !== "Enter" && event.key !== " ") return; + event.preventDefault(); + navigateToThread(threadRef); + }, + [navigateToThread, threadRef], + ); + const handleRowContextMenu = useCallback( + (event: React.MouseEvent) => { + event.preventDefault(); + if (hasSelection && isSelected) { + void handleMultiSelectContextMenu({ + x: event.clientX, + y: event.clientY, + }); + return; + } + + if (hasSelection) { + clearSelection(); + } + void handleThreadContextMenu(threadRef, { + x: event.clientX, + y: event.clientY, + }); + }, + [ + clearSelection, + handleMultiSelectContextMenu, + handleThreadContextMenu, + hasSelection, + isSelected, + threadRef, + ], + ); + const handlePrClick = useCallback( + (event: React.MouseEvent) => { + if (!prStatus) return; + openPrLink(event, prStatus.url); + }, + [openPrLink, prStatus], + ); + const handleRenameInputRef = useCallback( + (element: HTMLInputElement | null) => { + if (element && renamingInputRef.current !== element) { + renamingInputRef.current = element; + element.focus(); + element.select(); + } + }, + [renamingInputRef], + ); + const handleRenameInputChange = useCallback( + (event: React.ChangeEvent) => { + setRenamingTitle(event.target.value); + }, + [setRenamingTitle], + ); + const handleRenameInputKeyDown = useCallback( + (event: React.KeyboardEvent) => { + event.stopPropagation(); + if (event.key === "Enter") { + event.preventDefault(); + renamingCommittedRef.current = true; + void commitRename(threadRef, renamingTitle, thread.title); + } else if (event.key === "Escape") { + event.preventDefault(); + renamingCommittedRef.current = true; + cancelRename(); + } + }, + [cancelRename, commitRename, renamingCommittedRef, renamingTitle, thread.title, threadRef], + ); + const handleRenameInputBlur = useCallback(() => { + if (!renamingCommittedRef.current) { + void commitRename(threadRef, renamingTitle, thread.title); + } + }, [commitRename, renamingCommittedRef, renamingTitle, thread.title, threadRef]); + const handleRenameInputClick = useCallback((event: React.MouseEvent) => { + event.stopPropagation(); + }, []); + const handleConfirmArchiveRef = useCallback( + (element: HTMLButtonElement | null) => { + if (element) { + confirmArchiveButtonRefs.current.set(threadKey, element); + } else { + confirmArchiveButtonRefs.current.delete(threadKey); + } + }, + [confirmArchiveButtonRefs, threadKey], + ); + const stopPropagationOnPointerDown = useCallback( + (event: React.PointerEvent) => { + event.stopPropagation(); + }, + [], + ); + const handleConfirmArchiveClick = useCallback( + (event: React.MouseEvent) => { + event.preventDefault(); + event.stopPropagation(); + clearConfirmingArchive(); + void attemptArchiveThread(threadRef); + }, + [attemptArchiveThread, clearConfirmingArchive, threadRef], + ); + const handleStartArchiveConfirmation = useCallback( + (event: React.MouseEvent) => { + event.preventDefault(); + event.stopPropagation(); + setConfirmingArchiveThreadKey(threadKey); + requestAnimationFrame(() => { + confirmArchiveButtonRefs.current.get(threadKey)?.focus(); + }); + }, + [confirmArchiveButtonRefs, setConfirmingArchiveThreadKey, threadKey], + ); + const handleArchiveImmediateClick = useCallback( + (event: React.MouseEvent) => { + event.preventDefault(); + event.stopPropagation(); + void attemptArchiveThread(threadRef); + }, + [attemptArchiveThread, threadRef], + ); + const rowButtonRender = useMemo(() =>
, []); + + return ( + + +
+ {prStatus && ( + + + + + } + /> + {prStatus.tooltip} + + )} + {threadStatus && } + {renamingThreadKey === threadKey ? ( + + ) : ( + {thread.title} + )} +
+
+ {terminalStatus && ( + + + + )} +
+ {isConfirmingArchive ? ( + + ) : !isThreadRunning ? ( + appSettingsConfirmThreadArchive ? ( +
+ +
+ ) : ( + + + +
+ } + /> + Archive + + ) + ) : null} + + + {isRemoteThread && ( + + + } + > + + + {threadEnvironmentLabel} + + )} + {jumpLabel ? ( + + {jumpLabel} + + ) : ( + + {formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)} + + )} + + +
+
+ + + ); +}); + +interface SidebarProjectThreadListProps { + projectKey: string; + projectExpanded: boolean; + hasOverflowingThreads: boolean; + hiddenThreadStatus: ThreadStatusPill | null; + orderedProjectThreadKeys: readonly string[]; + renderedThreads: readonly SidebarThreadSummary[]; + showEmptyThreadState: boolean; + shouldShowThreadPanel: boolean; + isThreadListExpanded: boolean; + projectCwd: string; + activeRouteThreadKey: string | null; + threadJumpLabelByKey: ReadonlyMap; + appSettingsConfirmThreadArchive: boolean; + renamingThreadKey: string | null; + renamingTitle: string; + setRenamingTitle: (title: string) => void; + renamingInputRef: React.RefObject; + renamingCommittedRef: React.RefObject; + confirmingArchiveThreadKey: string | null; + setConfirmingArchiveThreadKey: React.Dispatch>; + confirmArchiveButtonRefs: React.RefObject>; + attachThreadListAutoAnimateRef: (node: HTMLElement | null) => void; + handleThreadClick: ( + event: React.MouseEvent, + threadRef: ScopedThreadRef, + orderedProjectThreadKeys: readonly string[], + ) => void; + navigateToThread: (threadRef: ScopedThreadRef) => void; + handleMultiSelectContextMenu: (position: { x: number; y: number }) => Promise; + handleThreadContextMenu: ( + threadRef: ScopedThreadRef, + position: { x: number; y: number }, + ) => Promise; + clearSelection: () => void; + commitRename: ( + threadRef: ScopedThreadRef, + newTitle: string, + originalTitle: string, + ) => Promise; + cancelRename: () => void; + attemptArchiveThread: (threadRef: ScopedThreadRef) => Promise; + openPrLink: (event: React.MouseEvent, prUrl: string) => void; + expandThreadListForProject: (projectKey: string) => void; + collapseThreadListForProject: (projectKey: string) => void; +} + +const SidebarProjectThreadList = memo(function SidebarProjectThreadList( + props: SidebarProjectThreadListProps, +) { + const { + projectKey, + projectExpanded, + hasOverflowingThreads, + hiddenThreadStatus, + orderedProjectThreadKeys, + renderedThreads, + showEmptyThreadState, + shouldShowThreadPanel, + isThreadListExpanded, + projectCwd, + activeRouteThreadKey, + threadJumpLabelByKey, + appSettingsConfirmThreadArchive, + renamingThreadKey, + renamingTitle, + setRenamingTitle, + renamingInputRef, + renamingCommittedRef, + confirmingArchiveThreadKey, + setConfirmingArchiveThreadKey, + confirmArchiveButtonRefs, + attachThreadListAutoAnimateRef, + handleThreadClick, + navigateToThread, + handleMultiSelectContextMenu, + handleThreadContextMenu, + clearSelection, + commitRename, + cancelRename, + attemptArchiveThread, + openPrLink, + expandThreadListForProject, + collapseThreadListForProject, + } = props; + const showMoreButtonRender = useMemo(() => +
+ } + /> + + {newThreadShortcutLabel ? `New thread (${newThreadShortcutLabel})` : "New thread"} + + + + + + + ); +}); + +const SidebarProjectListRow = memo(function SidebarProjectListRow(props: SidebarProjectItemProps) { + return ( + + + + ); +}); + function T3Wordmark() { return ( React.ReactNode; }) { @@ -437,217 +1937,623 @@ function SortableProjectItem({ ); } +const SidebarChromeHeader = memo(function SidebarChromeHeader({ + isElectron, +}: { + isElectron: boolean; +}) { + const wordmark = ( +
+ + + + + + Code + + + {APP_STAGE_LABEL} + + + } + /> + + Version {APP_VERSION} + + +
+ ); + + return isElectron ? ( + + {wordmark} + + ) : ( + {wordmark} + ); +}); + +const SidebarChromeFooter = memo(function SidebarChromeFooter() { + const navigate = useNavigate(); + const handleSettingsClick = useCallback(() => { + void navigate({ to: "/settings" }); + }, [navigate]); + + return ( + + + + + + + Settings + + + + + ); +}); + +interface SidebarProjectsContentProps { + showArm64IntelBuildWarning: boolean; + arm64IntelBuildWarningDescription: string | null; + desktopUpdateButtonAction: "download" | "install" | "none"; + desktopUpdateButtonDisabled: boolean; + handleDesktopUpdateButtonClick: () => void; + projectSortOrder: SidebarProjectSortOrder; + threadSortOrder: SidebarThreadSortOrder; + updateSettings: ReturnType["updateSettings"]; + shouldShowProjectPathEntry: boolean; + handleStartAddProject: () => void; + isElectron: boolean; + isPickingFolder: boolean; + isAddingProject: boolean; + handlePickFolder: () => Promise; + addProjectInputRef: React.RefObject; + addProjectError: string | null; + newCwd: string; + setNewCwd: React.Dispatch>; + setAddProjectError: React.Dispatch>; + handleAddProject: () => void; + setAddingProject: React.Dispatch>; + canAddProject: boolean; + isManualProjectSorting: boolean; + projectDnDSensors: ReturnType; + projectCollisionDetection: CollisionDetection; + handleProjectDragStart: (event: DragStartEvent) => void; + handleProjectDragEnd: (event: DragEndEvent) => void; + handleProjectDragCancel: (event: DragCancelEvent) => void; + handleNewThread: ReturnType["handleNewThread"]; + archiveThread: ReturnType["archiveThread"]; + deleteThread: ReturnType["deleteThread"]; + sortedProjects: readonly SidebarProjectSnapshot[]; + expandedThreadListsByProject: ReadonlySet; + activeRouteProjectKey: string | null; + routeThreadKey: string | null; + newThreadShortcutLabel: string | null; + threadJumpLabelByKey: ReadonlyMap; + attachThreadListAutoAnimateRef: (node: HTMLElement | null) => void; + expandThreadListForProject: (projectKey: string) => void; + collapseThreadListForProject: (projectKey: string) => void; + dragInProgressRef: React.RefObject; + suppressProjectClickAfterDragRef: React.RefObject; + suppressProjectClickForContextMenuRef: React.RefObject; + attachProjectListAutoAnimateRef: (node: HTMLElement | null) => void; + projectsLength: number; +} + +const SidebarProjectsContent = memo(function SidebarProjectsContent( + props: SidebarProjectsContentProps, +) { + const { + showArm64IntelBuildWarning, + arm64IntelBuildWarningDescription, + desktopUpdateButtonAction, + desktopUpdateButtonDisabled, + handleDesktopUpdateButtonClick, + projectSortOrder, + threadSortOrder, + updateSettings, + shouldShowProjectPathEntry, + handleStartAddProject, + isElectron, + isPickingFolder, + isAddingProject, + handlePickFolder, + addProjectInputRef, + addProjectError, + newCwd, + setNewCwd, + setAddProjectError, + handleAddProject, + setAddingProject, + canAddProject, + isManualProjectSorting, + projectDnDSensors, + projectCollisionDetection, + handleProjectDragStart, + handleProjectDragEnd, + handleProjectDragCancel, + handleNewThread, + archiveThread, + deleteThread, + sortedProjects, + expandedThreadListsByProject, + activeRouteProjectKey, + routeThreadKey, + newThreadShortcutLabel, + threadJumpLabelByKey, + attachThreadListAutoAnimateRef, + expandThreadListForProject, + collapseThreadListForProject, + dragInProgressRef, + suppressProjectClickAfterDragRef, + suppressProjectClickForContextMenuRef, + attachProjectListAutoAnimateRef, + projectsLength, + } = props; + + const handleProjectSortOrderChange = useCallback( + (sortOrder: SidebarProjectSortOrder) => { + updateSettings({ sidebarProjectSortOrder: sortOrder }); + }, + [updateSettings], + ); + const handleThreadSortOrderChange = useCallback( + (sortOrder: SidebarThreadSortOrder) => { + updateSettings({ sidebarThreadSortOrder: sortOrder }); + }, + [updateSettings], + ); + const handleAddProjectInputChange = useCallback( + (event: React.ChangeEvent) => { + setNewCwd(event.target.value); + setAddProjectError(null); + }, + [setAddProjectError, setNewCwd], + ); + const handleAddProjectInputKeyDown = useCallback( + (event: React.KeyboardEvent) => { + if (event.key === "Enter") handleAddProject(); + if (event.key === "Escape") { + setAddingProject(false); + setAddProjectError(null); + } + }, + [handleAddProject, setAddProjectError, setAddingProject], + ); + const handleBrowseForFolderClick = useCallback(() => { + void handlePickFolder(); + }, [handlePickFolder]); + + return ( + + {showArm64IntelBuildWarning && arm64IntelBuildWarningDescription ? ( + + + + Intel build on Apple Silicon + {arm64IntelBuildWarningDescription} + {desktopUpdateButtonAction !== "none" ? ( + + + + ) : null} + + + ) : null} + +
+ + Projects + +
+ + + + } + > + + + + {shouldShowProjectPathEntry ? "Cancel add project" : "Add project"} + + +
+
+ {shouldShowProjectPathEntry && ( +
+ {isElectron && ( + + )} +
+ + +
+ {addProjectError && ( +

+ {addProjectError} +

+ )} +
+ )} + + {isManualProjectSorting ? ( + + + project.projectKey)} + strategy={verticalListSortingStrategy} + > + {sortedProjects.map((project) => ( + + {(dragHandleProps) => ( + + )} + + ))} + + + + ) : ( + + {sortedProjects.map((project) => ( + + ))} + + )} + + {projectsLength === 0 && !shouldShowProjectPathEntry && ( +
+ No projects yet +
+ )} +
+
+ ); +}); + export default function Sidebar() { - const projects = useStore((store) => store.projects); - 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 projects = useStore(useShallow(selectProjectsAcrossEnvironments)); + const sidebarThreads = useStore(useShallow(selectSidebarThreadsAcrossEnvironments)); + const activeEnvironmentId = useStore((store) => store.activeEnvironmentId); + const projectExpandedById = useUiStateStore((store) => store.projectExpandedById); + const projectOrder = useUiStateStore((store) => store.projectOrder); 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 clearProjectDraftThreadId = useComposerDraftStore( - (store) => store.clearProjectDraftThreadId, - ); const navigate = useNavigate(); const pathname = useLocation({ select: (loc) => loc.pathname }); const isOnSettings = pathname.startsWith("/settings"); - const appSettings = useSettings(); + const sidebarThreadSortOrder = useSettings((s) => s.sidebarThreadSortOrder); + const sidebarProjectSortOrder = useSettings((s) => s.sidebarProjectSortOrder); + const defaultThreadEnvMode = useSettings((s) => s.defaultThreadEnvMode); const { updateSettings } = useUpdateSettings(); - const { handleNewThread } = useHandleNewThread(); + const { handleNewThread } = useNewThreadHandler(); const { archiveThread, deleteThread } = useThreadActions(); - const routeThreadId = useParams({ + const routeThreadRef = useParams({ strict: false, - select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null), - }); - const { data: keybindings = EMPTY_KEYBINDINGS } = useQuery({ - ...serverConfigQueryOptions(), - select: (config) => config.keybindings, + select: (params) => resolveThreadRouteRef(params), }); + const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null; + const keybindings = useServerKeybindings(); const [addingProject, setAddingProject] = useState(false); const [newCwd, setNewCwd] = useState(""); const [isPickingFolder, setIsPickingFolder] = useState(false); const [isAddingProject, setIsAddingProject] = useState(false); const [addProjectError, setAddProjectError] = useState(null); const addProjectInputRef = useRef(null); - const [renamingThreadId, setRenamingThreadId] = useState(null); - const [renamingTitle, setRenamingTitle] = useState(""); - const [confirmingArchiveThreadId, setConfirmingArchiveThreadId] = useState(null); const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState< - ReadonlySet + 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); - const rangeSelectTo = useThreadSelectionStore((s) => s.rangeSelectTo); + const selectedThreadCount = useThreadSelectionStore((s) => s.selectedThreadKeys.size); const clearSelection = useThreadSelectionStore((s) => s.clearSelection); - 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 primaryEnvironmentId = usePrimaryEnvironmentId(); + const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((s) => s.byId); + const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((s) => s.byId); const orderedProjects = useMemo(() => { return orderItemsByPreferredIds({ items: projects, preferredIds: projectOrder, - getId: (project) => project.id, + getId: (project) => scopedProjectKey(scopeProjectRef(project.environmentId, project.id)), }); }, [projectOrder, projects]); - const sidebarProjects = useMemo( - () => - orderedProjects.map((project) => ({ - ...project, - expanded: projectExpandedById[project.id] ?? true, - })), - [orderedProjects, projectExpandedById], + + // Build a mapping from physical project key → logical project key for + // cross-environment grouping. Projects that share a repositoryIdentity + // canonicalKey are treated as one logical project in the sidebar. + const physicalToLogicalKey = useMemo(() => { + const mapping = new Map(); + for (const project of orderedProjects) { + const physicalKey = scopedProjectKey(scopeProjectRef(project.environmentId, project.id)); + mapping.set(physicalKey, deriveLogicalProjectKey(project)); + } + return mapping; + }, [orderedProjects]); + + const sidebarProjects = useMemo(() => { + // Group projects by logical key while preserving insertion order from + // orderedProjects. + const groupedMembers = new Map(); + for (const project of orderedProjects) { + const logicalKey = deriveLogicalProjectKey(project); + const existing = groupedMembers.get(logicalKey); + if (existing) { + existing.push(project); + } else { + groupedMembers.set(logicalKey, [project]); + } + } + + const result: SidebarProjectSnapshot[] = []; + const seen = new Set(); + for (const project of orderedProjects) { + const logicalKey = deriveLogicalProjectKey(project); + if (seen.has(logicalKey)) continue; + seen.add(logicalKey); + + const members = groupedMembers.get(logicalKey)!; + // Prefer the primary environment's project as the representative. + const representative: Project | undefined = + (primaryEnvironmentId + ? members.find((p) => p.environmentId === primaryEnvironmentId) + : undefined) ?? members[0]; + if (!representative) continue; + const hasLocal = + primaryEnvironmentId !== null && + members.some((p) => p.environmentId === primaryEnvironmentId); + const hasRemote = + primaryEnvironmentId !== null + ? members.some((p) => p.environmentId !== primaryEnvironmentId) + : false; + + const refs = members.map((p) => scopeProjectRef(p.environmentId, p.id)); + const remoteLabels = members + .filter((p) => primaryEnvironmentId !== null && p.environmentId !== primaryEnvironmentId) + .map((p) => { + const rt = savedEnvironmentRuntimeById[p.environmentId]; + const saved = savedEnvironmentRegistry[p.environmentId]; + return rt?.descriptor?.label ?? saved?.label ?? p.environmentId; + }); + const snapshot: SidebarProjectSnapshot = { + id: representative.id, + environmentId: representative.environmentId, + name: representative.name, + cwd: representative.cwd, + repositoryIdentity: representative.repositoryIdentity ?? null, + defaultModelSelection: representative.defaultModelSelection, + createdAt: representative.createdAt, + updatedAt: representative.updatedAt, + scripts: representative.scripts, + projectKey: logicalKey, + environmentPresence: + hasLocal && hasRemote ? "mixed" : hasRemote ? "remote-only" : "local-only", + memberProjectRefs: refs, + remoteEnvironmentLabels: remoteLabels, + }; + result.push(snapshot); + } + return result; + }, [ + orderedProjects, + primaryEnvironmentId, + savedEnvironmentRegistry, + savedEnvironmentRuntimeById, + ]); + + const sidebarProjectByKey = useMemo( + () => new Map(sidebarProjects.map((project) => [project.projectKey, project] as const)), + [sidebarProjects], ); - const threads = useMemo( + const sidebarThreadByKey = useMemo( () => - serverThreads.map((thread) => - toSidebarThreadSnapshot(thread, threadLastVisitedAtById[thread.id]), + new Map( + sidebarThreads.map( + (thread) => + [scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), thread] as const, + ), ), - [serverThreads, threadLastVisitedAtById], + [sidebarThreads], ); - const projectCwdById = useMemo( - () => new Map(projects.map((project) => [project.id, project.cwd] as const)), - [projects], + // Resolve the active route's project key to a logical key so it matches the + // sidebar's grouped project entries. + const activeRouteProjectKey = useMemo(() => { + if (!routeThreadKey) { + return null; + } + const activeThread = sidebarThreadByKey.get(routeThreadKey); + if (!activeThread) return null; + const physicalKey = scopedProjectKey( + scopeProjectRef(activeThread.environmentId, activeThread.projectId), + ); + return physicalToLogicalKey.get(physicalKey) ?? physicalKey; + }, [routeThreadKey, sidebarThreadByKey, physicalToLogicalKey]); + + // Group threads by logical project key so all threads from grouped projects + // are displayed together. + const threadsByProjectKey = useMemo(() => { + const next = new Map(); + for (const thread of sidebarThreads) { + const physicalKey = scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)); + const logicalKey = physicalToLogicalKey.get(physicalKey) ?? physicalKey; + const existing = next.get(logicalKey); + if (existing) { + existing.push(thread); + } else { + next.set(logicalKey, [thread]); + } + } + return next; + }, [sidebarThreads, physicalToLogicalKey]); + const getCurrentSidebarShortcutContext = useCallback( + () => ({ + terminalFocus: isTerminalFocused(), + terminalOpen: routeThreadRef + ? selectThreadTerminalState( + useTerminalStateStore.getState().terminalStateByThreadKey, + routeThreadRef, + ).terminalOpen + : false, + }), + [routeThreadRef], ); - const routeTerminalOpen = routeThreadId - ? selectThreadTerminalState(terminalStateByThreadId, routeThreadId).terminalOpen - : false; - const sidebarShortcutLabelOptions = useMemo( + const newThreadShortcutLabelOptions = useMemo( () => ({ platform, context: { terminalFocus: false, - terminalOpen: routeTerminalOpen, + terminalOpen: false, }, }), - [platform, routeTerminalOpen], + [platform], ); - const threadGitTargets = useMemo( - () => - threads.map((thread) => ({ - threadId: thread.id, - branch: thread.branch, - cwd: thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null, - })), - [projectCwdById, threads], - ); - const threadGitStatusCwds = useMemo( - () => [ - ...new Set( - threadGitTargets - .filter((target) => target.branch !== null) - .map((target) => target.cwd) - .filter((cwd): cwd is string => cwd !== null), - ), - ], - [threadGitTargets], - ); - const threadGitStatusQueries = useQueries({ - queries: threadGitStatusCwds.map((cwd) => ({ - ...gitStatusQueryOptions(cwd), - staleTime: 30_000, - refetchInterval: 60_000, - })), - }); - const prByThreadId = useMemo(() => { - const statusByCwd = new Map(); - for (let index = 0; index < threadGitStatusCwds.length; index += 1) { - const cwd = threadGitStatusCwds[index]; - if (!cwd) continue; - const status = threadGitStatusQueries[index]?.data; - if (status) { - statusByCwd.set(cwd, status); - } - } - - const map = new Map(); - for (const target of threadGitTargets) { - const status = target.cwd ? statusByCwd.get(target.cwd) : undefined; - const branchMatches = - target.branch !== null && status?.branch !== null && status?.branch === target.branch; - map.set(target.threadId, branchMatches ? (status?.pr ?? null) : null); - } - return map; - }, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]); - - const openPrLink = useCallback((event: React.MouseEvent, prUrl: string) => { - event.preventDefault(); - event.stopPropagation(); - - const api = readNativeApi(); - if (!api) { - toastManager.add({ - type: "error", - title: "Link opening is unavailable.", - }); - return; - } - - void api.shell.openExternal(prUrl).catch((error) => { - toastManager.add({ - type: "error", - title: "Unable to open PR link", - description: error instanceof Error ? error.message : "An error occurred.", - }); - }); - }, []); - - 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 newThreadShortcutLabel = + shortcutLabelForCommand(keybindings, "chat.newLocal", newThreadShortcutLabelOptions) ?? + shortcutLabelForCommand(keybindings, "chat.new", newThreadShortcutLabelOptions); const focusMostRecentThreadForProject = useCallback( - (projectId: ProjectId) => { + (projectRef: { environmentId: EnvironmentId; projectId: ProjectId }) => { + const physicalKey = scopedProjectKey( + scopeProjectRef(projectRef.environmentId, projectRef.projectId), + ); + const logicalKey = physicalToLogicalKey.get(physicalKey) ?? physicalKey; const latestThread = sortThreadsForSidebar( - threads.filter((thread) => thread.projectId === projectId && thread.archivedAt === null), - appSettings.sidebarThreadSortOrder, + (threadsByProjectKey.get(logicalKey) ?? []).filter((thread) => thread.archivedAt === null), + sidebarThreadSortOrder, )[0]; if (!latestThread) return; void navigate({ - to: "/$threadId", - params: { threadId: latestThread.id }, + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(scopeThreadRef(latestThread.environmentId, latestThread.id)), }); }, - [appSettings.sidebarThreadSortOrder, navigate, threads], + [sidebarThreadSortOrder, navigate, threadsByProjectKey, physicalToLogicalKey], ); const addProjectFromPath = useCallback( async (rawCwd: string) => { const cwd = rawCwd.trim(); if (!cwd || isAddingProject) return; - const api = readNativeApi(); + const api = activeEnvironmentId ? readEnvironmentApi(activeEnvironmentId) : undefined; if (!api) return; setIsAddingProject(true); @@ -660,7 +2566,10 @@ export default function Sidebar() { const existing = projects.find((project) => project.cwd === cwd); if (existing) { - focusMostRecentThreadForProject(existing.id); + focusMostRecentThreadForProject({ + environmentId: existing.environmentId, + projectId: existing.id, + }); finishAddingProject(); return; } @@ -681,9 +2590,11 @@ export default function Sidebar() { }, createdAt, }); - await handleNewThread(projectId, { - envMode: appSettings.defaultThreadEnvMode, - }).catch(() => undefined); + if (activeEnvironmentId !== null) { + await handleNewThread(scopeProjectRef(activeEnvironmentId, projectId), { + envMode: defaultThreadEnvMode, + }).catch(() => undefined); + } } catch (error) { const description = error instanceof Error ? error.message : "An error occurred while adding the project."; @@ -703,11 +2614,12 @@ export default function Sidebar() { }, [ focusMostRecentThreadForProject, + activeEnvironmentId, handleNewThread, isAddingProject, projects, shouldBrowseForProjectImmediately, - appSettings.defaultThreadEnvMode, + defaultThreadEnvMode, ], ); @@ -718,7 +2630,7 @@ export default function Sidebar() { const canAddProject = newCwd.trim().length > 0 && !isAddingProject; const handlePickFolder = async () => { - const api = readNativeApi(); + const api = readLocalApi(); if (!api || isPickingFolder) return; setIsPickingFolder(true); let pickedPath: string | null = null; @@ -744,333 +2656,18 @@ export default function Sidebar() { setAddingProject((prev) => !prev); }; - const cancelRename = useCallback(() => { - setRenamingThreadId(null); - renamingInputRef.current = null; - }, []); - - const commitRename = useCallback( - async (threadId: ThreadId, newTitle: string, originalTitle: string) => { - const finishRename = () => { - setRenamingThreadId((current) => { - if (current !== threadId) return current; - renamingInputRef.current = null; - return null; - }); - }; - - const trimmed = newTitle.trim(); - if (trimmed.length === 0) { - toastManager.add({ - type: "warning", - title: "Thread title cannot be empty", - }); - finishRename(); - return; - } - if (trimmed === originalTitle) { - finishRename(); - return; - } - const api = readNativeApi(); - if (!api) { - finishRename(); - return; - } - try { - await api.orchestration.dispatchCommand({ - type: "thread.meta.update", - commandId: newCommandId(), - threadId, - title: trimmed, - }); - } catch (error) { - toastManager.add({ - type: "error", - title: "Failed to rename thread", - description: error instanceof Error ? error.message : "An error occurred.", - }); - } - finishRename(); - }, - [], - ); - - const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ - threadId: ThreadId; - }>({ - onCopy: (ctx) => { - toastManager.add({ - type: "success", - title: "Thread ID copied", - description: ctx.threadId, - }); - }, - onError: (error) => { - toastManager.add({ - type: "error", - title: "Failed to copy thread ID", - description: error instanceof Error ? error.message : "An error occurred.", - }); - }, - }); - const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ - path: string; - }>({ - onCopy: (ctx) => { - toastManager.add({ - type: "success", - title: "Path copied", - description: ctx.path, - }); - }, - onError: (error) => { - toastManager.add({ - type: "error", - title: "Failed to copy path", - description: error instanceof Error ? error.message : "An error occurred.", - }); - }, - }); - const handleThreadContextMenu = useCallback( - async (threadId: ThreadId, position: { x: number; y: number }) => { - const api = readNativeApi(); - if (!api) return; - const thread = threads.find((t) => t.id === threadId); - if (!thread) return; - const threadWorkspacePath = - thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null; - const clicked = await api.contextMenu.show( - [ - { id: "rename", label: "Rename thread" }, - { id: "mark-unread", label: "Mark unread" }, - { id: "copy-path", label: "Copy Path" }, - { id: "copy-thread-id", label: "Copy Thread ID" }, - { id: "delete", label: "Delete", destructive: true }, - ], - position, - ); - - if (clicked === "rename") { - setRenamingThreadId(threadId); - setRenamingTitle(thread.title); - renamingCommittedRef.current = false; - return; - } - - if (clicked === "mark-unread") { - markThreadUnread(threadId, thread.latestTurn?.completedAt); - return; - } - if (clicked === "copy-path") { - if (!threadWorkspacePath) { - toastManager.add({ - type: "error", - title: "Path unavailable", - description: "This thread does not have a workspace path to copy.", - }); - return; - } - copyPathToClipboard(threadWorkspacePath, { path: threadWorkspacePath }); - return; - } - if (clicked === "copy-thread-id") { - copyThreadIdToClipboard(threadId, { threadId }); - return; - } - if (clicked !== "delete") return; - if (appSettings.confirmThreadDelete) { - const confirmed = await api.dialogs.confirm( - [ - `Delete thread "${thread.title}"?`, - "This permanently clears conversation history for this thread.", - ].join("\n"), - ); - if (!confirmed) { - return; - } - } - await deleteThread(threadId); - }, - [ - appSettings.confirmThreadDelete, - copyPathToClipboard, - copyThreadIdToClipboard, - deleteThread, - markThreadUnread, - projectCwdById, - threads, - ], - ); - - const handleMultiSelectContextMenu = useCallback( - async (position: { x: number; y: number }) => { - const api = readNativeApi(); - if (!api) return; - const ids = [...selectedThreadIds]; - if (ids.length === 0) return; - const count = ids.length; - - const clicked = await api.contextMenu.show( - [ - { id: "mark-unread", label: `Mark unread (${count})` }, - { id: "delete", label: `Delete (${count})`, destructive: true }, - ], - position, - ); - - if (clicked === "mark-unread") { - for (const id of ids) { - const thread = threads.find((candidate) => candidate.id === id); - markThreadUnread(id, thread?.latestTurn?.completedAt); - } - clearSelection(); - return; - } - - if (clicked !== "delete") return; - - if (appSettings.confirmThreadDelete) { - const confirmed = await api.dialogs.confirm( - [ - `Delete ${count} thread${count === 1 ? "" : "s"}?`, - "This permanently clears conversation history for these threads.", - ].join("\n"), - ); - if (!confirmed) return; - } - - const deletedIds = new Set(ids); - for (const id of ids) { - await deleteThread(id, { deletedThreadIds: deletedIds }); - } - removeFromSelection(ids); - }, - [ - appSettings.confirmThreadDelete, - clearSelection, - deleteThread, - markThreadUnread, - removeFromSelection, - selectedThreadIds, - threads, - ], - ); - - const handleThreadClick = useCallback( - (event: MouseEvent, threadId: ThreadId, orderedProjectThreadIds: readonly ThreadId[]) => { - const isMac = isMacPlatform(navigator.platform); - const isModClick = isMac ? event.metaKey : event.ctrlKey; - const isShiftClick = event.shiftKey; - - if (isModClick) { - event.preventDefault(); - toggleThreadSelection(threadId); - return; - } - - if (isShiftClick) { - event.preventDefault(); - rangeSelectTo(threadId, orderedProjectThreadIds); - return; - } - - // Plain click — clear selection, set anchor for future shift-clicks, and navigate - if (selectedThreadIds.size > 0) { - clearSelection(); - } - setSelectionAnchor(threadId); - void navigate({ - to: "/$threadId", - params: { threadId }, - }); - }, - [ - clearSelection, - navigate, - rangeSelectTo, - selectedThreadIds.size, - setSelectionAnchor, - toggleThreadSelection, - ], - ); - const navigateToThread = useCallback( - (threadId: ThreadId) => { - if (selectedThreadIds.size > 0) { + (threadRef: ScopedThreadRef) => { + if (useThreadSelectionStore.getState().selectedThreadKeys.size > 0) { clearSelection(); } - setSelectionAnchor(threadId); + setSelectionAnchor(scopedThreadKey(threadRef)); void navigate({ - to: "/$threadId", - params: { threadId }, + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(threadRef), }); }, - [clearSelection, navigate, selectedThreadIds.size, setSelectionAnchor], - ); - - const handleProjectContextMenu = useCallback( - async (projectId: ProjectId, position: { x: number; y: number }) => { - const api = readNativeApi(); - if (!api) 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({ - type: "warning", - title: "Project is not empty", - description: "Delete all threads in this project before removing it.", - }); - return; - } - - const confirmed = await api.dialogs.confirm(`Remove project "${project.name}"?`); - if (!confirmed) return; - - try { - const projectDraftThread = getDraftThreadByProjectId(projectId); - if (projectDraftThread) { - clearComposerDraftForThread(projectDraftThread.threadId); - } - clearProjectDraftThreadId(projectId); - await api.orchestration.dispatchCommand({ - type: "project.delete", - commandId: newCommandId(), - projectId, - }); - } catch (error) { - const message = error instanceof Error ? error.message : "Unknown error removing project."; - console.error("Failed to remove project", { projectId, error }); - toastManager.add({ - type: "error", - title: `Failed to remove "${project.name}"`, - description: message, - }); - } - }, - [ - clearComposerDraftForThread, - clearProjectDraftThreadId, - copyPathToClipboard, - getDraftThreadByProjectId, - projects, - threads, - ], + [clearSelection, navigate, setSelectionAnchor], ); const projectDnDSensors = useSensors( @@ -1089,30 +2686,32 @@ export default function Sidebar() { const handleProjectDragEnd = useCallback( (event: DragEndEvent) => { - if (appSettings.sidebarProjectSortOrder !== "manual") { + if (sidebarProjectSortOrder !== "manual") { dragInProgressRef.current = false; return; } dragInProgressRef.current = false; const { active, over } = event; if (!over || active.id === over.id) return; - const activeProject = sidebarProjects.find((project) => project.id === active.id); - const overProject = sidebarProjects.find((project) => project.id === over.id); + const activeProject = sidebarProjects.find((project) => project.projectKey === active.id); + const overProject = sidebarProjects.find((project) => project.projectKey === over.id); if (!activeProject || !overProject) return; - reorderProjects(activeProject.id, overProject.id); + const activeMemberKeys = activeProject.memberProjectRefs.map(scopedProjectKey); + const overMemberKeys = overProject.memberProjectRefs.map(scopedProjectKey); + reorderProjects(activeMemberKeys, overMemberKeys); }, - [appSettings.sidebarProjectSortOrder, reorderProjects, sidebarProjects], + [sidebarProjectSortOrder, reorderProjects, sidebarProjects], ); const handleProjectDragStart = useCallback( (_event: DragStartEvent) => { - if (appSettings.sidebarProjectSortOrder !== "manual") { + if (sidebarProjectSortOrder !== "manual") { return; } dragInProgressRef.current = true; suppressProjectClickAfterDragRef.current = true; }, - [appSettings.sidebarProjectSortOrder], + [sidebarProjectSortOrder], ); const handleProjectDragCancel = useCallback((_event: DragCancelEvent) => { @@ -1137,148 +2736,155 @@ export default function Sidebar() { animatedThreadListsRef.current.add(node); }, []); - 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], + () => sidebarThreads.filter((thread) => thread.archivedAt === null), + [sidebarThreads], ); - const sortedProjects = useMemo( + const sortedProjects = useMemo(() => { + const sortableProjects = sidebarProjects.map((project) => ({ + ...project, + id: project.projectKey, + })); + const sortableThreads = visibleThreads.map((thread) => { + const physicalKey = scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)); + return { + ...thread, + projectId: (physicalToLogicalKey.get(physicalKey) ?? physicalKey) as ProjectId, + }; + }); + return sortProjectsForSidebar( + sortableProjects, + sortableThreads, + sidebarProjectSortOrder, + ).flatMap((project) => { + const resolvedProject = sidebarProjectByKey.get(project.id); + return resolvedProject ? [resolvedProject] : []; + }); + }, [ + sidebarProjectSortOrder, + physicalToLogicalKey, + sidebarProjectByKey, + sidebarProjects, + visibleThreads, + ]); + const isManualProjectSorting = sidebarProjectSortOrder === "manual"; + const visibleSidebarThreadKeys = useMemo( () => - sortProjectsForSidebar(sidebarProjects, visibleThreads, appSettings.sidebarProjectSortOrder), - [appSettings.sidebarProjectSortOrder, sidebarProjects, visibleThreads], - ); - const isManualProjectSorting = appSettings.sidebarProjectSortOrder === "manual"; - const renderedProjects = useMemo( - () => - sortedProjects.map((project) => { + sortedProjects.flatMap((project) => { const projectThreads = sortThreadsForSidebar( - visibleThreads.filter((thread) => thread.projectId === project.id), - appSettings.sidebarThreadSortOrder, + (threadsByProjectKey.get(project.projectKey) ?? []).filter( + (thread) => thread.archivedAt === null, + ), + 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 projectExpanded = projectExpandedById[project.projectKey] ?? true; + const activeThreadKey = routeThreadKey ?? undefined; const pinnedCollapsedThread = - !project.expanded && activeThreadId - ? (projectThreads.find((thread) => thread.id === activeThreadId) ?? null) + !projectExpanded && activeThreadKey + ? (projectThreads.find( + (thread) => + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === + activeThreadKey, + ) ?? 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 shouldShowThreadPanel = projectExpanded || pinnedCollapsedThread !== null; + if (!shouldShowThreadPanel) { + return []; + } + const isThreadListExpanded = expandedThreadListsByProject.has(project.projectKey); + const hasOverflowingThreads = projectThreads.length > THREAD_PREVIEW_LIMIT; + const previewThreads = + isThreadListExpanded || !hasOverflowingThreads + ? projectThreads + : projectThreads.slice(0, THREAD_PREVIEW_LIMIT); + const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : previewThreads; + return renderedThreads.map((thread) => + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), ); - 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, + sidebarThreadSortOrder, expandedThreadListsByProject, - routeThreadId, + projectExpandedById, + routeThreadKey, sortedProjects, - visibleThreads, + threadsByProjectKey, ], ); - const visibleSidebarThreadIds = useMemo( - () => getVisibleSidebarThreadIds(renderedProjects), - [renderedProjects], - ); - const threadJumpCommandById = useMemo(() => { - const mapping = new Map>>(); - for (const [visibleThreadIndex, threadId] of visibleSidebarThreadIds.entries()) { + const threadJumpCommandByKey = useMemo(() => { + const mapping = new Map>>(); + for (const [visibleThreadIndex, threadKey] of visibleSidebarThreadKeys.entries()) { const jumpCommand = threadJumpCommandForIndex(visibleThreadIndex); if (!jumpCommand) { return mapping; } - mapping.set(threadId, jumpCommand); + mapping.set(threadKey, jumpCommand); } return mapping; - }, [visibleSidebarThreadIds]); - const threadJumpThreadIds = useMemo( - () => [...threadJumpCommandById.keys()], - [threadJumpCommandById], + }, [visibleSidebarThreadKeys]); + const threadJumpThreadKeys = useMemo( + () => [...threadJumpCommandByKey.keys()], + [threadJumpCommandByKey], ); - 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; + const [threadJumpLabelByKey, setThreadJumpLabelByKey] = + useState>(EMPTY_THREAD_JUMP_LABELS); + const threadJumpLabelsRef = useRef>(EMPTY_THREAD_JUMP_LABELS); + threadJumpLabelsRef.current = threadJumpLabelByKey; + const showThreadJumpHintsRef = useRef(showThreadJumpHints); + showThreadJumpHintsRef.current = showThreadJumpHints; + const visibleThreadJumpLabelByKey = showThreadJumpHints + ? threadJumpLabelByKey + : EMPTY_THREAD_JUMP_LABELS; + const orderedSidebarThreadKeys = visibleSidebarThreadKeys; useEffect(() => { - const getShortcutContext = () => ({ - terminalFocus: isTerminalFocused(), - terminalOpen: routeTerminalOpen, - }); - - const onWindowKeyDown = (event: KeyboardEvent) => { - updateThreadJumpHintsVisibility( - shouldShowThreadJumpHints(event, keybindings, { - platform, - context: getShortcutContext(), - }), + const clearThreadJumpHints = () => { + setThreadJumpLabelByKey((current) => + current === EMPTY_THREAD_JUMP_LABELS ? current : EMPTY_THREAD_JUMP_LABELS, ); + updateThreadJumpHintsVisibility(false); + }; + const shouldIgnoreThreadJumpHintUpdate = (event: globalThis.KeyboardEvent) => + !event.metaKey && + !event.ctrlKey && + !event.altKey && + !event.shiftKey && + event.key !== "Meta" && + event.key !== "Control" && + event.key !== "Alt" && + event.key !== "Shift" && + !showThreadJumpHintsRef.current && + threadJumpLabelsRef.current === EMPTY_THREAD_JUMP_LABELS; + + const onWindowKeyDown = (event: globalThis.KeyboardEvent) => { + if (shouldIgnoreThreadJumpHintUpdate(event)) { + return; + } + const shortcutContext = getCurrentSidebarShortcutContext(); + const shouldShowHints = shouldShowThreadJumpHints(event, keybindings, { + platform, + context: shortcutContext, + }); + if (!shouldShowHints) { + if ( + showThreadJumpHintsRef.current || + threadJumpLabelsRef.current !== EMPTY_THREAD_JUMP_LABELS + ) { + clearThreadJumpHints(); + } + } else { + setThreadJumpLabelByKey((current) => { + const nextLabelMap = buildThreadJumpLabelMap({ + keybindings, + platform, + terminalOpen: shortcutContext.terminalOpen, + threadJumpCommandByKey, + }); + return threadJumpLabelMapsEqual(current, nextLabelMap) ? current : nextLabelMap; + }); + updateThreadJumpHintsVisibility(true); + } if (event.defaultPrevented || event.repeat) { return; @@ -1286,22 +2892,26 @@ export default function Sidebar() { const command = resolveShortcutCommand(event, keybindings, { platform, - context: getShortcutContext(), + context: shortcutContext, }); const traversalDirection = threadTraversalDirectionFromCommand(command); if (traversalDirection !== null) { - const targetThreadId = resolveAdjacentThreadId({ - threadIds: orderedSidebarThreadIds, - currentThreadId: routeThreadId, + const targetThreadKey = resolveAdjacentThreadId({ + threadIds: orderedSidebarThreadKeys, + currentThreadId: routeThreadKey, direction: traversalDirection, }); - if (!targetThreadId) { + if (!targetThreadKey) { + return; + } + const targetThread = sidebarThreadByKey.get(targetThreadKey); + if (!targetThread) { return; } event.preventDefault(); event.stopPropagation(); - navigateToThread(targetThreadId); + navigateToThread(scopeThreadRef(targetThread.environmentId, targetThread.id)); return; } @@ -1310,27 +2920,47 @@ export default function Sidebar() { return; } - const targetThreadId = threadJumpThreadIds[jumpIndex]; - if (!targetThreadId) { + const targetThreadKey = threadJumpThreadKeys[jumpIndex]; + if (!targetThreadKey) { + return; + } + const targetThread = sidebarThreadByKey.get(targetThreadKey); + if (!targetThread) { return; } event.preventDefault(); event.stopPropagation(); - navigateToThread(targetThreadId); + navigateToThread(scopeThreadRef(targetThread.environmentId, targetThread.id)); }; - const onWindowKeyUp = (event: KeyboardEvent) => { - updateThreadJumpHintsVisibility( - shouldShowThreadJumpHints(event, keybindings, { + const onWindowKeyUp = (event: globalThis.KeyboardEvent) => { + if (shouldIgnoreThreadJumpHintUpdate(event)) { + return; + } + const shortcutContext = getCurrentSidebarShortcutContext(); + const shouldShowHints = shouldShowThreadJumpHints(event, keybindings, { + platform, + context: shortcutContext, + }); + if (!shouldShowHints) { + clearThreadJumpHints(); + return; + } + setThreadJumpLabelByKey((current) => { + const nextLabelMap = buildThreadJumpLabelMap({ + keybindings, platform, - context: getShortcutContext(), - }), - ); + terminalOpen: shortcutContext.terminalOpen, + threadJumpCommandByKey, + }); + return threadJumpLabelMapsEqual(current, nextLabelMap) ? current : nextLabelMap; + }); + updateThreadJumpHintsVisibility(true); }; const onWindowBlur = () => { - updateThreadJumpHintsVisibility(false); + clearThreadJumpHints(); }; window.addEventListener("keydown", onWindowKeyDown); @@ -1343,463 +2973,21 @@ export default function Sidebar() { window.removeEventListener("blur", onWindowBlur); }; }, [ + getCurrentSidebarShortcutContext, keybindings, navigateToThread, - orderedSidebarThreadIds, + orderedSidebarThreadKeys, platform, - routeTerminalOpen, - routeThreadId, - threadJumpThreadIds, + routeThreadKey, + sidebarThreadByKey, + threadJumpCommandByKey, + threadJumpThreadKeys, updateThreadJumpHintsVisibility, ]); - function renderProjectItem( - renderedProject: (typeof renderedProjects)[number], - dragHandleProps: SortableProjectHandleProps | null, - ) { - const { - hasHiddenThreads, - hiddenThreadStatus, - orderedProjectThreadIds, - project, - projectStatus, - projectThreads, - threadStatuses, - renderedThreads, - showEmptyThreadState, - shouldShowThreadPanel, - isThreadListExpanded, - } = renderedProject; - const renderThreadRow = (thread: (typeof projectThreads)[number]) => { - const isActive = routeThreadId === thread.id; - const isSelected = selectedThreadIds.has(thread.id); - const isHighlighted = isActive || isSelected; - 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} - 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(); - navigateToThread(thread.id); - }} - onContextMenu={(event) => { - event.preventDefault(); - if (selectedThreadIds.size > 0 && selectedThreadIds.has(thread.id)) { - void handleMultiSelectContextMenu({ - x: event.clientX, - y: event.clientY, - }); - } else { - if (selectedThreadIds.size > 0) { - clearSelection(); - } - void handleThreadContextMenu(thread.id, { - x: event.clientX, - y: event.clientY, - }); - } - }} - > -
- {prStatus && ( - - { - openPrLink(event, prStatus.url); - }} - > - - - } - /> - {prStatus.tooltip} - - )} - {threadStatus && } - {renamingThreadId === thread.id ? ( - { - if (el && renamingInputRef.current !== el) { - renamingInputRef.current = el; - el.focus(); - el.select(); - } - }} - className="min-w-0 flex-1 truncate text-xs bg-transparent outline-none border border-ring rounded px-0.5" - value={renamingTitle} - onChange={(e) => setRenamingTitle(e.target.value)} - onKeyDown={(e) => { - e.stopPropagation(); - if (e.key === "Enter") { - e.preventDefault(); - renamingCommittedRef.current = true; - void commitRename(thread.id, renamingTitle, thread.title); - } else if (e.key === "Escape") { - e.preventDefault(); - renamingCommittedRef.current = true; - cancelRename(); - } - }} - onBlur={() => { - if (!renamingCommittedRef.current) { - void commitRename(thread.id, renamingTitle, thread.title); - } - }} - onClick={(e) => e.stopPropagation()} - /> - ) : ( - {thread.title} - )} -
-
- {terminalStatus && ( - - - - )} -
- {isConfirmingArchive ? ( - - ) : !isThreadRunning ? ( - appSettings.confirmThreadArchive ? ( -
- -
- ) : ( - - - -
- } - /> - Archive - - ) - ) : null} - - {showThreadJumpHints && jumpLabel ? ( - - {jumpLabel} - - ) : ( - - {formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)} - - )} - -
- -
-
- ); - }; - - return ( - <> -
- handleProjectTitleClick(event, project.id)} - onKeyDown={(event) => handleProjectTitleKeyDown(event, project.id)} - onContextMenu={(event) => { - event.preventDefault(); - suppressProjectClickForContextMenuRef.current = true; - void handleProjectContextMenu(project.id, { - x: event.clientX, - y: event.clientY, - }); - }} - > - {!project.expanded && projectStatus ? ( - - - - } - showOnHover - 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(); - void handleNewThread(project.id, { - envMode: resolveSidebarNewThreadEnvMode({ - defaultEnvMode: appSettings.defaultThreadEnvMode, - }), - }); - }} - > - - - } - /> - - {newThreadShortcutLabel ? `New thread (${newThreadShortcutLabel})` : "New 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); - }} - > - - {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 - - - )} -
- - ); - } - - 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(); - return; - } - if (suppressProjectClickAfterDragRef.current) { - // Consume the synthetic click emitted after a drag release. - suppressProjectClickAfterDragRef.current = false; - event.preventDefault(); - event.stopPropagation(); - return; - } - if (selectedThreadIds.size > 0) { - clearSelection(); - } - toggleProject(projectId); - }, - [clearSelection, selectedThreadIds.size, toggleProject], - ); - - const handleProjectTitleKeyDown = useCallback( - (event: React.KeyboardEvent, projectId: ProjectId) => { - if (event.key !== "Enter" && event.key !== " ") return; - event.preventDefault(); - if (dragInProgressRef.current) { - return; - } - toggleProject(projectId); - }, - [toggleProject], - ); - useEffect(() => { const onMouseDown = (event: globalThis.MouseEvent) => { - if (selectedThreadIds.size === 0) return; + if (selectedThreadCount === 0) return; const target = event.target instanceof HTMLElement ? event.target : null; if (!shouldClearThreadSelectionOnMouseDown(target)) return; clearSelection(); @@ -1809,7 +2997,7 @@ export default function Sidebar() { return () => { window.removeEventListener("mousedown", onMouseDown); }; - }, [clearSelection, selectedThreadIds.size]); + }, [clearSelection, selectedThreadCount]); useEffect(() => { if (!isElectron) return; @@ -1854,10 +3042,6 @@ export default function Sidebar() { desktopUpdateState && showArm64IntelBuildWarning ? getArm64IntelBuildWarningDescription(desktopUpdateState) : null; - const newThreadShortcutLabel = - shortcutLabelForCommand(keybindings, "chat.newLocal", sidebarShortcutLabelOptions) ?? - shortcutLabelForCommand(keybindings, "chat.new", sidebarShortcutLabelOptions); - const handleDesktopUpdateButtonClick = useCallback(() => { const bridge = window.desktopBridge; if (!bridge || !desktopUpdateState) return; @@ -1920,242 +3104,82 @@ export default function Sidebar() { } }, [desktopUpdateButtonAction, desktopUpdateButtonDisabled, desktopUpdateState]); - const expandThreadListForProject = useCallback((projectId: ProjectId) => { + const expandThreadListForProject = useCallback((projectKey: string) => { setExpandedThreadListsByProject((current) => { - if (current.has(projectId)) return current; + if (current.has(projectKey)) return current; const next = new Set(current); - next.add(projectId); + next.add(projectKey); return next; }); }, []); - const collapseThreadListForProject = useCallback((projectId: ProjectId) => { + const collapseThreadListForProject = useCallback((projectKey: string) => { setExpandedThreadListsByProject((current) => { - if (!current.has(projectId)) return current; + if (!current.has(projectKey)) return current; const next = new Set(current); - next.delete(projectId); + next.delete(projectKey); return next; }); }, []); - const wordmark = ( -
- - - - - - Code - - - {APP_STAGE_LABEL} - -
- } - /> - - Version {APP_VERSION} - - - - ); - return ( <> - {isElectron ? ( - - {wordmark} - - ) : ( - - {wordmark} - - )} + {isOnSettings ? ( ) : ( <> - - {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 - /> - -
- {addProjectError && ( -

- {addProjectError} -

- )} -
- )} - - {isManualProjectSorting ? ( - - - renderedProject.project.id)} - strategy={verticalListSortingStrategy} - > - {renderedProjects.map((renderedProject) => ( - - {(dragHandleProps) => renderProjectItem(renderedProject, dragHandleProps)} - - ))} - - - - ) : ( - - {renderedProjects.map((renderedProject) => ( - - {renderProjectItem(renderedProject, null)} - - ))} - - )} - - {projects.length === 0 && !shouldShowProjectPathEntry && ( -
- No projects yet -
- )} -
-
+ - - - - - void navigate({ to: "/settings" })} - > - - Settings - - - - + )} diff --git a/apps/web/src/components/SplashScreen.tsx b/apps/web/src/components/SplashScreen.tsx new file mode 100644 index 0000000000..a0b593a950 --- /dev/null +++ b/apps/web/src/components/SplashScreen.tsx @@ -0,0 +1,9 @@ +export function SplashScreen() { + return ( +
+
+ T3 Code +
+
+ ); +} diff --git a/apps/web/src/components/ThreadTerminalDrawer.browser.tsx b/apps/web/src/components/ThreadTerminalDrawer.browser.tsx new file mode 100644 index 0000000000..37e0df1cc4 --- /dev/null +++ b/apps/web/src/components/ThreadTerminalDrawer.browser.tsx @@ -0,0 +1,318 @@ +import "../index.css"; + +import { scopeThreadRef } from "@t3tools/client-runtime"; +import { ThreadId } from "@t3tools/contracts"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { render } from "vitest-browser-react"; + +const { + terminalConstructorSpy, + terminalDisposeSpy, + fitAddonFitSpy, + fitAddonLoadSpy, + environmentApiById, + readEnvironmentApiMock, + readLocalApiMock, +} = vi.hoisted(() => ({ + terminalConstructorSpy: vi.fn(), + terminalDisposeSpy: vi.fn(), + fitAddonFitSpy: vi.fn(), + fitAddonLoadSpy: vi.fn(), + environmentApiById: new Map } }>(), + readEnvironmentApiMock: vi.fn((environmentId: string) => environmentApiById.get(environmentId)), + readLocalApiMock: vi.fn< + () => + | { + contextMenu: { show: ReturnType }; + shell: { openExternal: ReturnType }; + } + | undefined + >(() => ({ + contextMenu: { show: vi.fn(async () => null) }, + shell: { openExternal: vi.fn(async () => undefined) }, + })), +})); + +vi.mock("@xterm/addon-fit", () => ({ + FitAddon: class MockFitAddon { + fit = fitAddonFitSpy; + }, +})); + +vi.mock("@xterm/xterm", () => ({ + Terminal: class MockTerminal { + cols = 80; + rows = 24; + options: { theme?: unknown } = {}; + buffer = { + active: { + viewportY: 0, + baseY: 0, + getLine: vi.fn(() => null), + }, + }; + + constructor(options: unknown) { + terminalConstructorSpy(options); + } + + loadAddon(addon: unknown) { + fitAddonLoadSpy(addon); + } + + open() {} + + write() {} + + clear() {} + + clearSelection() {} + + focus() {} + + refresh() {} + + scrollToBottom() {} + + hasSelection() { + return false; + } + + getSelection() { + return ""; + } + + getSelectionPosition() { + return null; + } + + attachCustomKeyEventHandler() { + return true; + } + + registerLinkProvider() { + return { dispose: vi.fn() }; + } + + onData() { + return { dispose: vi.fn() }; + } + + onSelectionChange() { + return { dispose: vi.fn() }; + } + + dispose() { + terminalDisposeSpy(); + } + }, +})); + +vi.mock("~/environmentApi", () => ({ + readEnvironmentApi: readEnvironmentApiMock, +})); + +vi.mock("~/localApi", () => ({ + ensureLocalApi: vi.fn(() => { + throw new Error("ensureLocalApi not implemented in browser test"); + }), + readLocalApi: readLocalApiMock, +})); + +import { TerminalViewport } from "./ThreadTerminalDrawer"; + +const THREAD_ID = ThreadId.make("thread-terminal-browser"); + +function createEnvironmentApi() { + return { + terminal: { + open: vi.fn(async () => ({ + threadId: THREAD_ID, + terminalId: "default", + cwd: "/repo/project", + worktreePath: null, + status: "running" as const, + pid: 123, + history: "", + exitCode: null, + exitSignal: null, + updatedAt: "2026-04-07T00:00:00.000Z", + })), + write: vi.fn(async () => undefined), + resize: vi.fn(async () => undefined), + }, + }; +} + +async function mountTerminalViewport(props: { + threadRef: ReturnType; + drawerBackgroundColor?: string; + drawerTextColor?: string; +}) { + const drawer = document.createElement("div"); + drawer.className = "thread-terminal-drawer"; + if (props.drawerBackgroundColor) { + drawer.style.backgroundColor = props.drawerBackgroundColor; + } + if (props.drawerTextColor) { + drawer.style.color = props.drawerTextColor; + } + + const host = document.createElement("div"); + host.style.width = "800px"; + host.style.height = "400px"; + drawer.append(host); + document.body.append(drawer); + + const screen = await render( + undefined} + onAddTerminalContext={() => undefined} + focusRequestId={0} + autoFocus={false} + resizeEpoch={0} + drawerHeight={320} + />, + { container: host }, + ); + + return { + rerender: async (nextProps: { threadRef: ReturnType }) => { + await screen.rerender( + undefined} + onAddTerminalContext={() => undefined} + focusRequestId={0} + autoFocus={false} + resizeEpoch={0} + drawerHeight={320} + />, + ); + }, + cleanup: async () => { + await screen.unmount(); + drawer.remove(); + }, + }; +} + +describe("TerminalViewport", () => { + afterEach(() => { + environmentApiById.clear(); + readEnvironmentApiMock.mockClear(); + readLocalApiMock.mockClear(); + terminalConstructorSpy.mockClear(); + terminalDisposeSpy.mockClear(); + fitAddonFitSpy.mockClear(); + fitAddonLoadSpy.mockClear(); + }); + + it("does not create a terminal when APIs are unavailable", async () => { + readEnvironmentApiMock.mockReturnValueOnce(undefined); + readLocalApiMock.mockReturnValueOnce(undefined); + + const mounted = await mountTerminalViewport({ + threadRef: scopeThreadRef("environment-a" as never, THREAD_ID), + }); + + try { + await vi.waitFor(() => { + expect(terminalConstructorSpy).not.toHaveBeenCalled(); + }); + } finally { + await mounted.cleanup(); + } + }); + + it("reopens the terminal when the scoped thread reference changes", async () => { + const environmentA = createEnvironmentApi(); + const environmentB = createEnvironmentApi(); + environmentApiById.set("environment-a", environmentA); + environmentApiById.set("environment-b", environmentB); + + const mounted = await mountTerminalViewport({ + threadRef: scopeThreadRef("environment-a" as never, THREAD_ID), + }); + + try { + await vi.waitFor(() => { + expect(environmentA.terminal.open).toHaveBeenCalledTimes(1); + }); + + await mounted.rerender({ + threadRef: scopeThreadRef("environment-b" as never, THREAD_ID), + }); + + await vi.waitFor(() => { + expect(environmentB.terminal.open).toHaveBeenCalledTimes(1); + }); + expect(terminalDisposeSpy).toHaveBeenCalledTimes(1); + } finally { + await mounted.cleanup(); + } + }); + + it("does not reopen the terminal when the scoped thread reference values stay the same", async () => { + const environment = createEnvironmentApi(); + environmentApiById.set("environment-a", environment); + + const mounted = await mountTerminalViewport({ + threadRef: scopeThreadRef("environment-a" as never, THREAD_ID), + }); + + try { + await vi.waitFor(() => { + expect(environment.terminal.open).toHaveBeenCalledTimes(1); + }); + + await mounted.rerender({ + threadRef: scopeThreadRef("environment-a" as never, THREAD_ID), + }); + + await vi.waitFor(() => { + expect(environment.terminal.open).toHaveBeenCalledTimes(1); + }); + expect(terminalDisposeSpy).not.toHaveBeenCalled(); + } finally { + await mounted.cleanup(); + } + }); + + it("uses the drawer surface colors for the terminal theme", async () => { + const environment = createEnvironmentApi(); + environmentApiById.set("environment-a", environment); + + const mounted = await mountTerminalViewport({ + threadRef: scopeThreadRef("environment-a" as never, THREAD_ID), + drawerBackgroundColor: "rgb(24, 28, 36)", + drawerTextColor: "rgb(228, 232, 240)", + }); + + try { + await vi.waitFor(() => { + expect(terminalConstructorSpy).toHaveBeenCalledTimes(1); + }); + + expect(terminalConstructorSpy).toHaveBeenCalledWith( + expect.objectContaining({ + theme: expect.objectContaining({ + background: "rgb(24, 28, 36)", + foreground: "rgb(228, 232, 240)", + }), + }), + ); + } finally { + await mounted.cleanup(); + } + }); +}); diff --git a/apps/web/src/components/ThreadTerminalDrawer.test.ts b/apps/web/src/components/ThreadTerminalDrawer.test.ts index 4d59583777..d9740cc305 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.test.ts +++ b/apps/web/src/components/ThreadTerminalDrawer.test.ts @@ -2,6 +2,8 @@ import { describe, expect, it } from "vitest"; import { resolveTerminalSelectionActionPosition, + selectPendingTerminalEventEntries, + selectTerminalEventEntriesAfterSnapshot, shouldHandleTerminalSelectionMouseUp, terminalSelectionActionDelayForClickCount, } from "./ThreadTerminalDrawer"; @@ -72,4 +74,64 @@ describe("resolveTerminalSelectionActionPosition", () => { expect(shouldHandleTerminalSelectionMouseUp(false, 0)).toBe(false); expect(shouldHandleTerminalSelectionMouseUp(true, 1)).toBe(false); }); + + it("replays only terminal events newer than the open snapshot", () => { + expect( + selectTerminalEventEntriesAfterSnapshot( + [ + { + id: 1, + event: { + threadId: "thread-1", + terminalId: "default", + createdAt: "2026-04-02T20:00:00.000Z", + type: "output", + data: "before", + }, + }, + { + id: 2, + event: { + threadId: "thread-1", + terminalId: "default", + createdAt: "2026-04-02T20:00:01.000Z", + type: "output", + data: "after", + }, + }, + ], + "2026-04-02T20:00:00.500Z", + ).map((entry) => entry.id), + ).toEqual([2]); + }); + + it("applies only terminal events that have not already been consumed", () => { + expect( + selectPendingTerminalEventEntries( + [ + { + id: 1, + event: { + threadId: "thread-1", + terminalId: "default", + createdAt: "2026-04-02T20:00:00.000Z", + type: "output", + data: "one", + }, + }, + { + id: 2, + event: { + threadId: "thread-1", + terminalId: "default", + createdAt: "2026-04-02T20:00:01.000Z", + type: "output", + data: "two", + }, + }, + ], + 1, + ).map((entry) => entry.id), + ).toEqual([2]); + }); }); diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index 1bdbfb6ad6..91f4dbc1b3 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -1,12 +1,18 @@ import { FitAddon } from "@xterm/addon-fit"; import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react"; -import { type ThreadId } from "@t3tools/contracts"; +import { + type ScopedThreadRef, + type TerminalEvent, + type TerminalSessionSnapshot, + type ThreadId, +} from "@t3tools/contracts"; import { Terminal, type ITheme } from "@xterm/xterm"; import { type PointerEvent as ReactPointerEvent, type ReactNode, useCallback, useEffect, + useEffectEvent, useMemo, useRef, useState, @@ -15,9 +21,12 @@ import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover"; import { type TerminalContextSelection } from "~/lib/terminalContext"; import { openInPreferredEditor } from "../editorPreferences"; import { + collectWrappedTerminalLinkLine, extractTerminalLinks, isTerminalLinkActivation, resolvePathLinkTarget, + resolveWrappedTerminalLinkRange, + wrappedTerminalLinkRangeIntersectsBufferLine, } from "../terminal-links"; import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keybindings"; import { @@ -26,7 +35,9 @@ import { MAX_TERMINALS_PER_GROUP, type ThreadTerminalGroup, } from "../types"; -import { readNativeApi } from "~/nativeApi"; +import { readEnvironmentApi } from "~/environmentApi"; +import { readLocalApi } from "~/localApi"; +import { selectTerminalEventEntries, useTerminalStateStore } from "../terminalStateStore"; const MIN_DRAWER_HEIGHT = 180; const MAX_DRAWER_HEIGHT_RATIO = 0.75; @@ -47,12 +58,58 @@ function writeSystemMessage(terminal: Terminal, message: string): void { terminal.write(`\r\n[terminal] ${message}\r\n`); } -function terminalThemeFromApp(): ITheme { +function writeTerminalSnapshot(terminal: Terminal, snapshot: TerminalSessionSnapshot): void { + terminal.write("\u001bc"); + if (snapshot.history.length > 0) { + terminal.write(snapshot.history); + } +} + +export function selectTerminalEventEntriesAfterSnapshot( + entries: ReadonlyArray<{ id: number; event: TerminalEvent }>, + snapshotUpdatedAt: string, +): ReadonlyArray<{ id: number; event: TerminalEvent }> { + return entries.filter((entry) => entry.event.createdAt > snapshotUpdatedAt); +} + +export function selectPendingTerminalEventEntries( + entries: ReadonlyArray<{ id: number; event: TerminalEvent }>, + lastAppliedTerminalEventId: number, +): ReadonlyArray<{ id: number; event: TerminalEvent }> { + return entries.filter((entry) => entry.id > lastAppliedTerminalEventId); +} + +function normalizeComputedColor(value: string | null | undefined, fallback: string): string { + const normalizedValue = value?.trim().toLowerCase(); + if ( + !normalizedValue || + normalizedValue === "transparent" || + normalizedValue === "rgba(0, 0, 0, 0)" || + normalizedValue === "rgba(0 0 0 / 0)" + ) { + return fallback; + } + return value ?? fallback; +} + +function terminalThemeFromApp(mountElement?: HTMLElement | null): ITheme { const isDark = document.documentElement.classList.contains("dark"); + const fallbackBackground = isDark ? "rgb(14, 18, 24)" : "rgb(255, 255, 255)"; + const fallbackForeground = isDark ? "rgb(237, 241, 247)" : "rgb(28, 33, 41)"; + const drawerSurface = + mountElement?.closest(".thread-terminal-drawer") ?? + document.querySelector(".thread-terminal-drawer") ?? + document.body; + const drawerStyles = getComputedStyle(drawerSurface); const bodyStyles = getComputedStyle(document.body); - const background = - bodyStyles.backgroundColor || (isDark ? "rgb(14, 18, 24)" : "rgb(255, 255, 255)"); - const foreground = bodyStyles.color || (isDark ? "rgb(237, 241, 247)" : "rgb(28, 33, 41)"); + const background = normalizeComputedColor( + drawerStyles.backgroundColor, + normalizeComputedColor(bodyStyles.backgroundColor, fallbackBackground), + ); + const foreground = normalizeComputedColor( + drawerStyles.color, + normalizeComputedColor(bodyStyles.color, fallbackForeground), + ); if (isDark) { return { @@ -181,10 +238,12 @@ export function shouldHandleTerminalSelectionMouseUp( } interface TerminalViewportProps { + threadRef: ScopedThreadRef; threadId: ThreadId; terminalId: string; terminalLabel: string; cwd: string; + worktreePath?: string | null; runtimeEnv?: Record; onSessionExited: () => void; onAddTerminalContext: (selection: TerminalContextSelection) => void; @@ -194,11 +253,13 @@ interface TerminalViewportProps { drawerHeight: number; } -function TerminalViewport({ +export function TerminalViewport({ + threadRef, threadId, terminalId, terminalLabel, cwd, + worktreePath, runtimeEnv, onSessionExited, onAddTerminalContext, @@ -210,33 +271,31 @@ function TerminalViewport({ const containerRef = useRef(null); const terminalRef = useRef(null); const fitAddonRef = useRef(null); - const onSessionExitedRef = useRef(onSessionExited); - const onAddTerminalContextRef = useRef(onAddTerminalContext); - const terminalLabelRef = useRef(terminalLabel); + const environmentId = threadRef.environmentId; const hasHandledExitRef = useRef(false); const selectionPointerRef = useRef<{ x: number; y: number } | null>(null); const selectionGestureActiveRef = useRef(false); const selectionActionRequestIdRef = useRef(0); const selectionActionOpenRef = useRef(false); const selectionActionTimerRef = useRef(null); - - useEffect(() => { - onSessionExitedRef.current = onSessionExited; - }, [onSessionExited]); - - useEffect(() => { - onAddTerminalContextRef.current = onAddTerminalContext; - }, [onAddTerminalContext]); - - useEffect(() => { - terminalLabelRef.current = terminalLabel; - }, [terminalLabel]); + const lastAppliedTerminalEventIdRef = useRef(0); + const terminalHydratedRef = useRef(false); + const handleSessionExited = useEffectEvent(() => { + onSessionExited(); + }); + const handleAddTerminalContext = useEffectEvent((selection: TerminalContextSelection) => { + onAddTerminalContext(selection); + }); + const readTerminalLabel = useEffectEvent(() => terminalLabel); useEffect(() => { const mount = containerRef.current; if (!mount) return; let disposed = false; + const api = readEnvironmentApi(environmentId); + const localApi = readLocalApi(); + if (!api || !localApi) return; const fitAddon = new FitAddon(); const terminal = new Terminal({ @@ -245,7 +304,7 @@ function TerminalViewport({ fontSize: 12, scrollback: 5_000, fontFamily: '"SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace', - theme: terminalThemeFromApp(), + theme: terminalThemeFromApp(mount), }); terminal.loadAddon(fitAddon); terminal.open(mount); @@ -254,9 +313,6 @@ function TerminalViewport({ terminalRef.current = terminal; fitAddonRef.current = fitAddon; - const api = readNativeApi(); - if (!api) return; - const clearSelectionAction = () => { selectionActionRequestIdRef.current += 1; if (selectionActionTimerRef.current !== null) { @@ -297,7 +353,7 @@ function TerminalViewport({ position, selection: { terminalId, - terminalLabel: terminalLabelRef.current, + terminalLabel: readTerminalLabel(), lineStart, lineEnd, text: normalizedText, @@ -317,14 +373,14 @@ function TerminalViewport({ const requestId = ++selectionActionRequestIdRef.current; selectionActionOpenRef.current = true; try { - const clicked = await api.contextMenu.show( + const clicked = await localApi.contextMenu.show( [{ id: "add-to-chat", label: "Add to chat" }], nextAction.position, ); if (requestId !== selectionActionRequestIdRef.current || clicked !== "add-to-chat") { return; } - onAddTerminalContextRef.current(nextAction.selection); + handleAddTerminalContext(nextAction.selection); terminalRef.current?.clearSelection(); terminalRef.current?.focus(); } finally { @@ -366,26 +422,31 @@ function TerminalViewport({ return; } - const line = activeTerminal.buffer.active.getLine(bufferLineNumber - 1); - if (!line) { + const wrappedLine = collectWrappedTerminalLinkLine(bufferLineNumber, (bufferLineIndex) => + activeTerminal.buffer.active.getLine(bufferLineIndex), + ); + if (!wrappedLine) { callback(undefined); return; } - const lineText = line.translateToString(true); - const matches = extractTerminalLinks(lineText); - if (matches.length === 0) { + const links = extractTerminalLinks(wrappedLine.text) + .map((match) => ({ + match, + range: resolveWrappedTerminalLinkRange(wrappedLine, match), + })) + .filter(({ range }) => + wrappedTerminalLinkRangeIntersectsBufferLine(range, bufferLineNumber), + ); + if (links.length === 0) { callback(undefined); return; } callback( - matches.map((match) => ({ + links.map(({ match, range }) => ({ text: match.text, - range: { - start: { x: match.start + 1, y: bufferLineNumber }, - end: { x: match.end, y: bufferLineNumber }, - }, + range, activate: (event: MouseEvent) => { if (!isTerminalLinkActivation(event)) return; @@ -393,7 +454,7 @@ function TerminalViewport({ if (!latestTerminal) return; if (match.kind === "url") { - void api.shell.openExternal(match.text).catch((error) => { + void localApi.shell.openExternal(match.text).catch((error: unknown) => { writeSystemMessage( latestTerminal, error instanceof Error ? error.message : "Unable to open link", @@ -403,7 +464,7 @@ function TerminalViewport({ } const target = resolvePathLinkTarget(match.text, cwd); - void openInPreferredEditor(api, target).catch((error) => { + void openInPreferredEditor(localApi, target).catch((error) => { writeSystemMessage( latestTerminal, error instanceof Error ? error.message : "Unable to open path", @@ -461,7 +522,7 @@ function TerminalViewport({ const themeObserver = new MutationObserver(() => { const activeTerminal = terminalRef.current; if (!activeTerminal) return; - activeTerminal.options.theme = terminalThemeFromApp(); + activeTerminal.options.theme = terminalThemeFromApp(containerRef.current); activeTerminal.refresh(0, activeTerminal.rows - 1); }); themeObserver.observe(document.documentElement, { @@ -469,43 +530,15 @@ function TerminalViewport({ attributeFilter: ["class", "style"], }); - const openTerminal = async () => { - try { - const activeTerminal = terminalRef.current; - const activeFitAddon = fitAddonRef.current; - if (!activeTerminal || !activeFitAddon) return; - activeFitAddon.fit(); - const snapshot = await api.terminal.open({ - threadId, - terminalId, - cwd, - cols: activeTerminal.cols, - rows: activeTerminal.rows, - ...(runtimeEnv ? { env: runtimeEnv } : {}), - }); - if (disposed) return; - activeTerminal.write("\u001bc"); - if (snapshot.history.length > 0) { - activeTerminal.write(snapshot.history); - } - if (autoFocus) { - window.requestAnimationFrame(() => { - activeTerminal.focus(); - }); - } - } catch (err) { - if (disposed) return; - writeSystemMessage( - terminal, - err instanceof Error ? err.message : "Failed to open terminal", - ); - } - }; - - const unsubscribe = api?.terminal.onEvent((event) => { - if (event.threadId !== threadId || event.terminalId !== terminalId) return; + const applyTerminalEvent = (event: TerminalEvent) => { const activeTerminal = terminalRef.current; - if (!activeTerminal) return; + if (!activeTerminal) { + return; + } + + if (event.type === "activity") { + return; + } if (event.type === "output") { activeTerminal.write(event.data); @@ -516,10 +549,7 @@ function TerminalViewport({ if (event.type === "started" || event.type === "restarted") { hasHandledExitRef.current = false; clearSelectionAction(); - activeTerminal.write("\u001bc"); - if (event.snapshot.history.length > 0) { - activeTerminal.write(event.snapshot.history); - } + writeTerminalSnapshot(activeTerminal, event.snapshot); return; } @@ -535,30 +565,113 @@ function TerminalViewport({ return; } - if (event.type === "exited") { - const details = [ - typeof event.exitCode === "number" ? `code ${event.exitCode}` : null, - typeof event.exitSignal === "number" ? `signal ${event.exitSignal}` : null, - ] - .filter((value): value is string => value !== null) - .join(", "); - writeSystemMessage( - activeTerminal, - details.length > 0 ? `Process exited (${details})` : "Process exited", - ); - if (hasHandledExitRef.current) { + const details = [ + typeof event.exitCode === "number" ? `code ${event.exitCode}` : null, + typeof event.exitSignal === "number" ? `signal ${event.exitSignal}` : null, + ] + .filter((value): value is string => value !== null) + .join(", "); + writeSystemMessage( + activeTerminal, + details.length > 0 ? `Process exited (${details})` : "Process exited", + ); + if (hasHandledExitRef.current) { + return; + } + hasHandledExitRef.current = true; + window.setTimeout(() => { + if (!hasHandledExitRef.current) { return; } - hasHandledExitRef.current = true; - window.setTimeout(() => { - if (!hasHandledExitRef.current) { - return; - } - onSessionExitedRef.current(); - }, 0); + handleSessionExited(); + }, 0); + }; + const applyPendingTerminalEvents = ( + terminalEventEntries: ReadonlyArray<{ id: number; event: TerminalEvent }>, + ) => { + const pendingEntries = selectPendingTerminalEventEntries( + terminalEventEntries, + lastAppliedTerminalEventIdRef.current, + ); + if (pendingEntries.length === 0) { + return; } + for (const entry of pendingEntries) { + applyTerminalEvent(entry.event); + } + lastAppliedTerminalEventIdRef.current = + pendingEntries.at(-1)?.id ?? lastAppliedTerminalEventIdRef.current; + }; + + const unsubscribeTerminalEvents = useTerminalStateStore.subscribe((state, previousState) => { + if (!terminalHydratedRef.current) { + return; + } + + const previousLastEntryId = + selectTerminalEventEntries( + previousState.terminalEventEntriesByKey, + threadRef, + terminalId, + ).at(-1)?.id ?? 0; + const nextEntries = selectTerminalEventEntries( + state.terminalEventEntriesByKey, + threadRef, + terminalId, + ); + const nextLastEntryId = nextEntries.at(-1)?.id ?? 0; + if (nextLastEntryId === previousLastEntryId) { + return; + } + + applyPendingTerminalEvents(nextEntries); }); + const openTerminal = async () => { + try { + const activeTerminal = terminalRef.current; + const activeFitAddon = fitAddonRef.current; + if (!activeTerminal || !activeFitAddon) return; + activeFitAddon.fit(); + const snapshot = await api.terminal.open({ + threadId, + terminalId, + cwd, + ...(worktreePath !== undefined ? { worktreePath } : {}), + cols: activeTerminal.cols, + rows: activeTerminal.rows, + ...(runtimeEnv ? { env: runtimeEnv } : {}), + }); + if (disposed) return; + writeTerminalSnapshot(activeTerminal, snapshot); + const bufferedEntries = selectTerminalEventEntries( + useTerminalStateStore.getState().terminalEventEntriesByKey, + threadRef, + terminalId, + ); + const replayEntries = selectTerminalEventEntriesAfterSnapshot( + bufferedEntries, + snapshot.updatedAt, + ); + for (const entry of replayEntries) { + applyTerminalEvent(entry.event); + } + lastAppliedTerminalEventIdRef.current = bufferedEntries.at(-1)?.id ?? 0; + terminalHydratedRef.current = true; + if (autoFocus) { + window.requestAnimationFrame(() => { + activeTerminal.focus(); + }); + } + } catch (err) { + if (disposed) return; + writeSystemMessage( + terminal, + err instanceof Error ? err.message : "Failed to open terminal", + ); + } + }; + const fitTimer = window.setTimeout(() => { const activeTerminal = terminalRef.current; const activeFitAddon = fitAddonRef.current; @@ -582,8 +695,10 @@ function TerminalViewport({ return () => { disposed = true; + terminalHydratedRef.current = false; + lastAppliedTerminalEventIdRef.current = 0; + unsubscribeTerminalEvents(); window.clearTimeout(fitTimer); - unsubscribe(); inputDisposable.dispose(); selectionDisposable.dispose(); terminalLinksDisposable.dispose(); @@ -600,7 +715,7 @@ function TerminalViewport({ // autoFocus is intentionally omitted; // it is only read at mount time and must not trigger terminal teardown/recreation. // eslint-disable-next-line react-hooks/exhaustive-deps - }, [cwd, runtimeEnv, terminalId, threadId]); + }, [cwd, environmentId, runtimeEnv, terminalId, threadId]); useEffect(() => { if (!autoFocus) return; @@ -615,7 +730,7 @@ function TerminalViewport({ }, [autoFocus, focusRequestId]); useEffect(() => { - const api = readNativeApi(); + const api = readEnvironmentApi(environmentId); const terminal = terminalRef.current; const fitAddon = fitAddonRef.current; if (!api || !terminal || !fitAddon) return; @@ -637,16 +752,22 @@ function TerminalViewport({ return () => { window.cancelAnimationFrame(frame); }; - }, [drawerHeight, resizeEpoch, terminalId, threadId]); + }, [drawerHeight, environmentId, resizeEpoch, terminalId, threadId]); return ( -
+
); } interface ThreadTerminalDrawerProps { + threadRef: ScopedThreadRef; threadId: ThreadId; cwd: string; + worktreePath?: string | null; runtimeEnv?: Record; + visible?: boolean; height: number; terminalIds: string[]; activeTerminalId: string; @@ -694,9 +815,12 @@ function TerminalActionButton({ label, className, onClick, children }: TerminalA } export default function ThreadTerminalDrawer({ + threadRef, threadId, cwd, + worktreePath, runtimeEnv, + visible = true, height, terminalIds, activeTerminalId, @@ -911,6 +1035,10 @@ export default function ThreadTerminalDrawer({ ); useEffect(() => { + if (!visible) { + return; + } + const onWindowResize = () => { const clampedHeight = clampDrawerHeight(drawerHeightRef.current); const changed = clampedHeight !== drawerHeightRef.current; @@ -927,7 +1055,14 @@ export default function ThreadTerminalDrawer({ return () => { window.removeEventListener("resize", onWindowResize); }; - }, [syncHeight]); + }, [syncHeight, visible]); + + useEffect(() => { + if (!visible) { + return; + } + setResizeEpoch((value) => value + 1); + }, [visible]); useEffect(() => { return () => { @@ -1006,10 +1141,12 @@ export default function ThreadTerminalDrawer({ >
onCloseTerminal(terminalId)} onAddTerminalContext={onAddTerminalContext} @@ -1026,10 +1163,12 @@ export default function ThreadTerminalDrawer({
onCloseTerminal(resolvedActiveTerminalId)} onAddTerminalContext={onAddTerminalContext} diff --git a/apps/web/src/components/WebSocketConnectionSurface.logic.test.ts b/apps/web/src/components/WebSocketConnectionSurface.logic.test.ts new file mode 100644 index 0000000000..aed81ab01c --- /dev/null +++ b/apps/web/src/components/WebSocketConnectionSurface.logic.test.ts @@ -0,0 +1,113 @@ +import { describe, expect, it } from "vitest"; + +import type { WsConnectionStatus } from "../rpc/wsConnectionState"; +import { shouldAutoReconnect, shouldRestartStalledReconnect } from "./WebSocketConnectionSurface"; + +function makeStatus(overrides: Partial = {}): WsConnectionStatus { + return { + attemptCount: 0, + closeCode: null, + closeReason: null, + connectedAt: null, + disconnectedAt: null, + hasConnected: false, + lastError: null, + lastErrorAt: null, + nextRetryAt: null, + online: true, + phase: "idle", + reconnectAttemptCount: 0, + reconnectMaxAttempts: 8, + reconnectPhase: "idle", + socketUrl: null, + ...overrides, + }; +} + +describe("WebSocketConnectionSurface.logic", () => { + it("forces reconnect on online when the app was offline", () => { + expect( + shouldAutoReconnect( + makeStatus({ + disconnectedAt: "2026-04-03T20:00:00.000Z", + online: false, + phase: "disconnected", + }), + "online", + ), + ).toBe(true); + }); + + it("forces reconnect on focus only for previously connected disconnected states", () => { + expect( + shouldAutoReconnect( + makeStatus({ + hasConnected: true, + online: true, + phase: "disconnected", + reconnectAttemptCount: 3, + reconnectPhase: "waiting", + }), + "focus", + ), + ).toBe(true); + + expect( + shouldAutoReconnect( + makeStatus({ + hasConnected: false, + online: true, + phase: "disconnected", + reconnectAttemptCount: 1, + reconnectPhase: "waiting", + }), + "focus", + ), + ).toBe(false); + }); + + it("forces reconnect on focus for exhausted reconnect loops", () => { + expect( + shouldAutoReconnect( + makeStatus({ + hasConnected: true, + online: true, + phase: "disconnected", + reconnectAttemptCount: 8, + reconnectPhase: "exhausted", + }), + "focus", + ), + ).toBe(true); + }); + + it("restarts a stalled reconnect window after the scheduled retry time passes", () => { + expect( + shouldRestartStalledReconnect( + makeStatus({ + hasConnected: true, + nextRetryAt: "2026-04-03T20:00:01.000Z", + online: true, + phase: "disconnected", + reconnectAttemptCount: 3, + reconnectPhase: "waiting", + }), + "2026-04-03T20:00:01.000Z", + ), + ).toBe(true); + + expect( + shouldRestartStalledReconnect( + makeStatus({ + hasConnected: true, + nextRetryAt: "2026-04-03T20:00:01.000Z", + online: true, + phase: "disconnected", + reconnectAttemptCount: 3, + reconnectPhase: "attempting", + }), + "2026-04-03T20:00:01.000Z", + ), + ).toBe(false); + }); +}); diff --git a/apps/web/src/components/WebSocketConnectionSurface.tsx b/apps/web/src/components/WebSocketConnectionSurface.tsx new file mode 100644 index 0000000000..7b350e9849 --- /dev/null +++ b/apps/web/src/components/WebSocketConnectionSurface.tsx @@ -0,0 +1,390 @@ +import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react"; + +import { type SlowRpcAckRequest, useSlowRpcAckRequests } from "../rpc/requestLatencyState"; +import { + getWsConnectionStatus, + getWsConnectionUiState, + setBrowserOnlineStatus, + type WsConnectionStatus, + type WsConnectionUiState, + useWsConnectionStatus, + WS_RECONNECT_MAX_ATTEMPTS, +} from "../rpc/wsConnectionState"; +import { toastManager } from "./ui/toast"; +import { getPrimaryEnvironmentConnection } from "../environments/runtime"; + +const FORCED_WS_RECONNECT_DEBOUNCE_MS = 5_000; +type WsAutoReconnectTrigger = "focus" | "online"; + +const connectionTimeFormatter = new Intl.DateTimeFormat(undefined, { + day: "numeric", + hour: "numeric", + minute: "2-digit", + month: "short", + second: "2-digit", +}); + +function formatConnectionMoment(isoDate: string | null): string | null { + if (!isoDate) { + return null; + } + + return connectionTimeFormatter.format(new Date(isoDate)); +} + +function formatRetryCountdown(nextRetryAt: string, nowMs: number): string { + const remainingMs = Math.max(0, new Date(nextRetryAt).getTime() - nowMs); + return `${Math.max(1, Math.ceil(remainingMs / 1000))}s`; +} + +function describeOfflineToast(): string { + return "WebSocket disconnected. Waiting for network."; +} + +function formatReconnectAttemptLabel(status: WsConnectionStatus): string { + const reconnectAttempt = Math.max( + 1, + Math.min(status.reconnectAttemptCount, WS_RECONNECT_MAX_ATTEMPTS), + ); + return `Attempt ${reconnectAttempt}/${status.reconnectMaxAttempts}`; +} + +function describeExhaustedToast(): string { + return "Retries exhausted trying to reconnect"; +} + +function buildReconnectTitle(_status: WsConnectionStatus): string { + return "Disconnected from T3 Server"; +} + +function describeRecoveredToast( + previousDisconnectedAt: string | null, + connectedAt: string | null, +): string { + const reconnectedAtLabel = formatConnectionMoment(connectedAt); + const disconnectedAtLabel = formatConnectionMoment(previousDisconnectedAt); + + if (disconnectedAtLabel && reconnectedAtLabel) { + return `Disconnected at ${disconnectedAtLabel} and reconnected at ${reconnectedAtLabel}.`; + } + + if (reconnectedAtLabel) { + return `Connection restored at ${reconnectedAtLabel}.`; + } + + return "Connection restored."; +} + +function describeSlowRpcAckToast(requests: ReadonlyArray): ReactNode { + const count = requests.length; + const thresholdSeconds = Math.round((requests[0]?.thresholdMs ?? 0) / 1000); + + return `${count} request${count === 1 ? "" : "s"} waiting longer than ${thresholdSeconds}s.`; +} + +export function shouldAutoReconnect( + status: WsConnectionStatus, + trigger: WsAutoReconnectTrigger, +): boolean { + const uiState = getWsConnectionUiState(status); + + if (trigger === "online") { + return ( + uiState === "offline" || + uiState === "reconnecting" || + uiState === "error" || + status.reconnectPhase === "exhausted" + ); + } + + return ( + status.online && + status.hasConnected && + (uiState === "reconnecting" || status.reconnectPhase === "exhausted") + ); +} + +export function shouldRestartStalledReconnect( + status: WsConnectionStatus, + expectedNextRetryAt: string, +): boolean { + return ( + status.reconnectPhase === "waiting" && + status.nextRetryAt === expectedNextRetryAt && + status.online && + status.hasConnected + ); +} + +export function WebSocketConnectionCoordinator() { + const status = useWsConnectionStatus(); + const [nowMs, setNowMs] = useState(() => Date.now()); + const lastForcedReconnectAtRef = useRef(0); + const toastIdRef = useRef | null>(null); + const toastResetTimerRef = useRef(null); + const previousUiStateRef = useRef(getWsConnectionUiState(status)); + const previousDisconnectedAtRef = useRef(status.disconnectedAt); + + const runReconnect = useEffectEvent((showFailureToast: boolean) => { + if (toastResetTimerRef.current !== null) { + window.clearTimeout(toastResetTimerRef.current); + toastResetTimerRef.current = null; + } + lastForcedReconnectAtRef.current = Date.now(); + void getPrimaryEnvironmentConnection() + .reconnect() + .catch((error) => { + if (!showFailureToast) { + console.warn("Automatic WebSocket reconnect failed", { error }); + return; + } + toastManager.add({ + type: "error", + title: "Reconnect failed", + description: error instanceof Error ? error.message : "Unable to restart the WebSocket.", + data: { + dismissAfterVisibleMs: 8_000, + hideCopyButton: true, + }, + }); + }); + }); + const syncBrowserOnlineStatus = useEffectEvent(() => { + setBrowserOnlineStatus(navigator.onLine !== false); + }); + const triggerManualReconnect = useEffectEvent(() => { + runReconnect(true); + }); + const triggerAutoReconnect = useEffectEvent((trigger: WsAutoReconnectTrigger) => { + const currentStatus = + trigger === "online" ? setBrowserOnlineStatus(true) : getWsConnectionStatus(); + + if (!shouldAutoReconnect(currentStatus, trigger)) { + return; + } + if (Date.now() - lastForcedReconnectAtRef.current < FORCED_WS_RECONNECT_DEBOUNCE_MS) { + return; + } + + runReconnect(false); + }); + + useEffect(() => { + const handleOnline = () => { + triggerAutoReconnect("online"); + }; + const handleFocus = () => { + triggerAutoReconnect("focus"); + }; + + syncBrowserOnlineStatus(); + window.addEventListener("online", handleOnline); + window.addEventListener("offline", syncBrowserOnlineStatus); + window.addEventListener("focus", handleFocus); + return () => { + window.removeEventListener("online", handleOnline); + window.removeEventListener("offline", syncBrowserOnlineStatus); + window.removeEventListener("focus", handleFocus); + }; + }, []); + + useEffect(() => { + if (status.reconnectPhase !== "waiting" || status.nextRetryAt === null) { + return; + } + + setNowMs(Date.now()); + const intervalId = window.setInterval(() => { + setNowMs(Date.now()); + }, 1_000); + + return () => { + window.clearInterval(intervalId); + }; + }, [status.nextRetryAt, status.reconnectPhase]); + + useEffect(() => { + if ( + status.reconnectPhase !== "waiting" || + status.nextRetryAt === null || + !status.online || + !status.hasConnected + ) { + return; + } + + const nextRetryAt = status.nextRetryAt; + const timeoutMs = Math.max(0, new Date(nextRetryAt).getTime() - Date.now()) + 1_500; + const timeoutId = window.setTimeout(() => { + const currentStatus = getWsConnectionStatus(); + if (!shouldRestartStalledReconnect(currentStatus, nextRetryAt)) { + return; + } + + runReconnect(false); + }, timeoutMs); + + return () => { + window.clearTimeout(timeoutId); + }; + }, [ + status.hasConnected, + status.nextRetryAt, + status.online, + status.reconnectAttemptCount, + status.reconnectPhase, + ]); + + useEffect(() => { + const uiState = getWsConnectionUiState(status); + const previousUiState = previousUiStateRef.current; + const previousDisconnectedAt = previousDisconnectedAtRef.current; + const shouldShowReconnectToast = status.hasConnected && uiState === "reconnecting"; + const shouldShowOfflineToast = uiState === "offline" && status.disconnectedAt !== null; + const shouldShowExhaustedToast = status.hasConnected && status.reconnectPhase === "exhausted"; + + if ( + toastResetTimerRef.current !== null && + (shouldShowReconnectToast || shouldShowOfflineToast || shouldShowExhaustedToast) + ) { + window.clearTimeout(toastResetTimerRef.current); + toastResetTimerRef.current = null; + } + + if (shouldShowReconnectToast || shouldShowOfflineToast || shouldShowExhaustedToast) { + const toastPayload = shouldShowOfflineToast + ? { + description: describeOfflineToast(), + timeout: 0, + title: "Offline", + type: "warning" as const, + data: { + hideCopyButton: true, + }, + } + : shouldShowExhaustedToast + ? { + actionProps: { + children: "Retry", + onClick: triggerManualReconnect, + }, + description: describeExhaustedToast(), + timeout: 0, + title: "Disconnected from T3 Server", + type: "error" as const, + data: { + hideCopyButton: true, + }, + } + : { + actionProps: { + children: "Retry now", + onClick: triggerManualReconnect, + }, + description: + status.nextRetryAt === null + ? `Reconnecting... ${formatReconnectAttemptLabel(status)}` + : `Reconnecting in ${formatRetryCountdown(status.nextRetryAt, nowMs)}... ${formatReconnectAttemptLabel(status)}`, + timeout: 0, + title: buildReconnectTitle(status), + type: "loading" as const, + data: { + hideCopyButton: true, + }, + }; + + if (toastIdRef.current) { + toastManager.update(toastIdRef.current, toastPayload); + } else { + toastIdRef.current = toastManager.add(toastPayload); + } + } else if (toastIdRef.current) { + toastManager.close(toastIdRef.current); + toastIdRef.current = null; + } + + if ( + uiState === "connected" && + (previousUiState === "offline" || previousUiState === "reconnecting") && + previousDisconnectedAt !== null + ) { + const successToast = { + description: describeRecoveredToast(previousDisconnectedAt, status.connectedAt), + title: "Reconnected to T3 Server", + type: "success" as const, + timeout: 0, + data: { + dismissAfterVisibleMs: 8_000, + hideCopyButton: true, + }, + }; + + if (toastIdRef.current) { + toastManager.update(toastIdRef.current, successToast); + } else { + toastIdRef.current = toastManager.add(successToast); + } + + toastResetTimerRef.current = window.setTimeout(() => { + toastIdRef.current = null; + toastResetTimerRef.current = null; + }, 8_250); + } + + previousUiStateRef.current = uiState; + previousDisconnectedAtRef.current = status.disconnectedAt; + }, [nowMs, status]); + + useEffect(() => { + return () => { + if (toastResetTimerRef.current !== null) { + window.clearTimeout(toastResetTimerRef.current); + } + }; + }, []); + + return null; +} + +export function SlowRpcAckToastCoordinator() { + const slowRequests = useSlowRpcAckRequests(); + const status = useWsConnectionStatus(); + const toastIdRef = useRef | null>(null); + + useEffect(() => { + if (getWsConnectionUiState(status) !== "connected") { + if (toastIdRef.current) { + toastManager.close(toastIdRef.current); + toastIdRef.current = null; + } + return; + } + + if (slowRequests.length === 0) { + if (toastIdRef.current) { + toastManager.close(toastIdRef.current); + toastIdRef.current = null; + } + return; + } + + const nextToast = { + description: describeSlowRpcAckToast(slowRequests), + timeout: 0, + title: "Some requests are slow", + type: "warning" as const, + }; + + if (toastIdRef.current) { + toastManager.update(toastIdRef.current, nextToast); + } else { + toastIdRef.current = toastManager.add(nextToast); + } + }, [slowRequests, status]); + + return null; +} + +export function WebSocketConnectionSurface({ children }: { readonly children: ReactNode }) { + return children; +} diff --git a/apps/web/src/components/auth/PairingRouteSurface.tsx b/apps/web/src/components/auth/PairingRouteSurface.tsx new file mode 100644 index 0000000000..f583af72ec --- /dev/null +++ b/apps/web/src/components/auth/PairingRouteSurface.tsx @@ -0,0 +1,195 @@ +import type { AuthSessionState } from "@t3tools/contracts"; +import React, { startTransition, useEffect, useRef, useState, useCallback } from "react"; + +import { APP_DISPLAY_NAME } from "../../branding"; +import { + peekPairingTokenFromUrl, + stripPairingTokenFromUrl, + submitServerAuthCredential, +} from "../../environments/primary"; +import { Button } from "../ui/button"; +import { Input } from "../ui/input"; + +export function PairingPendingSurface() { + return ( +
+
+
+
+
+
+ +
+

+ {APP_DISPLAY_NAME} +

+

+ Pairing with this environment +

+

+ Validating the pairing link and preparing your session. +

+
+
+ ); +} + +export function PairingRouteSurface({ + auth, + initialErrorMessage, + onAuthenticated, +}: { + auth: AuthSessionState["auth"]; + initialErrorMessage?: string; + onAuthenticated: () => void; +}) { + const autoPairTokenRef = useRef(peekPairingTokenFromUrl()); + const [credential, setCredential] = useState(() => autoPairTokenRef.current ?? ""); + const [errorMessage, setErrorMessage] = useState(initialErrorMessage ?? ""); + const [isSubmitting, setIsSubmitting] = useState(false); + const autoSubmitAttemptedRef = useRef(false); + + const submitCredential = useCallback( + async (nextCredential: string) => { + setIsSubmitting(true); + setErrorMessage(""); + + const submitError = await submitServerAuthCredential(nextCredential).then( + () => null, + (error) => errorMessageFromUnknown(error), + ); + + setIsSubmitting(false); + + if (submitError) { + setErrorMessage(submitError); + return; + } + + startTransition(() => { + onAuthenticated(); + }); + }, + [onAuthenticated], + ); + + const handleSubmit = useCallback( + async (event?: React.SubmitEvent) => { + event?.preventDefault(); + await submitCredential(credential); + }, + [submitCredential, credential], + ); + + useEffect(() => { + const token = autoPairTokenRef.current; + if (!token || autoSubmitAttemptedRef.current) { + return; + } + + autoSubmitAttemptedRef.current = true; + stripPairingTokenFromUrl(); + void submitCredential(token); + }, [submitCredential]); + + return ( +
+
+
+
+
+
+ +
+

+ {APP_DISPLAY_NAME} +

+

+ Pair with this environment +

+

+ {describeAuthGate(auth.bootstrapMethods)} +

+ +
void handleSubmit(event)}> +
+ + setCredential(event.currentTarget.value)} + placeholder="Paste a one-time token or pairing secret" + spellCheck={false} + value={credential} + /> +
+ + {errorMessage ? ( +
+ {errorMessage} +
+ ) : null} + +
+ + +
+
+ +
+ {describeSupportedMethods(auth.bootstrapMethods)} +
+
+
+ ); +} + +function errorMessageFromUnknown(error: unknown): string { + if (error instanceof Error && error.message.trim().length > 0) { + return error.message; + } + + if (typeof error === "string" && error.trim().length > 0) { + return error; + } + + return "Authentication failed."; +} + +function describeAuthGate(bootstrapMethods: ReadonlyArray): string { + if (bootstrapMethods.includes("desktop-bootstrap")) { + return "This environment expects a trusted pairing credential before the app can connect."; + } + + return "Enter a pairing token to start a session with this environment."; +} + +function describeSupportedMethods(bootstrapMethods: ReadonlyArray): string { + if ( + bootstrapMethods.includes("desktop-bootstrap") && + bootstrapMethods.includes("one-time-token") + ) { + return "Desktop-managed pairing and one-time pairing tokens are both accepted for this environment."; + } + + if (bootstrapMethods.includes("desktop-bootstrap")) { + return "This environment is desktop-managed. Open it from the desktop app or paste a bootstrap credential if one was issued explicitly."; + } + + return "This environment accepts one-time pairing tokens. Pairing links can open this page directly, or you can paste the token here."; +} diff --git a/apps/web/src/components/chat/ChangedFilesTree.test.tsx b/apps/web/src/components/chat/ChangedFilesTree.test.tsx new file mode 100644 index 0000000000..4e2a12ee12 --- /dev/null +++ b/apps/web/src/components/chat/ChangedFilesTree.test.tsx @@ -0,0 +1,116 @@ +import { TurnId } from "@t3tools/contracts"; +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; + +import { ChangedFilesTree } from "./ChangedFilesTree"; + +describe("ChangedFilesTree", () => { + it.each([ + { + name: "a compacted single-chain directory", + files: [ + { path: "apps/web/src/index.ts", additions: 2, deletions: 1 }, + { path: "apps/web/src/main.ts", additions: 3, deletions: 0 }, + ], + visibleLabels: ["apps/web/src"], + hiddenLabels: ["index.ts", "main.ts"], + }, + { + name: "a branch point after a compacted prefix", + files: [ + { path: "apps/server/src/git/Layers/GitCore.ts", additions: 4, deletions: 3 }, + { path: "apps/server/src/provider/Layers/CodexAdapter.ts", additions: 7, deletions: 2 }, + ], + visibleLabels: ["apps/server/src"], + hiddenLabels: ["git", "provider", "GitCore.ts", "CodexAdapter.ts"], + }, + { + name: "mixed root files and nested compacted directories", + files: [ + { path: "README.md", additions: 1, deletions: 0 }, + { path: "packages/shared/src/git.ts", additions: 8, deletions: 2 }, + { path: "packages/contracts/src/orchestration.ts", additions: 13, deletions: 3 }, + ], + visibleLabels: ["README.md", "packages"], + hiddenLabels: ["shared/src", "contracts/src", "git.ts", "orchestration.ts"], + }, + ])( + "renders $name collapsed on the first render when collapse-all is active", + ({ files, visibleLabels, hiddenLabels }) => { + const markup = renderToStaticMarkup( + {}} + />, + ); + + for (const label of visibleLabels) { + expect(markup).toContain(label); + } + for (const label of hiddenLabels) { + expect(markup).not.toContain(label); + } + }, + ); + + it.each([ + { + name: "a compacted single-chain directory", + files: [ + { path: "apps/web/src/index.ts", additions: 2, deletions: 1 }, + { path: "apps/web/src/main.ts", additions: 3, deletions: 0 }, + ], + visibleLabels: ["apps/web/src", "index.ts", "main.ts"], + }, + { + name: "a branch point after a compacted prefix", + files: [ + { path: "apps/server/src/git/Layers/GitCore.ts", additions: 4, deletions: 3 }, + { path: "apps/server/src/provider/Layers/CodexAdapter.ts", additions: 7, deletions: 2 }, + ], + visibleLabels: [ + "apps/server/src", + "git/Layers", + "provider/Layers", + "GitCore.ts", + "CodexAdapter.ts", + ], + }, + { + name: "mixed root files and nested compacted directories", + files: [ + { path: "README.md", additions: 1, deletions: 0 }, + { path: "packages/shared/src/git.ts", additions: 8, deletions: 2 }, + { path: "packages/contracts/src/orchestration.ts", additions: 13, deletions: 3 }, + ], + visibleLabels: [ + "README.md", + "packages", + "shared/src", + "contracts/src", + "git.ts", + "orchestration.ts", + ], + }, + ])( + "renders $name expanded on the first render when expand-all is active", + ({ files, visibleLabels }) => { + const markup = renderToStaticMarkup( + {}} + />, + ); + + for (const label of visibleLabels) { + expect(markup).toContain(label); + } + }, + ); +}); diff --git a/apps/web/src/components/chat/ChangedFilesTree.tsx b/apps/web/src/components/chat/ChangedFilesTree.tsx index a13ddad30d..29bd96ea05 100644 --- a/apps/web/src/components/chat/ChangedFilesTree.tsx +++ b/apps/web/src/components/chat/ChangedFilesTree.tsx @@ -1,5 +1,5 @@ import { type TurnId } from "@t3tools/contracts"; -import { memo, useCallback, useEffect, useMemo, useState } from "react"; +import { memo, useCallback, useMemo, useState } from "react"; import { type TurnDiffFileChange } from "../../types"; import { buildTurnDiffTree, type TurnDiffTreeNode } from "../../lib/turnDiffTree"; import { ChevronRightIcon, FolderIcon, FolderClosedIcon } from "lucide-react"; @@ -7,6 +7,8 @@ import { cn } from "~/lib/utils"; import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel"; import { VscodeEntryIcon } from "./VscodeEntryIcon"; +const EMPTY_DIRECTORY_OVERRIDES: Record = {}; + export const ChangedFilesTree = memo(function ChangedFilesTree(props: { turnId: TurnId; files: ReadonlyArray; @@ -20,32 +22,39 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: { () => collectDirectoryPaths(treeNodes).join("\u0000"), [treeNodes], ); - const allDirectoryExpansionState = useMemo( - () => - buildDirectoryExpansionState( - directoryPathsKey ? directoryPathsKey.split("\u0000") : [], - allDirectoriesExpanded, - ), - [allDirectoriesExpanded, directoryPathsKey], - ); - const [expandedDirectories, setExpandedDirectories] = useState>(() => - buildDirectoryExpansionState(directoryPathsKey ? directoryPathsKey.split("\u0000") : [], true), - ); - useEffect(() => { - setExpandedDirectories(allDirectoryExpansionState); - }, [allDirectoryExpansionState]); + const expansionStateKey = `${allDirectoriesExpanded ? "expanded" : "collapsed"}\u0000${directoryPathsKey}`; + const [directoryExpansionState, setDirectoryExpansionState] = useState<{ + key: string; + overrides: Record; + }>(() => ({ + key: expansionStateKey, + overrides: {}, + })); + const expandedDirectories = + directoryExpansionState.key === expansionStateKey + ? directoryExpansionState.overrides + : EMPTY_DIRECTORY_OVERRIDES; - const toggleDirectory = useCallback((pathValue: string, fallbackExpanded: boolean) => { - setExpandedDirectories((current) => ({ - ...current, - [pathValue]: !(current[pathValue] ?? fallbackExpanded), - })); - }, []); + const toggleDirectory = useCallback( + (pathValue: string) => { + setDirectoryExpansionState((current) => { + const nextOverrides = current.key === expansionStateKey ? current.overrides : {}; + return { + key: expansionStateKey, + overrides: { + ...nextOverrides, + [pathValue]: !(nextOverrides[pathValue] ?? allDirectoriesExpanded), + }, + }; + }); + }, + [allDirectoriesExpanded, expansionStateKey], + ); const renderTreeNode = (node: TurnDiffTreeNode, depth: number) => { const leftPadding = 8 + depth * 14; if (node.kind === "directory") { - const isExpanded = expandedDirectories[node.path] ?? depth === 0; + const isExpanded = expandedDirectories[node.path] ?? allDirectoriesExpanded; return (
+ + + + + + {props.showPlanToggle ? ( + <> + + + + ) : null} + + ); +}); + +const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(props: { + compact: boolean; + activeContextWindow: ReturnType; + isPreparingWorktree: boolean; + pendingAction: { + questionIndex: number; + isLastQuestion: boolean; + canAdvance: boolean; + isResponding: boolean; + isComplete: boolean; + } | null; + isRunning: boolean; + showPlanFollowUpPrompt: boolean; + promptHasText: boolean; + isSendBusy: boolean; + isConnecting: boolean; + hasSendableContent: boolean; + onPreviousPendingQuestion: () => void; + onInterrupt: () => void; + onImplementPlanInNewThread: () => void; +}) { + return ( + <> + {props.activeContextWindow ? : null} + {props.isPreparingWorktree ? ( + Preparing worktree... + ) : null} + + + ); +}); + +// -------------------------------------------------------------------------- +// Handle exposed to ChatView +// -------------------------------------------------------------------------- + +export interface ChatComposerHandle { + focusAtEnd: () => void; + focusAt: (cursor: number) => void; + readSnapshot: () => { + value: string; + cursor: number; + expandedCursor: number; + terminalContextIds: string[]; + }; + /** Reset composer cursor/trigger/highlight after external prompt mutations (e.g. onSend). */ + resetCursorState: (options?: { + cursor?: number; + prompt?: string; + detectTrigger?: boolean; + }) => void; + /** Insert a terminal context from the terminal drawer. */ + addTerminalContext: (selection: TerminalContextSelection) => void; + /** Get the current prompt/effort/model state for use in send. */ + getSendContext: () => { + prompt: string; + images: ComposerImageAttachment[]; + terminalContexts: TerminalContextDraft[]; + selectedPromptEffort: string | null; + selectedModelOptionsForDispatch: unknown; + selectedModelSelection: ModelSelection; + selectedProvider: ProviderKind; + selectedModel: string; + selectedProviderModels: ReadonlyArray; + }; +} + +// -------------------------------------------------------------------------- +// Props +// -------------------------------------------------------------------------- + +export interface ChatComposerProps { + composerDraftTarget: ScopedThreadRef | DraftId; + environmentId: EnvironmentId; + routeKind: "server" | "draft"; + routeThreadRef: ScopedThreadRef; + draftId: DraftId | null; + + // Thread context + activeThreadId: ThreadId | null; + activeThreadEnvironmentId: EnvironmentId | undefined; + activeThread: Thread | undefined; + isServerThread: boolean; + isLocalDraftThread: boolean; + + // Session phase + phase: SessionPhase; + isConnecting: boolean; + isSendBusy: boolean; + isPreparingWorktree: boolean; + + // Pending approvals / inputs + activePendingApproval: PendingApproval | null; + pendingApprovals: PendingApproval[]; + pendingUserInputs: PendingUserInput[]; + activePendingProgress: { + questionIndex: number; + isLastQuestion: boolean; + canAdvance: boolean; + customAnswer: string; + activeQuestion: { id: string } | null; + } | null; + activePendingResolvedAnswers: Record | null; + activePendingIsResponding: boolean; + activePendingDraftAnswers: Record; + activePendingQuestionIndex: number; + respondingRequestIds: ApprovalRequestId[]; + + // Plan + showPlanFollowUpPrompt: boolean; + activeProposedPlan: Thread["proposedPlans"][number] | null; + activePlan: { turnId?: TurnId } | null; + sidebarProposedPlan: { turnId?: TurnId } | null; + planSidebarOpen: boolean; + + // Mode + runtimeMode: RuntimeMode; + interactionMode: ProviderInteractionMode; + + // Provider / model + lockedProvider: ProviderKind | null; + providerStatuses: ServerProvider[]; + activeProjectDefaultModelSelection: ModelSelection | null | undefined; + activeThreadModelSelection: ModelSelection | null | undefined; + + // Context window + activeThreadActivities: Thread["activities"] | undefined; + + // Misc + resolvedTheme: "light" | "dark"; + settings: UnifiedSettings; + gitCwd: string | null; + + // Refs the parent needs kept in sync + promptRef: React.MutableRefObject; + composerImagesRef: React.MutableRefObject; + composerTerminalContextsRef: React.MutableRefObject; + + // Scroll + shouldAutoScrollRef: React.MutableRefObject; + scheduleStickToBottom: () => void; + + // Callbacks + onSend: (e?: { preventDefault: () => void }) => void; + onInterrupt: () => void; + onImplementPlanInNewThread: () => void; + onRespondToApproval: ( + requestId: ApprovalRequestId, + decision: ProviderApprovalDecision, + ) => Promise; + onSelectActivePendingUserInputOption: (questionId: string, optionLabel: string) => void; + onAdvanceActivePendingUserInput: () => void; + onPreviousActivePendingUserInputQuestion: () => void; + onChangeActivePendingUserInputCustomAnswer: ( + questionId: string, + value: string, + nextCursor: number, + expandedCursor: number, + cursorAdjacentToMention: boolean, + ) => void; + + onProviderModelSelect: (provider: ProviderKind, model: string) => void; + toggleInteractionMode: () => void; + handleRuntimeModeChange: (mode: RuntimeMode) => void; + handleInteractionModeChange: (mode: ProviderInteractionMode) => void; + togglePlanSidebar: () => void; + + focusComposer: () => void; + scheduleComposerFocus: () => void; + setThreadError: (threadId: ThreadId | null, error: string | null) => void; + onExpandImage: (preview: ExpandedImagePreview) => void; +} + +// -------------------------------------------------------------------------- +// Component +// -------------------------------------------------------------------------- + +export const ChatComposer = memo( + forwardRef(function ChatComposer(props, ref) { + const { + composerDraftTarget, + environmentId, + routeKind, + routeThreadRef, + draftId, + activeThreadId, + activeThreadEnvironmentId: _activeThreadEnvironmentId, + activeThread, + isServerThread: _isServerThread, + isLocalDraftThread: _isLocalDraftThread, + phase, + isConnecting, + isSendBusy, + isPreparingWorktree, + activePendingApproval, + pendingApprovals, + pendingUserInputs, + activePendingProgress, + activePendingResolvedAnswers, + activePendingIsResponding, + activePendingDraftAnswers, + activePendingQuestionIndex, + respondingRequestIds, + showPlanFollowUpPrompt, + activeProposedPlan, + activePlan, + sidebarProposedPlan, + planSidebarOpen, + runtimeMode, + interactionMode, + lockedProvider, + providerStatuses, + activeProjectDefaultModelSelection, + activeThreadModelSelection, + activeThreadActivities, + resolvedTheme, + settings, + gitCwd, + promptRef, + composerImagesRef, + composerTerminalContextsRef, + shouldAutoScrollRef, + scheduleStickToBottom, + onSend, + onInterrupt, + onImplementPlanInNewThread, + onRespondToApproval, + onSelectActivePendingUserInputOption, + onAdvanceActivePendingUserInput, + onPreviousActivePendingUserInputQuestion, + onChangeActivePendingUserInputCustomAnswer, + onProviderModelSelect, + toggleInteractionMode, + handleRuntimeModeChange, + handleInteractionModeChange, + togglePlanSidebar, + focusComposer, + scheduleComposerFocus, + setThreadError, + onExpandImage, + } = props; + + // ------------------------------------------------------------------ + // Store subscriptions (prompt / images / terminal contexts) + // ------------------------------------------------------------------ + const composerDraft = useComposerThreadDraft(composerDraftTarget); + const prompt = composerDraft.prompt; + const composerImages = composerDraft.images; + const composerTerminalContexts = composerDraft.terminalContexts; + const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds; + + const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt); + const addComposerDraftImage = useComposerDraftStore((store) => store.addImage); + const addComposerDraftImages = useComposerDraftStore((store) => store.addImages); + const removeComposerDraftImage = useComposerDraftStore((store) => store.removeImage); + const insertComposerDraftTerminalContext = useComposerDraftStore( + (store) => store.insertTerminalContext, + ); + const removeComposerDraftTerminalContext = useComposerDraftStore( + (store) => store.removeTerminalContext, + ); + const setComposerDraftTerminalContexts = useComposerDraftStore( + (store) => store.setTerminalContexts, + ); + const clearComposerDraftPersistedAttachments = useComposerDraftStore( + (store) => store.clearPersistedAttachments, + ); + const syncComposerDraftPersistedAttachments = useComposerDraftStore( + (store) => store.syncPersistedAttachments, + ); + const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft); + + // ------------------------------------------------------------------ + // Model state + // ------------------------------------------------------------------ + const selectedProviderByThreadId = composerDraft.activeProvider ?? null; + const threadProvider = + activeThreadModelSelection?.provider ?? activeProjectDefaultModelSelection?.provider ?? null; + + const unlockedSelectedProvider = resolveSelectableProvider( + providerStatuses, + selectedProviderByThreadId ?? threadProvider ?? "codex", + ); + const selectedProvider: ProviderKind = lockedProvider ?? unlockedSelectedProvider; + + const { modelOptions: composerModelOptions, selectedModel } = useEffectiveComposerModelState({ + threadRef: composerDraftTarget, + providers: providerStatuses, + selectedProvider, + threadModelSelection: activeThreadModelSelection, + projectModelSelection: activeProjectDefaultModelSelection, + settings, + }); + + const selectedProviderModels = getProviderModels(providerStatuses, selectedProvider); + const selectedProviderStatus = useMemo( + () => providerStatuses.find((provider) => provider.provider === selectedProvider), + [providerStatuses, selectedProvider], + ); + + const composerProviderState = useMemo( + () => + getComposerProviderState({ + provider: selectedProvider, + model: selectedModel, + models: selectedProviderModels, + prompt, + modelOptions: composerModelOptions, + }), + [composerModelOptions, prompt, selectedModel, selectedProvider, selectedProviderModels], + ); + + const selectedPromptEffort = composerProviderState.promptEffort; + const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch; + const selectedModelSelection = useMemo( + () => ({ + provider: selectedProvider, + model: selectedModel, + ...(selectedModelOptionsForDispatch ? { options: selectedModelOptionsForDispatch } : {}), + }), + [selectedModel, selectedModelOptionsForDispatch, selectedProvider], + ); + const selectedModelForPicker = selectedModel; + const modelOptionsByProvider = useMemo< + Record> + >( + () => ({ + codex: providerStatuses.find((provider) => provider.provider === "codex")?.models ?? [], + claudeAgent: + providerStatuses.find((provider) => provider.provider === "claudeAgent")?.models ?? [], + }), + [providerStatuses], + ); + const selectedModelForPickerWithCustomFallback = useMemo(() => { + const currentOptions = modelOptionsByProvider[selectedProvider]; + return currentOptions.some((option) => option.slug === selectedModelForPicker) + ? selectedModelForPicker + : (normalizeModelSlug(selectedModelForPicker, selectedProvider) ?? selectedModelForPicker); + }, [modelOptionsByProvider, selectedModelForPicker, selectedProvider]); + const searchableModelOptions = useMemo( + () => + AVAILABLE_PROVIDER_OPTIONS.filter( + (option) => lockedProvider === null || option.value === lockedProvider, + ).flatMap((option) => + modelOptionsByProvider[option.value].map(({ slug, name }) => ({ + provider: option.value, + providerLabel: option.label, + slug, + name, + searchSlug: slug.toLowerCase(), + searchName: name.toLowerCase(), + searchProvider: option.label.toLowerCase(), + })), + ), + [lockedProvider, modelOptionsByProvider], + ); + + // ------------------------------------------------------------------ + // Context window + // ------------------------------------------------------------------ + const activeContextWindow = useMemo( + () => deriveLatestContextWindowSnapshot(activeThreadActivities ?? []), + [activeThreadActivities], + ); + + // ------------------------------------------------------------------ + // Composer-local state + // ------------------------------------------------------------------ + const [composerCursor, setComposerCursor] = useState(() => + collapseExpandedComposerCursor(prompt, prompt.length), + ); + const [composerTrigger, setComposerTrigger] = useState(() => + detectComposerTrigger(prompt, prompt.length), + ); + const [composerHighlightedItemId, setComposerHighlightedItemId] = useState(null); + const [composerHighlightedSearchKey, setComposerHighlightedSearchKey] = useState( + null, + ); + const [isDragOverComposer, setIsDragOverComposer] = useState(false); + const [isComposerFooterCompact, setIsComposerFooterCompact] = useState(false); + const [isComposerPrimaryActionsCompact, setIsComposerPrimaryActionsCompact] = useState(false); + + // ------------------------------------------------------------------ + // Refs + // ------------------------------------------------------------------ + const composerEditorRef = useRef(null); + const composerFormRef = useRef(null); + const composerFormHeightRef = useRef(0); + const composerSelectLockRef = useRef(false); + const composerMenuOpenRef = useRef(false); + const composerMenuItemsRef = useRef([]); + const activeComposerMenuItemRef = useRef(null); + const dragDepthRef = useRef(0); + + // ------------------------------------------------------------------ + // Derived: composer send state + // ------------------------------------------------------------------ + const composerSendState = useMemo( + () => + deriveComposerSendState({ + prompt, + imageCount: composerImages.length, + terminalContexts: composerTerminalContexts, + }), + [composerImages.length, composerTerminalContexts, prompt], + ); + + // ------------------------------------------------------------------ + // Derived: composer trigger / menu + // ------------------------------------------------------------------ + const composerTriggerKind = composerTrigger?.kind ?? null; + const pathTriggerQuery = composerTrigger?.kind === "path" ? composerTrigger.query : ""; + const isPathTrigger = composerTriggerKind === "path"; + const [debouncedPathQuery, composerPathQueryDebouncer] = useDebouncedValue( + pathTriggerQuery, + { wait: COMPOSER_PATH_QUERY_DEBOUNCE_MS }, + (debouncerState) => ({ isPending: debouncerState.isPending }), + ); + const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : ""; + const workspaceEntriesQuery = useQuery( + projectSearchEntriesQueryOptions({ + environmentId, + cwd: gitCwd, + query: effectivePathQuery, + enabled: isPathTrigger, + limit: 80, + }), + ); + const workspaceEntries = workspaceEntriesQuery.data?.entries ?? EMPTY_PROJECT_ENTRIES; + + const composerMenuItems = useMemo(() => { + if (!composerTrigger) return []; + if (composerTrigger.kind === "path") { + return workspaceEntries.map((entry) => ({ + id: `path:${entry.kind}:${entry.path}`, + type: "path", + path: entry.path, + pathKind: entry.kind, + label: basenameOfPath(entry.path), + description: entry.parentPath ?? "", + })); + } + if (composerTrigger.kind === "slash-command") { + const builtInSlashCommandItems = [ + { + id: "slash:model", + type: "slash-command", + command: "model", + label: "/model", + description: "Switch response model for this thread", + }, + { + id: "slash:plan", + type: "slash-command", + command: "plan", + label: "/plan", + description: "Switch this thread into plan mode", + }, + { + id: "slash:default", + type: "slash-command", + command: "default", + label: "/default", + description: "Switch this thread back to normal build mode", + }, + ] satisfies ReadonlyArray>; + const providerSlashCommandItems = (selectedProviderStatus?.slashCommands ?? []).map( + (command) => ({ + id: `provider-slash-command:${selectedProvider}:${command.name}`, + type: "provider-slash-command" as const, + provider: selectedProvider, + command, + label: `/${command.name}`, + description: command.description ?? command.input?.hint ?? "Run provider command", + }), + ); + const query = composerTrigger.query.trim().toLowerCase(); + const slashCommandItems = [...builtInSlashCommandItems, ...providerSlashCommandItems]; + if (!query) { + return slashCommandItems; + } + return searchSlashCommandItems(slashCommandItems, query); + } + if (composerTrigger.kind === "skill") { + return searchProviderSkills( + selectedProviderStatus?.skills ?? [], + composerTrigger.query, + ).map((skill) => ({ + id: `skill:${selectedProvider}:${skill.name}`, + type: "skill" as const, + provider: selectedProvider, + skill, + label: formatProviderSkillDisplayName(skill), + description: + skill.shortDescription ?? + skill.description ?? + (skill.scope ? `${skill.scope} skill` : "Run provider skill"), + })); + } + return searchableModelOptions + .filter(({ searchSlug, searchName, searchProvider }) => { + const query = composerTrigger.query.trim().toLowerCase(); + if (!query) return true; + return ( + searchSlug.includes(query) || + searchName.includes(query) || + searchProvider.includes(query) + ); + }) + .map(({ provider, providerLabel, slug, name }) => ({ + id: `model:${provider}:${slug}`, + type: "model", + provider, + model: slug, + label: name, + description: `${providerLabel} · ${slug}`, + })); + }, [ + composerTrigger, + searchableModelOptions, + selectedProvider, + selectedProviderStatus, + workspaceEntries, + ]); + + const composerMenuOpen = Boolean(composerTrigger); + const composerMenuSearchKey = composerTrigger + ? `${composerTrigger.kind}:${composerTrigger.query.trim().toLowerCase()}` + : null; + const activeComposerMenuItem = useMemo(() => { + const activeItemId = resolveComposerMenuActiveItemId({ + items: composerMenuItems, + highlightedItemId: composerHighlightedItemId, + currentSearchKey: composerMenuSearchKey, + highlightedSearchKey: composerHighlightedSearchKey, + }); + return composerMenuItems.find((item) => item.id === activeItemId) ?? null; + }, [ + composerHighlightedItemId, + composerHighlightedSearchKey, + composerMenuItems, + composerMenuSearchKey, + ]); + + composerMenuOpenRef.current = composerMenuOpen; + composerMenuItemsRef.current = composerMenuItems; + activeComposerMenuItemRef.current = activeComposerMenuItem; + + const nonPersistedComposerImageIdSet = useMemo( + () => new Set(nonPersistedComposerImageIds), + [nonPersistedComposerImageIds], + ); + + const isComposerApprovalState = activePendingApproval !== null; + const activePendingUserInput = pendingUserInputs[0] ?? null; + const hasComposerHeader = + isComposerApprovalState || + pendingUserInputs.length > 0 || + (showPlanFollowUpPrompt && activeProposedPlan !== null); + + const composerFooterHasWideActions = showPlanFollowUpPrompt || activePendingProgress !== null; + const showPlanSidebarToggle = Boolean(activePlan || sidebarProposedPlan || planSidebarOpen); + 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 isComposerMenuLoading = + composerTriggerKind === "path" && + ((pathTriggerQuery.length > 0 && composerPathQueryDebouncer.state.isPending) || + workspaceEntriesQuery.isLoading || + workspaceEntriesQuery.isFetching); + const composerMenuEmptyState = useMemo(() => { + if (composerTriggerKind === "skill") { + return "No skills found. Try / to browse provider commands."; + } + return composerTriggerKind === "path" + ? "No matching files or folders." + : "No matching command."; + }, [composerTriggerKind]); + + // ------------------------------------------------------------------ + // Provider traits UI + // ------------------------------------------------------------------ + const setPromptFromTraits = useCallback( + (nextPrompt: string) => { + if (nextPrompt === promptRef.current) { + scheduleComposerFocus(); + return; + } + promptRef.current = nextPrompt; + setComposerDraftPrompt(composerDraftTarget, nextPrompt); + const nextCursor = collapseExpandedComposerCursor(nextPrompt, nextPrompt.length); + setComposerCursor(nextCursor); + setComposerTrigger(detectComposerTrigger(nextPrompt, nextPrompt.length)); + scheduleComposerFocus(); + }, + [composerDraftTarget, promptRef, scheduleComposerFocus, setComposerDraftPrompt], + ); + + const providerTraitsMenuContent = renderProviderTraitsMenuContent({ + provider: selectedProvider, + ...(routeKind === "server" ? { threadRef: routeThreadRef } : {}), + ...(routeKind === "draft" && draftId ? { draftId } : {}), + model: selectedModel, + models: selectedProviderModels, + modelOptions: composerModelOptions?.[selectedProvider], + prompt, + onPromptChange: setPromptFromTraits, + }); + const providerTraitsPicker = renderProviderTraitsPicker({ + provider: selectedProvider, + ...(routeKind === "server" ? { threadRef: routeThreadRef } : {}), + ...(routeKind === "draft" && draftId ? { draftId } : {}), + model: selectedModel, + models: selectedProviderModels, + modelOptions: composerModelOptions?.[selectedProvider], + prompt, + onPromptChange: setPromptFromTraits, + }); + const pendingPrimaryAction = useMemo( + () => + activePendingProgress + ? { + questionIndex: activePendingProgress.questionIndex, + isLastQuestion: activePendingProgress.isLastQuestion, + canAdvance: activePendingProgress.canAdvance, + isResponding: activePendingIsResponding, + isComplete: Boolean(activePendingResolvedAnswers), + } + : null, + [activePendingIsResponding, activePendingProgress, activePendingResolvedAnswers], + ); + + // ------------------------------------------------------------------ + // Prompt helpers + // ------------------------------------------------------------------ + const setPrompt = useCallback( + (nextPrompt: string) => { + setComposerDraftPrompt(composerDraftTarget, nextPrompt); + }, + [composerDraftTarget, setComposerDraftPrompt], + ); + + const addComposerImage = useCallback( + (image: ComposerImageAttachment) => { + addComposerDraftImage(composerDraftTarget, image); + }, + [composerDraftTarget, addComposerDraftImage], + ); + + const addComposerImagesToDraft = useCallback( + (images: ComposerImageAttachment[]) => { + addComposerDraftImages(composerDraftTarget, images); + }, + [composerDraftTarget, addComposerDraftImages], + ); + + const removeComposerImageFromDraft = useCallback( + (imageId: string) => { + removeComposerDraftImage(composerDraftTarget, imageId); + }, + [composerDraftTarget, removeComposerDraftImage], + ); + + const removeComposerTerminalContextFromDraft = useCallback( + (contextId: string) => { + const contextIndex = composerTerminalContexts.findIndex( + (context) => context.id === contextId, + ); + if (contextIndex < 0) return; + const removal = removeInlineTerminalContextPlaceholder(promptRef.current, contextIndex); + promptRef.current = removal.prompt; + setPrompt(removal.prompt); + removeComposerDraftTerminalContext(composerDraftTarget, contextId); + const nextCursor = collapseExpandedComposerCursor(removal.prompt, removal.cursor); + setComposerCursor(nextCursor); + setComposerTrigger(detectComposerTrigger(removal.prompt, removal.cursor)); + }, + [ + composerDraftTarget, + composerTerminalContexts, + promptRef, + removeComposerDraftTerminalContext, + setPrompt, + ], + ); + + // ------------------------------------------------------------------ + // Sync refs back to parent + // ------------------------------------------------------------------ + useEffect(() => { + promptRef.current = prompt; + setComposerCursor((existing) => clampCollapsedComposerCursor(prompt, existing)); + }, [prompt, promptRef]); + + useEffect(() => { + composerImagesRef.current = composerImages; + }, [composerImages, composerImagesRef]); + + useEffect(() => { + composerTerminalContextsRef.current = composerTerminalContexts; + }, [composerTerminalContexts, composerTerminalContextsRef]); + + // ------------------------------------------------------------------ + // Composer menu highlight sync + // ------------------------------------------------------------------ + useEffect(() => { + if (!composerMenuOpen) { + setComposerHighlightedItemId(null); + setComposerHighlightedSearchKey(null); + return; + } + const nextActiveItemId = resolveComposerMenuActiveItemId({ + items: composerMenuItems, + highlightedItemId: composerHighlightedItemId, + currentSearchKey: composerMenuSearchKey, + highlightedSearchKey: composerHighlightedSearchKey, + }); + setComposerHighlightedItemId((existing) => + existing === nextActiveItemId ? existing : nextActiveItemId, + ); + setComposerHighlightedSearchKey((existing) => + existing === composerMenuSearchKey ? existing : composerMenuSearchKey, + ); + }, [ + composerHighlightedItemId, + composerHighlightedSearchKey, + composerMenuItems, + composerMenuOpen, + composerMenuSearchKey, + ]); + + const lastSyncedPendingInputRef = useRef<{ + requestId: string | null; + questionId: string | null; + } | null>(null); + + useEffect(() => { + const nextCustomAnswer = activePendingProgress?.customAnswer; + if (typeof nextCustomAnswer !== "string") { + lastSyncedPendingInputRef.current = null; + return; + } + + const nextRequestId = activePendingUserInput?.requestId ?? null; + const nextQuestionId = activePendingProgress?.activeQuestion?.id ?? null; + const questionChanged = + lastSyncedPendingInputRef.current?.requestId !== nextRequestId || + lastSyncedPendingInputRef.current?.questionId !== nextQuestionId; + const textChangedExternally = promptRef.current !== nextCustomAnswer; + + lastSyncedPendingInputRef.current = { + requestId: nextRequestId, + questionId: nextQuestionId, + }; + + if (!questionChanged && !textChangedExternally) { + return; + } + + promptRef.current = nextCustomAnswer; + const nextCursor = collapseExpandedComposerCursor(nextCustomAnswer, nextCustomAnswer.length); + setComposerCursor(nextCursor); + setComposerTrigger( + detectComposerTrigger( + nextCustomAnswer, + expandCollapsedComposerCursor(nextCustomAnswer, nextCursor), + ), + ); + setComposerHighlightedItemId(null); + }, [ + activePendingProgress?.customAnswer, + activePendingProgress?.activeQuestion?.id, + activePendingUserInput?.requestId, + promptRef, + ]); + + // ------------------------------------------------------------------ + // Reset compositor state on thread/draft change + // ------------------------------------------------------------------ + useEffect(() => { + setComposerHighlightedItemId(null); + setComposerCursor( + collapseExpandedComposerCursor(promptRef.current, promptRef.current.length), + ); + setComposerTrigger(detectComposerTrigger(promptRef.current, promptRef.current.length)); + dragDepthRef.current = 0; + setIsDragOverComposer(false); + }, [draftId, activeThreadId, promptRef]); + + // ------------------------------------------------------------------ + // Footer compact layout observation + // ------------------------------------------------------------------ + useLayoutEffect(() => { + const composerForm = composerFormRef.current; + if (!composerForm) return; + const measureComposerFormWidth = () => composerForm.clientWidth; + const measureFooterCompactness = () => { + const composerFormWidth = measureComposerFormWidth(); + const footerCompact = shouldUseCompactComposerFooter(composerFormWidth, { + hasWideActions: composerFooterHasWideActions, + }); + const primaryActionsCompact = + footerCompact && + shouldUseCompactComposerPrimaryActions(composerFormWidth, { + hasWideActions: composerFooterHasWideActions, + }); + return { + primaryActionsCompact, + footerCompact, + }; + }; + + composerFormHeightRef.current = composerForm.getBoundingClientRect().height; + 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 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; + composerFormHeightRef.current = nextHeight; + if (previousHeight > 0 && Math.abs(nextHeight - previousHeight) < 0.5) return; + if (!shouldAutoScrollRef.current) return; + scheduleStickToBottom(); + }); + + observer.observe(composerForm); + return () => { + observer.disconnect(); + }; + }, [ + activeThreadId, + composerFooterActionLayoutKey, + composerFooterHasWideActions, + scheduleStickToBottom, + shouldAutoScrollRef, + ]); + + // ------------------------------------------------------------------ + // Image persist effect + // ------------------------------------------------------------------ + useEffect(() => { + let cancelled = false; + void (async () => { + if (composerImages.length === 0) { + clearComposerDraftPersistedAttachments(composerDraftTarget); + return; + } + const getPersistedAttachmentsForThread = () => + getComposerDraft(composerDraftTarget)?.persistedAttachments ?? []; + try { + const currentPersistedAttachments = getPersistedAttachmentsForThread(); + const existingPersistedById = new Map( + currentPersistedAttachments.map((attachment) => [attachment.id, attachment]), + ); + const stagedAttachmentById = new Map(); + await Promise.all( + composerImages.map(async (image) => { + try { + const dataUrl = await readFileAsDataUrl(image.file); + stagedAttachmentById.set(image.id, { + id: image.id, + name: image.name, + mimeType: image.mimeType, + sizeBytes: image.sizeBytes, + dataUrl, + }); + } catch { + const existingPersisted = existingPersistedById.get(image.id); + if (existingPersisted) { + stagedAttachmentById.set(image.id, existingPersisted); + } + } + }), + ); + const serialized = Array.from(stagedAttachmentById.values()); + if (cancelled) return; + syncComposerDraftPersistedAttachments(composerDraftTarget, serialized); + } catch { + const currentImageIds = new Set(composerImages.map((image) => image.id)); + const fallbackPersistedAttachments = getPersistedAttachmentsForThread(); + const fallbackPersistedIds = fallbackPersistedAttachments + .map((attachment) => attachment.id) + .filter((id) => currentImageIds.has(id)); + const fallbackPersistedIdSet = new Set(fallbackPersistedIds); + const fallbackAttachments = fallbackPersistedAttachments.filter((attachment) => + fallbackPersistedIdSet.has(attachment.id), + ); + if (cancelled) return; + syncComposerDraftPersistedAttachments(composerDraftTarget, fallbackAttachments); + } + })(); + return () => { + cancelled = true; + }; + }, [ + composerDraftTarget, + clearComposerDraftPersistedAttachments, + composerImages, + getComposerDraft, + syncComposerDraftPersistedAttachments, + ]); + + // ------------------------------------------------------------------ + // Callbacks: prompt change + // ------------------------------------------------------------------ + const onPromptChange = useCallback( + ( + nextPrompt: string, + nextCursor: number, + expandedCursor: number, + cursorAdjacentToMention: boolean, + terminalContextIds: string[], + ) => { + if (activePendingProgress?.activeQuestion && pendingUserInputs.length > 0) { + setComposerCursor(nextCursor); + setComposerTrigger( + cursorAdjacentToMention ? null : detectComposerTrigger(nextPrompt, expandedCursor), + ); + onChangeActivePendingUserInputCustomAnswer( + activePendingProgress.activeQuestion.id, + nextPrompt, + nextCursor, + expandedCursor, + cursorAdjacentToMention, + ); + return; + } + promptRef.current = nextPrompt; + setPrompt(nextPrompt); + if (!terminalContextIdListsEqual(composerTerminalContexts, terminalContextIds)) { + setComposerDraftTerminalContexts( + composerDraftTarget, + syncTerminalContextsByIds(composerTerminalContexts, terminalContextIds), + ); + } + setComposerCursor(nextCursor); + setComposerTrigger( + cursorAdjacentToMention ? null : detectComposerTrigger(nextPrompt, expandedCursor), + ); + }, + [ + activePendingProgress?.activeQuestion, + pendingUserInputs.length, + onChangeActivePendingUserInputCustomAnswer, + promptRef, + setPrompt, + composerDraftTarget, + composerTerminalContexts, + setComposerDraftTerminalContexts, + ], + ); + + // ------------------------------------------------------------------ + // Callbacks: prompt replacement / menu + // ------------------------------------------------------------------ + const applyPromptReplacement = useCallback( + ( + rangeStart: number, + rangeEnd: number, + replacement: string, + options?: { expectedText?: string }, + ): boolean => { + const currentText = promptRef.current; + const safeStart = Math.max(0, Math.min(currentText.length, rangeStart)); + const safeEnd = Math.max(safeStart, Math.min(currentText.length, rangeEnd)); + if ( + options?.expectedText !== undefined && + currentText.slice(safeStart, safeEnd) !== options.expectedText + ) { + return false; + } + const next = replaceTextRange(promptRef.current, rangeStart, rangeEnd, replacement); + const nextCursor = collapseExpandedComposerCursor(next.text, next.cursor); + const nextExpandedCursor = expandCollapsedComposerCursor(next.text, nextCursor); + promptRef.current = next.text; + const activePendingQuestion = activePendingProgress?.activeQuestion; + if (activePendingQuestion && activePendingUserInput) { + onChangeActivePendingUserInputCustomAnswer( + activePendingQuestion.id, + next.text, + nextCursor, + nextExpandedCursor, + false, + ); + } else { + setPrompt(next.text); + } + setComposerCursor(nextCursor); + setComposerTrigger(detectComposerTrigger(next.text, nextExpandedCursor)); + window.requestAnimationFrame(() => { + composerEditorRef.current?.focusAt(nextCursor); + }); + return true; + }, + [ + activePendingProgress?.activeQuestion, + activePendingUserInput, + onChangeActivePendingUserInputCustomAnswer, + promptRef, + setPrompt, + ], + ); + + const readComposerSnapshot = useCallback((): { + value: string; + cursor: number; + expandedCursor: number; + terminalContextIds: string[]; + } => { + const editorSnapshot = composerEditorRef.current?.readSnapshot(); + if (editorSnapshot) { + return editorSnapshot; + } + return { + value: promptRef.current, + cursor: composerCursor, + expandedCursor: expandCollapsedComposerCursor(promptRef.current, composerCursor), + terminalContextIds: composerTerminalContexts.map((context) => context.id), + }; + }, [composerCursor, composerTerminalContexts, promptRef]); + + const resolveActiveComposerTrigger = useCallback((): { + snapshot: { value: string; cursor: number; expandedCursor: number }; + trigger: ComposerTrigger | null; + } => { + const snapshot = readComposerSnapshot(); + return { + snapshot, + trigger: detectComposerTrigger(snapshot.value, snapshot.expandedCursor), + }; + }, [readComposerSnapshot]); + + const onSelectComposerItem = useCallback( + (item: ComposerCommandItem) => { + if (composerSelectLockRef.current) return; + composerSelectLockRef.current = true; + window.requestAnimationFrame(() => { + composerSelectLockRef.current = false; + }); + const { snapshot, trigger } = resolveActiveComposerTrigger(); + if (!trigger) return; + if (item.type === "path") { + const replacement = `@${item.path} `; + const replacementRangeEnd = extendReplacementRangeForTrailingSpace( + snapshot.value, + trigger.rangeEnd, + replacement, + ); + const applied = applyPromptReplacement( + trigger.rangeStart, + replacementRangeEnd, + replacement, + { expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) }, + ); + if (applied) { + setComposerHighlightedItemId(null); + } + return; + } + if (item.type === "slash-command") { + if (item.command === "model") { + const replacement = "/model "; + const replacementRangeEnd = extendReplacementRangeForTrailingSpace( + snapshot.value, + trigger.rangeEnd, + replacement, + ); + const applied = applyPromptReplacement( + trigger.rangeStart, + replacementRangeEnd, + replacement, + { expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) }, + ); + if (applied) { + setComposerHighlightedItemId(null); + } + return; + } + void handleInteractionModeChange(item.command === "plan" ? "plan" : "default"); + const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", { + expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd), + }); + if (applied) { + setComposerHighlightedItemId(null); + } + return; + } + if (item.type === "provider-slash-command") { + const replacement = `/${item.command.name} `; + const replacementRangeEnd = extendReplacementRangeForTrailingSpace( + snapshot.value, + trigger.rangeEnd, + replacement, + ); + const applied = applyPromptReplacement( + trigger.rangeStart, + replacementRangeEnd, + replacement, + { expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) }, + ); + if (applied) { + setComposerHighlightedItemId(null); + } + return; + } + if (item.type === "skill") { + const replacement = `$${item.skill.name} `; + const replacementRangeEnd = extendReplacementRangeForTrailingSpace( + snapshot.value, + trigger.rangeEnd, + replacement, + ); + const applied = applyPromptReplacement( + trigger.rangeStart, + replacementRangeEnd, + replacement, + { expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) }, + ); + if (applied) { + setComposerHighlightedItemId(null); + } + return; + } + onProviderModelSelect(item.provider, item.model); + const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", { + expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd), + }); + if (applied) { + setComposerHighlightedItemId(null); + } + }, + [ + applyPromptReplacement, + handleInteractionModeChange, + onProviderModelSelect, + resolveActiveComposerTrigger, + ], + ); + + const onComposerMenuItemHighlighted = useCallback( + (itemId: string | null) => { + setComposerHighlightedItemId(itemId); + setComposerHighlightedSearchKey(composerMenuSearchKey); + }, + [composerMenuSearchKey], + ); + + const nudgeComposerMenuHighlight = useCallback( + (key: "ArrowDown" | "ArrowUp") => { + if (composerMenuItems.length === 0) return; + const highlightedIndex = composerMenuItems.findIndex( + (item) => item.id === composerHighlightedItemId, + ); + const normalizedIndex = + highlightedIndex >= 0 ? highlightedIndex : key === "ArrowDown" ? -1 : 0; + const offset = key === "ArrowDown" ? 1 : -1; + const nextIndex = + (normalizedIndex + offset + composerMenuItems.length) % composerMenuItems.length; + const nextItem = composerMenuItems[nextIndex]; + setComposerHighlightedItemId(nextItem?.id ?? null); + }, + [composerHighlightedItemId, composerMenuItems], + ); + + // ------------------------------------------------------------------ + // Callbacks: command key + // ------------------------------------------------------------------ + const onComposerCommandKey = ( + key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab", + event: KeyboardEvent, + ) => { + if (key === "Tab" && event.shiftKey) { + toggleInteractionMode(); + return true; + } + const { trigger } = resolveActiveComposerTrigger(); + const menuIsActive = composerMenuOpenRef.current || trigger !== null; + if (menuIsActive) { + const currentItems = composerMenuItemsRef.current; + const selectedItem = activeComposerMenuItemRef.current ?? currentItems[0]; + if (key === "ArrowDown" && currentItems.length > 0) { + nudgeComposerMenuHighlight("ArrowDown"); + return true; + } + if (key === "ArrowUp" && currentItems.length > 0) { + nudgeComposerMenuHighlight("ArrowUp"); + return true; + } + if ((key === "Enter" || key === "Tab") && selectedItem) { + onSelectComposerItem(selectedItem); + return true; + } + } + if (key === "Enter" && !event.shiftKey) { + void onSend(); + return true; + } + return false; + }; + + // ------------------------------------------------------------------ + // Callbacks: images + // ------------------------------------------------------------------ + const addComposerImages = (files: File[]) => { + if (!activeThreadId || files.length === 0) return; + if (pendingUserInputs.length > 0) { + toastManager.add({ + type: "error", + title: "Attach images after answering plan questions.", + }); + return; + } + const nextImages: ComposerImageAttachment[] = []; + let nextImageCount = composerImagesRef.current.length; + let error: string | null = null; + for (const file of files) { + if (!file.type.startsWith("image/")) { + error = `Unsupported file type for '${file.name}'. Please attach image files only.`; + continue; + } + if (file.size > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { + error = `'${file.name}' exceeds the ${IMAGE_SIZE_LIMIT_LABEL} attachment limit.`; + continue; + } + if (nextImageCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) { + error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`; + break; + } + const previewUrl = URL.createObjectURL(file); + nextImages.push({ + type: "image", + id: randomUUID(), + name: file.name || "image", + mimeType: file.type, + sizeBytes: file.size, + previewUrl, + file, + }); + nextImageCount += 1; + } + if (nextImages.length === 1 && nextImages[0]) { + addComposerImage(nextImages[0]); + } else if (nextImages.length > 1) { + addComposerImagesToDraft(nextImages); + } + setThreadError(activeThreadId, error); + }; + + const removeComposerImage = (imageId: string) => { + removeComposerImageFromDraft(imageId); + }; + + // ------------------------------------------------------------------ + // Callbacks: paste / drag + // ------------------------------------------------------------------ + const onComposerPaste = (event: React.ClipboardEvent) => { + const files = Array.from(event.clipboardData.files); + if (files.length === 0) return; + const imageFiles = files.filter((file) => file.type.startsWith("image/")); + if (imageFiles.length === 0) return; + event.preventDefault(); + addComposerImages(imageFiles); + }; + + const onComposerDragEnter = (event: React.DragEvent) => { + if (!event.dataTransfer.types.includes("Files")) return; + event.preventDefault(); + dragDepthRef.current += 1; + setIsDragOverComposer(true); + }; + + const onComposerDragOver = (event: React.DragEvent) => { + if (!event.dataTransfer.types.includes("Files")) return; + event.preventDefault(); + event.dataTransfer.dropEffect = "copy"; + setIsDragOverComposer(true); + }; + + const onComposerDragLeave = (event: React.DragEvent) => { + if (!event.dataTransfer.types.includes("Files")) return; + event.preventDefault(); + const nextTarget = event.relatedTarget; + if (nextTarget instanceof Node && event.currentTarget.contains(nextTarget)) return; + dragDepthRef.current = Math.max(0, dragDepthRef.current - 1); + if (dragDepthRef.current === 0) { + setIsDragOverComposer(false); + } + }; + + const onComposerDrop = (event: React.DragEvent) => { + if (!event.dataTransfer.types.includes("Files")) return; + event.preventDefault(); + dragDepthRef.current = 0; + setIsDragOverComposer(false); + const files = Array.from(event.dataTransfer.files); + addComposerImages(files); + focusComposer(); + }; + const handleInterruptPrimaryAction = useCallback(() => { + void onInterrupt(); + }, [onInterrupt]); + const handleImplementPlanInNewThreadPrimaryAction = useCallback(() => { + void onImplementPlanInNewThread(); + }, [onImplementPlanInNewThread]); + + // ------------------------------------------------------------------ + // Imperative handle + // ------------------------------------------------------------------ + useImperativeHandle( + ref, + () => ({ + focusAtEnd: () => { + composerEditorRef.current?.focusAtEnd(); + }, + focusAt: (cursor: number) => { + composerEditorRef.current?.focusAt(cursor); + }, + readSnapshot: () => { + return readComposerSnapshot(); + }, + resetCursorState: (options?: { + cursor?: number; + prompt?: string; + detectTrigger?: boolean; + }) => { + const promptForState = options?.prompt ?? promptRef.current; + const cursor = clampCollapsedComposerCursor(promptForState, options?.cursor ?? 0); + setComposerHighlightedItemId(null); + setComposerCursor(cursor); + setComposerTrigger( + options?.detectTrigger + ? detectComposerTrigger( + promptForState, + expandCollapsedComposerCursor(promptForState, cursor), + ) + : null, + ); + }, + addTerminalContext: (selection: TerminalContextSelection) => { + if (!activeThread) return; + const snapshot = composerEditorRef.current?.readSnapshot() ?? { + value: promptRef.current, + cursor: composerCursor, + expandedCursor: expandCollapsedComposerCursor(promptRef.current, composerCursor), + terminalContextIds: composerTerminalContexts.map((context) => context.id), + }; + const insertion = insertInlineTerminalContextPlaceholder( + snapshot.value, + snapshot.expandedCursor, + ); + const nextCollapsedCursor = collapseExpandedComposerCursor( + insertion.prompt, + insertion.cursor, + ); + const inserted = insertComposerDraftTerminalContext( + composerDraftTarget, + insertion.prompt, + { + id: randomUUID(), + threadId: activeThread.id, + createdAt: new Date().toISOString(), + ...selection, + }, + insertion.contextIndex, + ); + if (!inserted) return; + promptRef.current = insertion.prompt; + setComposerCursor(nextCollapsedCursor); + setComposerTrigger(detectComposerTrigger(insertion.prompt, insertion.cursor)); + window.requestAnimationFrame(() => { + composerEditorRef.current?.focusAt(nextCollapsedCursor); + }); + }, + getSendContext: () => ({ + prompt: promptRef.current, + images: composerImagesRef.current, + terminalContexts: composerTerminalContextsRef.current, + selectedPromptEffort, + selectedModelOptionsForDispatch, + selectedModelSelection, + selectedProvider, + selectedModel, + selectedProviderModels, + }), + }), + [ + activeThread, + composerDraftTarget, + composerCursor, + composerTerminalContexts, + insertComposerDraftTerminalContext, + promptRef, + composerImagesRef, + composerTerminalContextsRef, + readComposerSnapshot, + selectedModel, + selectedModelOptionsForDispatch, + selectedModelSelection, + selectedPromptEffort, + selectedProvider, + selectedProviderModels, + ], + ); + + // Render + // ------------------------------------------------------------------ + return ( +
+
+
+ {activePendingApproval ? ( +
+ +
+ ) : pendingUserInputs.length > 0 ? ( +
+ +
+ ) : showPlanFollowUpPrompt && activeProposedPlan ? ( +
+ +
+ ) : null} + +
+ {composerMenuOpen && !isComposerApprovalState && ( +
+ +
+ )} + + {!isComposerApprovalState && + pendingUserInputs.length === 0 && + composerImages.length > 0 && ( +
+ {composerImages.map((image) => ( +
+ {image.previewUrl ? ( + + ) : ( +
+ {image.name} +
+ )} + {nonPersistedComposerImageIdSet.has(image.id) && ( + + + + + } + /> + + Draft attachment could not be saved locally and may be lost on + navigation. + + + )} + +
+ ))} +
+ )} + + +
+ + {/* Bottom toolbar */} + {activePendingApproval ? ( +
+ +
+ ) : ( +
+
+ + + {isComposerFooterCompact ? ( + + ) : ( + <> + {providerTraitsPicker ? ( + <> + + {providerTraitsPicker} + + ) : null} + + + )} +
+ + {/* Right side: send / stop button */} +
+ 0} + isSendBusy={isSendBusy} + isConnecting={isConnecting} + isPreparingWorktree={isPreparingWorktree} + hasSendableContent={composerSendState.hasSendableContent} + onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion} + onInterrupt={handleInterruptPrimaryAction} + onImplementPlanInNewThread={handleImplementPlanInNewThreadPrimaryAction} + /> +
+
+ )} +
+
+
+ ); + }), +); diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index f04c9879fa..cda0bb1367 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -1,11 +1,14 @@ import { + type EnvironmentId, type EditorId, type ProjectScript, type ResolvedKeybindingsConfig, type ThreadId, } from "@t3tools/contracts"; +import { scopeThreadRef } from "@t3tools/client-runtime"; import { memo } from "react"; import GitActionsControl from "../GitActionsControl"; +import { type DraftId } from "~/composerDraftStore"; import { DiffIcon, TerminalSquareIcon } from "lucide-react"; import { Badge } from "../ui/badge"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -15,7 +18,9 @@ import { SidebarTrigger } from "../ui/sidebar"; import { OpenInPicker } from "./OpenInPicker"; interface ChatHeaderProps { + activeThreadEnvironmentId: EnvironmentId; activeThreadId: ThreadId; + draftId?: DraftId; activeThreadTitle: string; activeProjectName: string | undefined; isGitRepo: boolean; @@ -39,7 +44,9 @@ interface ChatHeaderProps { } export const ChatHeader = memo(function ChatHeader({ + activeThreadEnvironmentId, activeThreadId, + draftId, activeThreadTitle, activeProjectName, isGitRepo, @@ -101,7 +108,13 @@ export const ChatHeader = memo(function ChatHeader({ openInCwd={openInCwd} /> )} - {activeProjectName && } + {activeProjectName && ( + + )} ["draftsByThreadId"]; const model = props?.modelSelection?.model ?? DEFAULT_MODEL_BY_PROVIDER[provider]; - draftsByThreadId[threadId] = { - prompt: props?.prompt ?? "", - images: [], - nonPersistedImageIds: [], - persistedAttachments: [], - terminalContexts: [], - modelSelectionByProvider: { - [provider]: { - provider, - model, - ...(props?.modelSelection?.options ? { options: props.modelSelection.options } : {}), + useComposerDraftStore.setState({ + draftsByThreadKey: { + [threadKey]: { + prompt: props?.prompt ?? "", + images: [], + nonPersistedImageIds: [], + persistedAttachments: [], + terminalContexts: [], + modelSelectionByProvider: { + [provider]: { + provider, + model, + ...(props?.modelSelection?.options ? { options: props.modelSelection.options } : {}), + }, + }, + activeProvider: provider, + runtimeMode: null, + interactionMode: null, }, }, - activeProvider: provider, - runtimeMode: null, - interactionMode: null, - }; - useComposerDraftStore.setState({ - draftsByThreadId, - draftThreadsByThreadId: {}, - projectDraftThreadIdByProjectId: {}, + draftThreadsByThreadKey: {}, + logicalProjectDraftThreadKeyByLogicalProjectKey: {}, }); const host = document.createElement("div"); document.body.append(host); @@ -121,7 +129,7 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str , { container: host }, ); @@ -150,9 +158,9 @@ describe("CompactComposerControlsMenu", () => { afterEach(() => { document.body.innerHTML = ""; useComposerDraftStore.setState({ - draftsByThreadId: {}, - draftThreadsByThreadId: {}, - projectDraftThreadIdByProjectId: {}, + draftsByThreadKey: {}, + draftThreadsByThreadKey: {}, + logicalProjectDraftThreadKeyByLogicalProjectKey: {}, stickyModelSelectionByProvider: {}, }); }); diff --git a/apps/web/src/components/chat/CompactComposerControlsMenu.tsx b/apps/web/src/components/chat/CompactComposerControlsMenu.tsx index db38ed8c1e..84e0953440 100644 --- a/apps/web/src/components/chat/CompactComposerControlsMenu.tsx +++ b/apps/web/src/components/chat/CompactComposerControlsMenu.tsx @@ -20,7 +20,7 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls traitsMenuContent?: ReactNode; onToggleInteractionMode: () => void; onTogglePlanSidebar: () => void; - onToggleRuntimeMode: () => void; + onRuntimeModeChange: (mode: RuntimeMode) => void; }) { return ( @@ -60,10 +60,11 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls value={props.runtimeMode} onValueChange={(value) => { if (!value || value === props.runtimeMode) return; - props.onToggleRuntimeMode(); + props.onRuntimeModeChange(value as RuntimeMode); }} > Supervised + Auto-accept edits Full access {props.activePlan ? ( diff --git a/apps/web/src/components/chat/ComposerCommandMenu.tsx b/apps/web/src/components/chat/ComposerCommandMenu.tsx index fc7ea27c29..de7cf2b2b8 100644 --- a/apps/web/src/components/chat/ComposerCommandMenu.tsx +++ b/apps/web/src/components/chat/ComposerCommandMenu.tsx @@ -1,10 +1,24 @@ -import { type ProjectEntry, type ProviderKind } from "@t3tools/contracts"; -import { memo, useLayoutEffect, useRef } from "react"; -import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic"; +import { + type ProjectEntry, + type ProviderKind, + type ServerProviderSkill, + type ServerProviderSlashCommand, +} from "@t3tools/contracts"; import { BotIcon } from "lucide-react"; +import { memo, useLayoutEffect, useMemo, useRef } from "react"; + +import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic"; +import { formatProviderSkillInstallSource } from "~/providerSkillPresentation"; import { cn } from "~/lib/utils"; import { Badge } from "../ui/badge"; -import { Command, CommandItem, CommandList } from "../ui/command"; +import { + Command, + CommandGroup, + CommandGroupLabel, + CommandItem, + CommandList, + CommandSeparator, +} from "../ui/command"; import { VscodeEntryIcon } from "./VscodeEntryIcon"; export type ComposerCommandItem = @@ -23,6 +37,14 @@ export type ComposerCommandItem = label: string; description: string; } + | { + id: string; + type: "provider-slash-command"; + provider: ProviderKind; + command: ServerProviderSlashCommand; + label: string; + description: string; + } | { id: string; type: "model"; @@ -30,18 +52,83 @@ export type ComposerCommandItem = model: string; label: string; description: string; + } + | { + id: string; + type: "skill"; + provider: ProviderKind; + skill: ServerProviderSkill; + label: string; + description: string; }; +type ComposerCommandGroup = { + id: string; + label: string | null; + items: ComposerCommandItem[]; +}; + +function SkillGlyph(props: { className?: string }) { + return ( + + ); +} + +function groupCommandItems( + items: ComposerCommandItem[], + triggerKind: ComposerTriggerKind | null, + groupSlashCommandSections: boolean, +): ComposerCommandGroup[] { + if (triggerKind === "skill") { + return items.length > 0 ? [{ id: "skills", label: "Skills", items }] : []; + } + if (triggerKind !== "slash-command" || !groupSlashCommandSections) { + return [{ id: "default", label: null, items }]; + } + + const builtInItems = items.filter((item) => item.type === "slash-command"); + const providerItems = items.filter((item) => item.type === "provider-slash-command"); + + const groups: ComposerCommandGroup[] = []; + if (builtInItems.length > 0) { + groups.push({ id: "built-in", label: "Built-in", items: builtInItems }); + } + if (providerItems.length > 0) { + groups.push({ id: "provider", label: "Provider", items: providerItems }); + } + return groups; +} + export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: { items: ComposerCommandItem[]; resolvedTheme: "light" | "dark"; isLoading: boolean; triggerKind: ComposerTriggerKind | null; + groupSlashCommandSections?: boolean; + emptyStateText?: string; activeItemId: string | null; onHighlightedItemChange: (itemId: string | null) => void; onSelect: (item: ComposerCommandItem) => void; }) { const listRef = useRef(null); + const groups = useMemo( + () => + groupCommandItems(props.items, props.triggerKind, props.groupSlashCommandSections ?? true), + [props.groupSlashCommandSections, props.items, props.triggerKind], + ); useLayoutEffect(() => { if (!props.activeItemId || !listRef.current) return; @@ -65,27 +152,56 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: { ref={listRef} className="relative overflow-hidden rounded-xl border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs" > - - {props.items.map((item) => ( - + + {groups.map((group, groupIndex) => ( +
+ {groupIndex > 0 ? : null} + + {group.label ? ( + + {group.label} + + ) : null} + {group.items.map((item) => ( + + ))} + +
))}
- {props.items.length === 0 && ( -

- {props.isLoading - ? "Searching workspace files..." - : props.triggerKind === "path" - ? "No matching files or folders." - : "No matching command."} -

- )} + {props.items.length === 0 ? ( +
+ {props.triggerKind === "skill" ? ( + + + Skills + +

+ {props.isLoading + ? "Searching workspace skills..." + : (props.emptyStateText ?? + "No skills found. Try / to browse provider commands.")} +

+
+ ) : ( +

+ {props.isLoading + ? "Searching workspace files..." + : (props.emptyStateText ?? + (props.triggerKind === "path" + ? "No matching files or folders." + : "No matching command."))} +

+ )} +
+ ) : null}
); @@ -98,6 +214,9 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: { onHighlight: (itemId: string | null) => void; onSelect: (item: ComposerCommandItem) => void; }) { + const skillSourceLabel = + props.item.type === "skill" ? formatProviderSkillInstallSource(props.item.skill) : null; + return ( ) : null} {props.item.type === "slash-command" ? ( - + + ) : null} + {props.item.type === "provider-slash-command" ? ( + + + + ) : null} + {props.item.type === "skill" ? ( + + + ) : null} {props.item.type === "model" ? ( model ) : null} - - {props.item.label} + + {props.item.label} + + {props.item.description} + - {props.item.description} + {skillSourceLabel ? ( + {skillSourceLabel} + ) : null} ); }); diff --git a/apps/web/src/components/chat/ComposerPendingTerminalContexts.test.tsx b/apps/web/src/components/chat/ComposerPendingTerminalContexts.test.tsx index 060f197e97..1807fb4265 100644 --- a/apps/web/src/components/chat/ComposerPendingTerminalContexts.test.tsx +++ b/apps/web/src/components/chat/ComposerPendingTerminalContexts.test.tsx @@ -10,7 +10,7 @@ describe("ComposerPendingTerminalContextChip", () => { ; questionIndex: number; - onSelectOption: (questionId: string, optionLabel: string) => void; + onToggleOption: (questionId: string, optionLabel: string) => void; onAdvance: () => void; } @@ -22,7 +22,7 @@ export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserIn respondingRequestIds, answers, questionIndex, - onSelectOption, + onToggleOption, onAdvance, }: PendingUserInputPanelProps) { if (pendingUserInputs.length === 0) return null; @@ -36,7 +36,7 @@ export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserIn isResponding={respondingRequestIds.includes(activePrompt.requestId)} answers={answers} questionIndex={questionIndex} - onSelectOption={onSelectOption} + onToggleOption={onToggleOption} onAdvance={onAdvance} /> ); @@ -47,19 +47,24 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( isResponding, answers, questionIndex, - onSelectOption, + onToggleOption, onAdvance, }: { prompt: PendingUserInput; isResponding: boolean; answers: Record; questionIndex: number; - onSelectOption: (questionId: string, optionLabel: string) => void; + onToggleOption: (questionId: string, optionLabel: string) => void; onAdvance: () => void; }) { const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex); const activeQuestion = progress.activeQuestion; const autoAdvanceTimerRef = useRef(null); + const onAdvanceRef = useRef(onAdvance); + + useEffect(() => { + onAdvanceRef.current = onAdvance; + }, [onAdvance]); // Clear auto-advance timer on unmount useEffect(() => { @@ -70,24 +75,23 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( }; }, []); - const selectOptionAndAutoAdvance = useCallback( - (questionId: string, optionLabel: string) => { - onSelectOption(questionId, optionLabel); - if (autoAdvanceTimerRef.current !== null) { - window.clearTimeout(autoAdvanceTimerRef.current); - } - autoAdvanceTimerRef.current = window.setTimeout(() => { - autoAdvanceTimerRef.current = null; - onAdvance(); - }, 200); - }, - [onSelectOption, onAdvance], - ); + const handleOptionSelection = useEffectEvent((questionId: string, optionLabel: string) => { + onToggleOption(questionId, optionLabel); + if (activeQuestion?.multiSelect) { + return; + } + if (autoAdvanceTimerRef.current !== null) { + window.clearTimeout(autoAdvanceTimerRef.current); + } + autoAdvanceTimerRef.current = window.setTimeout(() => { + autoAdvanceTimerRef.current = null; + onAdvanceRef.current(); + }, 200); + }); - // Keyboard shortcut: number keys 1-9 select corresponding option and auto-advance. - // Works even when the Lexical composer (contenteditable) has focus — the composer - // doubles as a custom-answer field during user input, and when it's empty the digit - // keys should pick options instead of typing into the editor. + // Keyboard shortcut: number keys 1-9 select corresponding options when focus is + // outside editable fields. Multi-select prompts toggle options in place; single- + // select prompts keep the existing auto-advance behavior. useEffect(() => { if (!activeQuestion || isResponding) return; const handler = (event: globalThis.KeyboardEvent) => { @@ -96,11 +100,11 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) { return; } - // If the user has started typing a custom answer in the contenteditable - // composer, let digit keys pass through so they can type numbers. - if (target instanceof HTMLElement && target.isContentEditable) { - const hasCustomText = progress.customAnswer.length > 0; - if (hasCustomText) return; + if ( + target instanceof HTMLElement && + target.closest('[contenteditable]:not([contenteditable="false"])') + ) { + return; } const digit = Number.parseInt(event.key, 10); if (Number.isNaN(digit) || digit < 1 || digit > 9) return; @@ -109,11 +113,11 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( const option = activeQuestion.options[optionIndex]; if (!option) return; event.preventDefault(); - selectOptionAndAutoAdvance(activeQuestion.id, option.label); + handleOptionSelection(activeQuestion.id, option.label); }; document.addEventListener("keydown", handler); return () => document.removeEventListener("keydown", handler); - }, [activeQuestion, isResponding, selectOptionAndAutoAdvance, progress.customAnswer.length]); + }, [activeQuestion, isResponding]); if (!activeQuestion) { return null; @@ -134,16 +138,19 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(

{activeQuestion.question}

+ {activeQuestion.multiSelect ? ( +

Select one or more options.

+ ) : null}
{activeQuestion.options.map((option, index) => { - const isSelected = progress.selectedOptionLabel === option.label; + const isSelected = progress.selectedOptionLabels.includes(option.label); const shortcutKey = index < 9 ? index + 1 : null; return ( + ) : ( + + ) + ) : 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/ExpandedImageDialog.tsx b/apps/web/src/components/chat/ExpandedImageDialog.tsx new file mode 100644 index 0000000000..10031b48cd --- /dev/null +++ b/apps/web/src/components/chat/ExpandedImageDialog.tsx @@ -0,0 +1,120 @@ +import { memo, useCallback, useEffect, useState } from "react"; +import { ChevronLeftIcon, ChevronRightIcon, XIcon } from "lucide-react"; +import { Button } from "../ui/button"; +import type { ExpandedImagePreview } from "./ExpandedImagePreview"; + +interface ExpandedImageDialogProps { + preview: ExpandedImagePreview; + onClose: () => void; +} + +export const ExpandedImageDialog = memo(function ExpandedImageDialog({ + preview: initialPreview, + onClose, +}: ExpandedImageDialogProps) { + const [preview, setPreview] = useState(initialPreview); + + // Sync when the parent hands us a new preview reference. + useEffect(() => { + setPreview(initialPreview); + }, [initialPreview]); + + const navigateImage = useCallback((direction: -1 | 1) => { + setPreview((existing) => { + if (existing.images.length <= 1) return existing; + const nextIndex = + (existing.index + direction + existing.images.length) % existing.images.length; + if (nextIndex === existing.index) return existing; + return { ...existing, index: nextIndex }; + }); + }, []); + + useEffect(() => { + const onKeyDown = (event: globalThis.KeyboardEvent) => { + if (event.key === "Escape") { + event.preventDefault(); + event.stopPropagation(); + onClose(); + return; + } + if (preview.images.length <= 1) return; + if (event.key === "ArrowLeft") { + event.preventDefault(); + event.stopPropagation(); + navigateImage(-1); + return; + } + if (event.key !== "ArrowRight") return; + event.preventDefault(); + event.stopPropagation(); + navigateImage(1); + }; + window.addEventListener("keydown", onKeyDown); + return () => window.removeEventListener("keydown", onKeyDown); + }, [navigateImage, onClose, preview.images.length]); + + const item = preview.images[preview.index]; + if (!item) return null; + + return ( +
+ + )} +
+ + {item.name} +

+ {item.name} + {preview.images.length > 1 ? ` (${preview.index + 1}/${preview.images.length})` : ""} +

+
+ {preview.images.length > 1 && ( + + )} +
+ ); +}); diff --git a/apps/web/src/components/chat/MessageCopyButton.tsx b/apps/web/src/components/chat/MessageCopyButton.tsx index cf1e798912..ad5d56dd5a 100644 --- a/apps/web/src/components/chat/MessageCopyButton.tsx +++ b/apps/web/src/components/chat/MessageCopyButton.tsx @@ -1,20 +1,82 @@ -import { memo } from "react"; +import { memo, useRef } from "react"; import { CopyIcon, CheckIcon } from "lucide-react"; import { Button } from "../ui/button"; import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; +import { cn } from "~/lib/utils"; +import { anchoredToastManager } from "../ui/toast"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; -export const MessageCopyButton = memo(function MessageCopyButton({ text }: { text: string }) { - const { copyToClipboard, isCopied } = useCopyToClipboard(); +const ANCHORED_TOAST_TIMEOUT_MS = 1000; +const onCopy = (ref: React.RefObject) => { + if (ref.current) { + anchoredToastManager.add({ + data: { + tooltipStyle: true, + }, + positionerProps: { + anchor: ref.current, + }, + timeout: ANCHORED_TOAST_TIMEOUT_MS, + title: "Copied!", + }); + } +}; + +const onCopyError = (ref: React.RefObject, error: Error) => { + if (ref.current) { + anchoredToastManager.add({ + data: { + tooltipStyle: true, + }, + positionerProps: { + anchor: ref.current, + }, + timeout: ANCHORED_TOAST_TIMEOUT_MS, + title: "Failed to copy", + description: error.message, + }); + } +}; + +export const MessageCopyButton = memo(function MessageCopyButton({ + text, + size = "xs", + variant = "outline", + className, +}: { + text: string; + size?: "xs" | "icon-xs"; + variant?: "outline" | "ghost"; + className?: string; +}) { + const ref = useRef(null); + const { copyToClipboard, isCopied } = useCopyToClipboard({ + onCopy: () => onCopy(ref), + onError: (error: Error) => onCopyError(ref, error), + timeout: ANCHORED_TOAST_TIMEOUT_MS, + }); return ( - + + copyToClipboard(text)} + ref={ref} + type="button" + size={size} + variant={variant} + className={cn(className)} + /> + } + > + {isCopied ? : } + + +

Copy to clipboard

+
+
); }); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index dee42a8586..2910547122 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -1,5 +1,10 @@ import { describe, expect, it } from "vitest"; -import { computeMessageDurationStart, normalizeCompactToolLabel } from "./MessagesTimeline.logic"; +import { + computeMessageDurationStart, + deriveMessagesTimelineRows, + normalizeCompactToolLabel, + resolveAssistantMessageCopyState, +} from "./MessagesTimeline.logic"; describe("computeMessageDurationStart", () => { it("returns message createdAt when there is no preceding user message", () => { @@ -143,3 +148,120 @@ describe("normalizeCompactToolLabel", () => { expect(normalizeCompactToolLabel("Read file completed")).toBe("Read file"); }); }); + +describe("resolveAssistantMessageCopyState", () => { + it("returns enabled copy state for completed assistant messages", () => { + expect( + resolveAssistantMessageCopyState({ + showCopyButton: true, + text: "Ship it", + streaming: false, + }), + ).toEqual({ + text: "Ship it", + visible: true, + }); + }); + + it("hides copy while an assistant message is still streaming", () => { + expect( + resolveAssistantMessageCopyState({ + showCopyButton: true, + text: "Still streaming", + streaming: true, + }), + ).toEqual({ + text: "Still streaming", + visible: false, + }); + }); + + it("hides copy for empty completed assistant messages", () => { + expect( + resolveAssistantMessageCopyState({ + showCopyButton: true, + text: " ", + streaming: false, + }), + ).toEqual({ + text: null, + visible: false, + }); + }); + + it("hides copy for non-terminal assistant messages", () => { + expect( + resolveAssistantMessageCopyState({ + showCopyButton: false, + text: "Interim thought", + streaming: false, + }), + ).toEqual({ + text: "Interim thought", + visible: false, + }); + }); +}); + +describe("deriveMessagesTimelineRows", () => { + it("only enables assistant copy for the terminal assistant message in a turn", () => { + const rows = deriveMessagesTimelineRows({ + timelineEntries: [ + { + id: "user-1-entry", + kind: "message", + createdAt: "2026-01-01T00:00:00Z", + message: { + id: "user-1" as never, + role: "user", + text: "Write a poem", + turnId: null, + createdAt: "2026-01-01T00:00:00Z", + streaming: false, + }, + }, + { + id: "assistant-thought-entry", + kind: "message", + createdAt: "2026-01-01T00:00:10Z", + message: { + id: "assistant-thought" as never, + role: "assistant", + text: "I should ground this first.", + turnId: "turn-1" as never, + createdAt: "2026-01-01T00:00:10Z", + completedAt: "2026-01-01T00:00:11Z", + streaming: false, + }, + }, + { + id: "assistant-final-entry", + kind: "message", + createdAt: "2026-01-01T00:00:20Z", + message: { + id: "assistant-final" as never, + role: "assistant", + text: "Here is the poem.", + turnId: "turn-1" as never, + createdAt: "2026-01-01T00:00:20Z", + completedAt: "2026-01-01T00:00:30Z", + streaming: false, + }, + }, + ], + completionDividerBeforeEntryId: "assistant-final-entry", + isWorking: false, + activeTurnStartedAt: null, + }); + + const assistantRows = rows.filter( + (row): row is Extract<(typeof rows)[number], { kind: "message" }> => + row.kind === "message" && row.message.role === "assistant", + ); + + expect(assistantRows).toHaveLength(2); + expect(assistantRows[0]?.showAssistantCopyButton).toBe(false); + expect(assistantRows[1]?.showAssistantCopyButton).toBe(true); + expect(assistantRows[1]?.showCompletionDivider).toBe(true); + }); +}); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 726d61888e..25debf5066 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -1,3 +1,11 @@ +import { type MessageId } from "@t3tools/contracts"; +import { type TimelineEntry, type WorkLogEntry } from "../../session-logic"; +import { buildTurnDiffTree, type TurnDiffTreeNode } from "../../lib/turnDiffTree"; +import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types"; +import { estimateTimelineMessageHeight } from "../timelineHeight"; + +export const MAX_VISIBLE_WORK_LOG_ENTRIES = 6; + export interface TimelineDurationMessage { id: string; role: "user" | "assistant" | "system"; @@ -5,6 +13,30 @@ export interface TimelineDurationMessage { completedAt?: string | undefined; } +export type MessagesTimelineRow = + | { + kind: "work"; + id: string; + createdAt: string; + groupedEntries: WorkLogEntry[]; + } + | { + kind: "message"; + id: string; + createdAt: string; + message: ChatMessage; + durationStart: string; + showCompletionDivider: boolean; + showAssistantCopyButton: boolean; + } + | { + kind: "proposed-plan"; + id: string; + createdAt: string; + proposedPlan: ProposedPlan; + } + | { kind: "working"; id: string; createdAt: string | null }; + export function computeMessageDurationStart( messages: ReadonlyArray, ): Map { @@ -27,3 +59,188 @@ export function computeMessageDurationStart( export function normalizeCompactToolLabel(value: string): string { return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim(); } + +export function resolveAssistantMessageCopyState({ + text, + showCopyButton, + streaming, +}: { + text: string | null; + showCopyButton: boolean; + streaming: boolean; +}) { + const hasText = text !== null && text.trim().length > 0; + return { + text: hasText ? text : null, + visible: showCopyButton && hasText && !streaming, + }; +} + +function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray) { + const lastAssistantMessageIdByResponseKey = new Map(); + let nullTurnResponseIndex = 0; + + for (const timelineEntry of timelineEntries) { + if (timelineEntry.kind !== "message") { + continue; + } + const { message } = timelineEntry; + if (message.role === "user") { + nullTurnResponseIndex += 1; + continue; + } + if (message.role !== "assistant") { + continue; + } + + const responseKey = message.turnId + ? `turn:${message.turnId}` + : `unkeyed:${nullTurnResponseIndex}`; + lastAssistantMessageIdByResponseKey.set(responseKey, message.id); + } + + return new Set(lastAssistantMessageIdByResponseKey.values()); +} + +export function deriveMessagesTimelineRows(input: { + timelineEntries: ReadonlyArray; + completionDividerBeforeEntryId: string | null; + isWorking: boolean; + activeTurnStartedAt: string | null; +}): MessagesTimelineRow[] { + const nextRows: MessagesTimelineRow[] = []; + const durationStartByMessageId = computeMessageDurationStart( + input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])), + ); + const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries); + + for (let index = 0; index < input.timelineEntries.length; index += 1) { + const timelineEntry = input.timelineEntries[index]; + if (!timelineEntry) { + continue; + } + + if (timelineEntry.kind === "work") { + const groupedEntries = [timelineEntry.entry]; + let cursor = index + 1; + while (cursor < input.timelineEntries.length) { + const nextEntry = input.timelineEntries[cursor]; + if (!nextEntry || nextEntry.kind !== "work") break; + groupedEntries.push(nextEntry.entry); + cursor += 1; + } + nextRows.push({ + kind: "work", + id: timelineEntry.id, + createdAt: timelineEntry.createdAt, + groupedEntries, + }); + index = cursor - 1; + continue; + } + + if (timelineEntry.kind === "proposed-plan") { + nextRows.push({ + kind: "proposed-plan", + id: timelineEntry.id, + createdAt: timelineEntry.createdAt, + proposedPlan: timelineEntry.proposedPlan, + }); + continue; + } + + nextRows.push({ + kind: "message", + id: timelineEntry.id, + createdAt: timelineEntry.createdAt, + message: timelineEntry.message, + durationStart: + durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt, + showCompletionDivider: + timelineEntry.message.role === "assistant" && + input.completionDividerBeforeEntryId === timelineEntry.id, + showAssistantCopyButton: + timelineEntry.message.role === "assistant" && + terminalAssistantMessageIds.has(timelineEntry.message.id), + }); + } + + if (input.isWorking) { + nextRows.push({ + kind: "working", + id: "working-indicator-row", + createdAt: input.activeTurnStartedAt, + }); + } + + return nextRows; +} + +export function estimateMessagesTimelineRowHeight( + row: MessagesTimelineRow, + input: { + timelineWidthPx: number | null; + expandedWorkGroups?: Readonly>; + turnDiffSummaryByAssistantMessageId?: ReadonlyMap; + }, +): number { + switch (row.kind) { + case "work": + return estimateWorkRowHeight(row, input); + case "proposed-plan": + return estimateTimelineProposedPlanHeight(row.proposedPlan); + case "working": + return 40; + case "message": { + let estimate = estimateTimelineMessageHeight(row.message, { + timelineWidthPx: input.timelineWidthPx, + }); + const turnDiffSummary = input.turnDiffSummaryByAssistantMessageId?.get(row.message.id); + if (turnDiffSummary && turnDiffSummary.files.length > 0) { + estimate += estimateChangedFilesCardHeight(turnDiffSummary); + } + return estimate; + } + } +} + +function estimateWorkRowHeight( + row: Extract, + input: { + expandedWorkGroups?: Readonly>; + }, +): number { + const isExpanded = input.expandedWorkGroups?.[row.id] ?? false; + const hasOverflow = row.groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES; + const visibleEntries = + hasOverflow && !isExpanded ? MAX_VISIBLE_WORK_LOG_ENTRIES : row.groupedEntries.length; + const onlyToolEntries = row.groupedEntries.every((entry) => entry.tone === "tool"); + const showHeader = hasOverflow || !onlyToolEntries; + + // Card chrome, optional header, and one compact work-entry row per visible entry. + return 28 + (showHeader ? 26 : 0) + visibleEntries * 32; +} + +function estimateTimelineProposedPlanHeight(proposedPlan: ProposedPlan): number { + const estimatedLines = Math.max(1, Math.ceil(proposedPlan.planMarkdown.length / 72)); + return 120 + Math.min(estimatedLines * 22, 880); +} + +function estimateChangedFilesCardHeight(turnDiffSummary: TurnDiffSummary): number { + const treeNodes = buildTurnDiffTree(turnDiffSummary.files); + const visibleNodeCount = countTurnDiffTreeNodes(treeNodes); + + // Card chrome: top/bottom padding, header row, and tree spacing. + return 60 + visibleNodeCount * 25; +} + +function countTurnDiffTreeNodes(nodes: ReadonlyArray): number { + let count = 0; + for (const node of nodes) { + count += 1; + if (node.kind === "directory") { + count += countTurnDiffTreeNodes(node.children); + } + } + return count; +} diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsx index 692438c74a..c4bca4b4f0 100644 --- a/apps/web/src/components/chat/MessagesTimeline.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx @@ -42,6 +42,8 @@ beforeAll(() => { }); }); +const ACTIVE_THREAD_ENVIRONMENT_ID = "environment-local" as never; + describe("MessagesTimeline", () => { it("renders inline terminal labels with the composer chip UI", async () => { const { MessagesTimeline } = await import("./MessagesTimeline"); @@ -58,7 +60,7 @@ describe("MessagesTimeline", () => { kind: "message", createdAt: "2026-03-17T19:12:28.000Z", message: { - id: MessageId.makeUnsafe("message-2"), + id: MessageId.make("message-2"), role: "user", text: [ "yoo what's @terminal-1:1-5 mean", @@ -80,11 +82,14 @@ describe("MessagesTimeline", () => { nowIso="2026-03-17T19:12:30.000Z" expandedWorkGroups={{}} onToggleWorkGroup={() => {}} + changedFilesExpandedByTurnId={{}} + onSetChangedFilesExpanded={() => {}} onOpenTurnDiff={() => {}} revertTurnCountByUserMessageId={new Map()} onRevertUserMessage={() => {}} isRevertingCheckpoint={false} onImageExpand={() => {}} + activeThreadEnvironmentId={ACTIVE_THREAD_ENVIRONMENT_ID} markdownCwd={undefined} resolvedTheme="light" timestampFormat="locale" @@ -95,7 +100,7 @@ describe("MessagesTimeline", () => { expect(markup).toContain("Terminal 1 lines 1-5"); expect(markup).toContain("lucide-terminal"); expect(markup).toContain("yoo what's "); - }); + }, 10_000); it("renders context compaction entries in the normal work log", async () => { const { MessagesTimeline } = await import("./MessagesTimeline"); @@ -125,11 +130,14 @@ describe("MessagesTimeline", () => { nowIso="2026-03-17T19:12:30.000Z" expandedWorkGroups={{}} onToggleWorkGroup={() => {}} + changedFilesExpandedByTurnId={{}} + onSetChangedFilesExpanded={() => {}} onOpenTurnDiff={() => {}} revertTurnCountByUserMessageId={new Map()} onRevertUserMessage={() => {}} isRevertingCheckpoint={false} onImageExpand={() => {}} + activeThreadEnvironmentId={ACTIVE_THREAD_ENVIRONMENT_ID} markdownCwd={undefined} resolvedTheme="light" timestampFormat="locale" diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 9e0b895912..f08d544cc1 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1,4 +1,4 @@ -import { type MessageId, type TurnId } from "@t3tools/contracts"; +import { type EnvironmentId, type MessageId, type TurnId } from "@t3tools/contracts"; import { memo, useCallback, @@ -35,14 +35,21 @@ import { } from "lucide-react"; import { Button } from "../ui/button"; import { clamp } from "effect/Number"; -import { estimateTimelineMessageHeight } from "../timelineHeight"; import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview"; import { ProposedPlanCard } from "./ProposedPlanCard"; import { ChangedFilesTree } from "./ChangedFilesTree"; import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel"; import { MessageCopyButton } from "./MessageCopyButton"; -import { computeMessageDurationStart, normalizeCompactToolLabel } from "./MessagesTimeline.logic"; +import { + MAX_VISIBLE_WORK_LOG_ENTRIES, + deriveMessagesTimelineRows, + estimateMessagesTimelineRowHeight, + normalizeCompactToolLabel, + resolveAssistantMessageCopyState, + type MessagesTimelineRow, +} from "./MessagesTimeline.logic"; import { TerminalContextInlineChip } from "./TerminalContextInlineChip"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { deriveDisplayedUserMessageState, type ParsedTerminalContextEntry, @@ -50,19 +57,20 @@ import { import { cn } from "~/lib/utils"; import { type TimestampFormat } from "@t3tools/contracts/settings"; import { formatTimestamp } from "../../timestampFormat"; + import { buildInlineTerminalContextText, formatInlineTerminalContextLabel, textContainsInlineTerminalContextLabels, } from "./userMessageTerminalContexts"; -const MAX_VISIBLE_WORK_LOG_ENTRIES = 6; const ALWAYS_UNVIRTUALIZED_TAIL_ROWS = 8; interface MessagesTimelineProps { hasMessages: boolean; isWorking: boolean; activeTurnInProgress: boolean; + activeTurnId?: TurnId | null; activeTurnStartedAt: string | null; scrollContainer: HTMLDivElement | null; timelineEntries: ReturnType; @@ -72,21 +80,36 @@ interface MessagesTimelineProps { nowIso: string; expandedWorkGroups: Record; onToggleWorkGroup: (groupId: string) => void; + changedFilesExpandedByTurnId: Record; + onSetChangedFilesExpanded: (turnId: TurnId, expanded: boolean) => void; onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void; revertTurnCountByUserMessageId: Map; onRevertUserMessage: (messageId: MessageId) => void; isRevertingCheckpoint: boolean; onImageExpand: (preview: ExpandedImagePreview) => void; + activeThreadEnvironmentId: EnvironmentId; markdownCwd: string | undefined; resolvedTheme: "light" | "dark"; timestampFormat: TimestampFormat; workspaceRoot: string | undefined; + onVirtualizerSnapshot?: (snapshot: { + totalSize: number; + measurements: ReadonlyArray<{ + id: string; + kind: MessagesTimelineRow["kind"]; + index: number; + size: number; + start: number; + end: number; + }>; + }) => void; } export const MessagesTimeline = memo(function MessagesTimeline({ hasMessages, isWorking, activeTurnInProgress, + activeTurnId, activeTurnStartedAt, scrollContainer, timelineEntries, @@ -96,15 +119,19 @@ export const MessagesTimeline = memo(function MessagesTimeline({ nowIso, expandedWorkGroups, onToggleWorkGroup, + changedFilesExpandedByTurnId, + onSetChangedFilesExpanded, onOpenTurnDiff, revertTurnCountByUserMessageId, onRevertUserMessage, isRevertingCheckpoint, onImageExpand, + activeThreadEnvironmentId, markdownCwd, resolvedTheme, timestampFormat, workspaceRoot, + onVirtualizerSnapshot, }: MessagesTimelineProps) { const timelineRootRef = useRef(null); const [timelineWidthPx, setTimelineWidthPx] = useState(null); @@ -134,70 +161,16 @@ export const MessagesTimeline = memo(function MessagesTimeline({ }; }, [hasMessages, isWorking]); - const rows = useMemo(() => { - const nextRows: TimelineRow[] = []; - const durationStartByMessageId = computeMessageDurationStart( - timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])), - ); - - for (let index = 0; index < timelineEntries.length; index += 1) { - const timelineEntry = timelineEntries[index]; - if (!timelineEntry) { - continue; - } - - if (timelineEntry.kind === "work") { - const groupedEntries = [timelineEntry.entry]; - let cursor = index + 1; - while (cursor < timelineEntries.length) { - const nextEntry = timelineEntries[cursor]; - if (!nextEntry || nextEntry.kind !== "work") break; - groupedEntries.push(nextEntry.entry); - cursor += 1; - } - nextRows.push({ - kind: "work", - id: timelineEntry.id, - createdAt: timelineEntry.createdAt, - groupedEntries, - }); - index = cursor - 1; - continue; - } - - if (timelineEntry.kind === "proposed-plan") { - nextRows.push({ - kind: "proposed-plan", - id: timelineEntry.id, - createdAt: timelineEntry.createdAt, - proposedPlan: timelineEntry.proposedPlan, - }); - continue; - } - - nextRows.push({ - kind: "message", - id: timelineEntry.id, - createdAt: timelineEntry.createdAt, - message: timelineEntry.message, - durationStart: - durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt, - showCompletionDivider: - timelineEntry.message.role === "assistant" && - completionDividerBeforeEntryId === timelineEntry.id, - }); - } - - if (isWorking) { - nextRows.push({ - kind: "working", - id: "working-indicator-row", - createdAt: activeTurnStartedAt, - }); - } - - return nextRows; - }, [timelineEntries, completionDividerBeforeEntryId, isWorking, activeTurnStartedAt]); + const rows = useMemo( + () => + deriveMessagesTimelineRows({ + timelineEntries, + completionDividerBeforeEntryId, + isWorking, + activeTurnStartedAt, + }), + [timelineEntries, completionDividerBeforeEntryId, isWorking, activeTurnStartedAt], + ); const firstUnvirtualizedRowIndex = useMemo(() => { const firstTailRowIndex = Math.max(rows.length - ALWAYS_UNVIRTUALIZED_TAIL_ROWS, 0); @@ -241,19 +214,26 @@ export const MessagesTimeline = memo(function MessagesTimeline({ minimum: 0, maximum: rows.length, }); + const virtualMeasurementScopeKey = + timelineWidthPx === null ? "width:unknown" : `width:${Math.round(timelineWidthPx)}`; const rowVirtualizer = useVirtualizer({ count: virtualizedRowCount, getScrollElement: () => scrollContainer, - // Use stable row ids so virtual measurements do not leak across thread switches. - getItemKey: (index: number) => rows[index]?.id ?? index, + // Scope cached row measurements to the current timeline width so offscreen + // rows do not keep stale heights after wrapping changes. + getItemKey: (index: number) => { + const rowId = rows[index]?.id ?? String(index); + return `${virtualMeasurementScopeKey}:${rowId}`; + }, estimateSize: (index: number) => { const row = rows[index]; if (!row) return 96; - if (row.kind === "work") return 112; - if (row.kind === "proposed-plan") return estimateTimelineProposedPlanHeight(row.proposedPlan); - if (row.kind === "working") return 40; - return estimateTimelineMessageHeight(row.message, { timelineWidthPx }); + return estimateMessagesTimelineRowHeight(row, { + expandedWorkGroups, + timelineWidthPx, + turnDiffSummaryByAssistantMessageId, + }); }, measureElement: measureVirtualElement, useAnimationFrameWithResizeObserver: true, @@ -295,22 +275,43 @@ export const MessagesTimeline = memo(function MessagesTimeline({ } }; }, []); + useLayoutEffect(() => { + if (!onVirtualizerSnapshot) { + return; + } + onVirtualizerSnapshot({ + totalSize: rowVirtualizer.getTotalSize(), + measurements: rowVirtualizer.measurementsCache + .slice(0, virtualizedRowCount) + .flatMap((measurement) => { + const row = rows[measurement.index]; + if (!row) { + return []; + } + return [ + { + id: row.id, + kind: row.kind, + index: measurement.index, + size: measurement.size, + start: measurement.start, + end: measurement.end, + }, + ]; + }), + }); + }, [onVirtualizerSnapshot, rowVirtualizer, rows, virtualizedRowCount]); const virtualRows = rowVirtualizer.getVirtualItems(); const nonVirtualizedRows = rows.slice(virtualizedRowCount); - const [allDirectoriesExpandedByTurnId, setAllDirectoriesExpandedByTurnId] = useState< - Record - >({}); - const onToggleAllDirectories = useCallback((turnId: TurnId) => { - setAllDirectoriesExpandedByTurnId((current) => ({ - ...current, - [turnId]: !(current[turnId] ?? true), - })); - }, []); const renderRowContent = (row: TimelineRow) => (
@@ -429,7 +430,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ )}
-

+

{formatTimestamp(row.message.createdAt, timestampFormat)}

@@ -442,6 +443,16 @@ export const MessagesTimeline = memo(function MessagesTimeline({ row.message.role === "assistant" && (() => { const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)"); + const assistantTurnStillInProgress = + activeTurnInProgress && + activeTurnId !== null && + activeTurnId !== undefined && + row.message.turnId === activeTurnId; + const assistantCopyState = resolveAssistantMessageCopyState({ + text: row.message.text ?? null, + showCopyButton: row.showAssistantCopyButton, + streaming: row.message.streaming || assistantTurnStillInProgress, + }); return ( <> {row.showCompletionDivider && ( @@ -467,7 +478,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ const summaryStat = summarizeTurnDiffStats(checkpointFiles); const changedFileCountLabel = String(checkpointFiles.length); const allDirectoriesExpanded = - allDirectoriesExpandedByTurnId[turnSummary.turnId] ?? true; + changedFilesExpandedByTurnId[turnSummary.turnId] ?? true; return (
@@ -489,7 +500,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({ size="xs" variant="outline" data-scroll-anchor-ignore - onClick={() => onToggleAllDirectories(turnSummary.turnId)} + onClick={() => + onSetChangedFilesExpanded(turnSummary.turnId, !allDirectoriesExpanded) + } > {allDirectoriesExpanded ? "Collapse all" : "Expand all"} @@ -516,15 +529,27 @@ export const MessagesTimeline = memo(function MessagesTimeline({
); })()} -

- {formatMessageMeta( - row.message.createdAt, - row.message.streaming - ? formatElapsed(row.durationStart, nowIso) - : formatElapsed(row.durationStart, row.message.completedAt), - timestampFormat, - )} -

+
+

+ {formatMessageMeta( + row.message.createdAt, + row.message.streaming + ? formatElapsed(row.durationStart, nowIso) + : formatElapsed(row.durationStart, row.message.completedAt), + timestampFormat, + )} +

+ {assistantCopyState.visible ? ( +
+ +
+ ) : null} +
); @@ -534,6 +559,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
@@ -585,6 +611,10 @@ export const MessagesTimeline = memo(function MessagesTimeline({
[number]; type TimelineMessage = Extract["message"]; -type TimelineProposedPlan = Extract["proposedPlan"]; -type TimelineWorkEntry = Extract["entry"]; -type TimelineRow = - | { - kind: "work"; - id: string; - createdAt: string; - groupedEntries: TimelineWorkEntry[]; - } - | { - kind: "message"; - id: string; - createdAt: string; - message: TimelineMessage; - durationStart: string; - showCompletionDivider: boolean; - } - | { - kind: "proposed-plan"; - id: string; - createdAt: string; - proposedPlan: TimelineProposedPlan; - } - | { kind: "working"; id: string; createdAt: string | null }; - -function estimateTimelineProposedPlanHeight(proposedPlan: TimelineProposedPlan): number { - const estimatedLines = Math.max(1, Math.ceil(proposedPlan.planMarkdown.length / 72)); - return 120 + Math.min(estimatedLines * 22, 880); -} +type TimelineWorkEntry = Extract["groupedEntries"][number]; +type TimelineRow = MessagesTimelineRow; function formatWorkingTimer(startIso: string, endIso: string): string | null { const startedAtMs = Date.parse(startIso); @@ -726,7 +729,7 @@ const UserMessageBody = memo(function UserMessageBody(props: { } return ( -
+
{inlineNodes}
); @@ -754,7 +757,7 @@ const UserMessageBody = memo(function UserMessageBody(props: { } return ( -
+
{inlineNodes}
); @@ -765,9 +768,9 @@ const UserMessageBody = memo(function UserMessageBody(props: { } return ( -
+    
{props.text} -
+
); }); @@ -819,6 +822,16 @@ function workEntryPreview( : `${firstPath} +${workEntry.changedFiles!.length - 1} more`; } +function workEntryRawCommand( + workEntry: Pick, +): string | null { + const rawCommand = workEntry.rawCommand?.trim(); + if (!rawCommand || !workEntry.command) { + return null; + } + return rawCommand === workEntry.command.trim() ? null : rawCommand; +} + function workEntryIcon(workEntry: TimelineWorkEntry): LucideIcon { if (workEntry.requestKind === "command") return TerminalIcon; if (workEntry.requestKind === "file-read") return EyeIcon; @@ -867,6 +880,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: { const EntryIcon = workEntryIcon(workEntry); const heading = toolWorkEntryHeading(workEntry); const preview = workEntryPreview(workEntry); + const rawCommand = workEntryRawCommand(workEntry); const displayText = preview ? `${heading} - ${preview}` : heading; const hasChangedFiles = (workEntry.changedFiles?.length ?? 0) > 0; const previewIsChangedFiles = hasChangedFiles && !workEntry.command && !workEntry.detail; @@ -880,19 +894,46 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
-

- - {heading} - - {preview && - {preview}} -

+
+

+ + {heading} + + {preview && + (rawCommand ? ( + + + {" "} + - {preview} + + } + /> + +

+ {rawCommand} +
+ + + ) : ( + - {preview} + ))} +

+
{hasChangedFiles && !previewIsChangedFiles && ( diff --git a/apps/web/src/components/chat/MessagesTimeline.virtualization.browser.tsx b/apps/web/src/components/chat/MessagesTimeline.virtualization.browser.tsx new file mode 100644 index 0000000000..be3cf5c67a --- /dev/null +++ b/apps/web/src/components/chat/MessagesTimeline.virtualization.browser.tsx @@ -0,0 +1,1071 @@ +import "../../index.css"; + +import { MessageId, type TurnId } from "@t3tools/contracts"; +import { page } from "vitest/browser"; +import { useCallback, useState, type ComponentProps } from "react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { render } from "vitest-browser-react"; + +import { deriveTimelineEntries, type WorkLogEntry } from "../../session-logic"; +import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types"; +import { MessagesTimeline } from "./MessagesTimeline"; +import { + deriveMessagesTimelineRows, + estimateMessagesTimelineRowHeight, +} from "./MessagesTimeline.logic"; + +const DEFAULT_VIEWPORT = { + width: 960, + height: 1_100, +}; +const MARKDOWN_CWD = "/repo/project"; +const ACTIVE_THREAD_ENVIRONMENT_ID = "environment-local" as never; + +interface RowMeasurement { + actualHeightPx: number; + estimatedHeightPx: number; + timelineWidthPx: number; + virtualizerSizePx: number; + renderedInVirtualizedRegion: boolean; +} + +interface VirtualizationScenario { + name: string; + targetRowId: string; + props: Omit< + ComponentProps, + "scrollContainer" | "activeThreadEnvironmentId" + >; + maxEstimateDeltaPx: number; +} + +interface VirtualizerSnapshot { + totalSize: number; + measurements: ReadonlyArray<{ + id: string; + kind: string; + index: number; + size: number; + start: number; + end: number; + }>; +} + +function MessagesTimelineBrowserHarness( + props: Omit< + ComponentProps, + "scrollContainer" | "activeThreadEnvironmentId" + >, +) { + const [scrollContainer, setScrollContainer] = useState(null); + const [expandedWorkGroups, setExpandedWorkGroups] = useState>( + () => props.expandedWorkGroups, + ); + const [changedFilesExpandedByTurnId, setChangedFilesExpandedByTurnId] = useState< + Record + >(() => props.changedFilesExpandedByTurnId); + const handleToggleWorkGroup = useCallback( + (groupId: string) => { + setExpandedWorkGroups((current) => ({ + ...current, + [groupId]: !(current[groupId] ?? false), + })); + props.onToggleWorkGroup(groupId); + }, + [props], + ); + const handleSetChangedFilesExpanded = useCallback( + (turnId: TurnId, expanded: boolean) => { + setChangedFilesExpandedByTurnId((current) => ({ + ...current, + [turnId]: expanded, + })); + props.onSetChangedFilesExpanded(turnId, expanded); + }, + [props], + ); + + return ( +
+ +
+ ); +} + +function isoAt(offsetSeconds: number): string { + return new Date(Date.UTC(2026, 2, 17, 19, 12, 28) + offsetSeconds * 1_000).toISOString(); +} + +function createMessage(input: { + id: string; + role: ChatMessage["role"]; + text: string; + offsetSeconds: number; + attachments?: ChatMessage["attachments"]; +}): ChatMessage { + return { + id: MessageId.make(input.id), + role: input.role, + text: input.text, + ...(input.attachments ? { attachments: input.attachments } : {}), + createdAt: isoAt(input.offsetSeconds), + ...(input.role === "assistant" ? { completedAt: isoAt(input.offsetSeconds + 1) } : {}), + streaming: false, + }; +} + +function createToolWorkEntry(input: { + id: string; + offsetSeconds: number; + label?: string; + detail?: string; +}): WorkLogEntry { + return { + id: input.id, + createdAt: isoAt(input.offsetSeconds), + label: input.label ?? "exec_command completed", + ...(input.detail ? { detail: input.detail } : {}), + tone: "tool", + toolTitle: "exec_command", + }; +} + +function createPlan(input: { + id: string; + offsetSeconds: number; + planMarkdown: string; +}): ProposedPlan { + return { + id: input.id as ProposedPlan["id"], + turnId: null, + planMarkdown: input.planMarkdown, + implementedAt: null, + implementationThreadId: null, + createdAt: isoAt(input.offsetSeconds), + updatedAt: isoAt(input.offsetSeconds + 1), + }; +} + +function createBaseTimelineProps(input: { + messages?: ChatMessage[]; + proposedPlans?: ProposedPlan[]; + workEntries?: WorkLogEntry[]; + expandedWorkGroups?: Record; + completionDividerBeforeEntryId?: string | null; + turnDiffSummaryByAssistantMessageId?: Map; + onVirtualizerSnapshot?: ComponentProps["onVirtualizerSnapshot"]; +}): Omit, "scrollContainer" | "activeThreadEnvironmentId"> { + return { + hasMessages: true, + isWorking: false, + activeTurnInProgress: false, + activeTurnStartedAt: null, + timelineEntries: deriveTimelineEntries( + input.messages ?? [], + input.proposedPlans ?? [], + input.workEntries ?? [], + ), + completionDividerBeforeEntryId: input.completionDividerBeforeEntryId ?? null, + completionSummary: null, + turnDiffSummaryByAssistantMessageId: input.turnDiffSummaryByAssistantMessageId ?? new Map(), + nowIso: isoAt(10_000), + expandedWorkGroups: input.expandedWorkGroups ?? {}, + onToggleWorkGroup: () => {}, + changedFilesExpandedByTurnId: {}, + onSetChangedFilesExpanded: () => {}, + onOpenTurnDiff: () => {}, + revertTurnCountByUserMessageId: new Map(), + onRevertUserMessage: () => {}, + isRevertingCheckpoint: false, + onImageExpand: () => {}, + markdownCwd: MARKDOWN_CWD, + resolvedTheme: "light", + timestampFormat: "locale", + workspaceRoot: MARKDOWN_CWD, + ...(input.onVirtualizerSnapshot ? { onVirtualizerSnapshot: input.onVirtualizerSnapshot } : {}), + }; +} + +function createFillerMessages(input: { + prefix: string; + startOffsetSeconds: number; + pairCount: number; +}): ChatMessage[] { + const messages: ChatMessage[] = []; + for (let index = 0; index < input.pairCount; index += 1) { + const baseOffset = input.startOffsetSeconds + index * 4; + messages.push( + createMessage({ + id: `${input.prefix}-user-${index}`, + role: "user", + text: `filler user message ${index}`, + offsetSeconds: baseOffset, + }), + ); + messages.push( + createMessage({ + id: `${input.prefix}-assistant-${index}`, + role: "assistant", + text: `filler assistant message ${index}`, + offsetSeconds: baseOffset + 1, + }), + ); + } + return messages; +} + +function createChangedFilesSummary( + targetMessageId: MessageId, + files: TurnDiffSummary["files"], +): Map { + return new Map([ + [ + targetMessageId, + { + turnId: "turn-changed-files" as TurnId, + completedAt: isoAt(10), + assistantMessageId: targetMessageId, + files, + }, + ], + ]); +} + +function createChangedFilesScenario(input: { + name: string; + rowId: string; + files: TurnDiffSummary["files"]; + maxEstimateDeltaPx?: number; +}): VirtualizationScenario { + const beforeMessages = createFillerMessages({ + prefix: `${input.rowId}-before`, + startOffsetSeconds: 0, + pairCount: 2, + }); + const afterMessages = createFillerMessages({ + prefix: `${input.rowId}-after`, + startOffsetSeconds: 40, + pairCount: 8, + }); + const changedFilesMessage = createMessage({ + id: input.rowId, + role: "assistant", + text: "Validation passed on the merged tree.", + offsetSeconds: 12, + }); + + return { + name: input.name, + targetRowId: changedFilesMessage.id, + props: createBaseTimelineProps({ + messages: [...beforeMessages, changedFilesMessage, ...afterMessages], + turnDiffSummaryByAssistantMessageId: createChangedFilesSummary( + changedFilesMessage.id, + input.files, + ), + }), + maxEstimateDeltaPx: input.maxEstimateDeltaPx ?? 72, + }; +} + +function createAssistantMessageScenario(input: { + name: string; + rowId: string; + text: string; + maxEstimateDeltaPx?: number; +}): VirtualizationScenario { + const beforeMessages = createFillerMessages({ + prefix: `${input.rowId}-before`, + startOffsetSeconds: 0, + pairCount: 2, + }); + const afterMessages = createFillerMessages({ + prefix: `${input.rowId}-after`, + startOffsetSeconds: 40, + pairCount: 8, + }); + const assistantMessage = createMessage({ + id: input.rowId, + role: "assistant", + text: input.text, + offsetSeconds: 12, + }); + + return { + name: input.name, + targetRowId: assistantMessage.id, + props: createBaseTimelineProps({ + messages: [...beforeMessages, assistantMessage, ...afterMessages], + }), + maxEstimateDeltaPx: input.maxEstimateDeltaPx ?? 16, + }; +} + +function buildStaticScenarios(): VirtualizationScenario[] { + const beforeMessages = createFillerMessages({ + prefix: "before", + startOffsetSeconds: 0, + pairCount: 2, + }); + const afterMessages = createFillerMessages({ + prefix: "after", + startOffsetSeconds: 40, + pairCount: 8, + }); + + const longUserMessage = createMessage({ + id: "target-user-long", + role: "user", + text: "x".repeat(3_200), + offsetSeconds: 12, + }); + const workEntries = Array.from({ length: 4 }, (_, index) => + createToolWorkEntry({ + id: `target-work-${index}`, + offsetSeconds: 12 + index, + detail: `tool output line ${index + 1}`, + }), + ); + const moderatePlan = createPlan({ + id: "target-plan", + offsetSeconds: 12, + planMarkdown: [ + "# Stabilize virtualization", + "", + "- Gather baseline measurements", + "- Add browser harness coverage", + "- Compare estimated and rendered heights", + "- Fix the broken rows without broad refactors", + "- Re-run lint and typecheck", + ].join("\n"), + }); + return [ + { + name: "long user message", + targetRowId: longUserMessage.id, + props: createBaseTimelineProps({ + messages: [...beforeMessages, longUserMessage, ...afterMessages], + }), + maxEstimateDeltaPx: 56, + }, + { + name: "grouped work log row", + targetRowId: workEntries[0]!.id, + props: createBaseTimelineProps({ + messages: [...beforeMessages, ...afterMessages], + workEntries, + }), + maxEstimateDeltaPx: 56, + }, + { + name: "expanded grouped work log row with show more enabled", + targetRowId: "target-work-expanded-0", + props: createBaseTimelineProps({ + messages: [...beforeMessages, ...afterMessages], + workEntries: Array.from({ length: 10 }, (_, index) => + createToolWorkEntry({ + id: `target-work-expanded-${index}`, + offsetSeconds: 12 + index, + detail: `tool output line ${index + 1}`, + }), + ), + expandedWorkGroups: { + "target-work-expanded-0": true, + }, + }), + maxEstimateDeltaPx: 72, + }, + { + name: "proposed plan row", + targetRowId: moderatePlan.id, + props: createBaseTimelineProps({ + messages: [...beforeMessages, ...afterMessages], + proposedPlans: [moderatePlan], + }), + maxEstimateDeltaPx: 96, + }, + createAssistantMessageScenario({ + name: "assistant single-paragraph row with plain prose", + rowId: "target-assistant-plain-prose", + text: [ + "The host is still expanding to content somewhere in the grid layout.", + "I'm stripping it back further to a plain block container so the test width", + "is actually the timeline width.", + ].join(" "), + }), + createAssistantMessageScenario({ + name: "assistant single-paragraph row with inline code", + rowId: "target-assistant-inline-code", + text: [ + "Typecheck found one exact-optional-property issue in the browser harness:", + "I was always passing `onVirtualizerSnapshot`, including `undefined`.", + "I'm tightening that object construction and rerunning the checks.", + ].join(" "), + maxEstimateDeltaPx: 28, + }), + createChangedFilesScenario({ + name: "assistant changed-files row with a compacted single-chain directory", + rowId: "target-assistant-changed-files-single-chain", + files: [ + { path: "apps/web/src/components/chat/ChangedFilesTree.tsx", additions: 37, deletions: 45 }, + { + path: "apps/web/src/components/chat/ChangedFilesTree.test.tsx", + additions: 0, + deletions: 26, + }, + ], + }), + createChangedFilesScenario({ + name: "assistant changed-files row with a branch after compaction", + rowId: "target-assistant-changed-files-branch-point", + files: [ + { path: "apps/server/src/git/Layers/GitCore.ts", additions: 44, deletions: 38 }, + { path: "apps/server/src/git/Layers/GitCore.test.ts", additions: 18, deletions: 9 }, + { + path: "apps/server/src/provider/Layers/CodexAdapter.ts", + additions: 27, + deletions: 8, + }, + { + path: "apps/server/src/provider/Layers/CodexAdapter.test.ts", + additions: 36, + deletions: 0, + }, + ], + }), + createChangedFilesScenario({ + name: "assistant changed-files row with mixed root and nested entries", + rowId: "target-assistant-changed-files-mixed-root", + files: [ + { path: "README.md", additions: 5, deletions: 1 }, + { path: "packages/contracts/src/orchestration.ts", additions: 13, deletions: 3 }, + { path: "packages/shared/src/git.ts", additions: 8, deletions: 2 }, + ], + }), + ]; +} + +async function nextFrame(): Promise { + await new Promise((resolve) => { + window.requestAnimationFrame(() => resolve()); + }); +} + +async function waitForLayout(): Promise { + await nextFrame(); + await nextFrame(); + await nextFrame(); +} + +async function setViewport(viewport: { width: number; height: number }): Promise { + await page.viewport(viewport.width, viewport.height); + await waitForLayout(); +} + +async function waitForProductionStyles(): Promise { + await vi.waitFor( + () => { + expect( + getComputedStyle(document.documentElement).getPropertyValue("--background").trim(), + ).not.toBe(""); + expect(getComputedStyle(document.body).marginTop).toBe("0px"); + }, + { timeout: 4_000, interval: 16 }, + ); +} + +async function waitForElement( + query: () => T | null, + errorMessage: string, +): Promise { + let element: T | null = null; + await vi.waitFor( + () => { + element = query(); + expect(element, errorMessage).toBeTruthy(); + }, + { timeout: 8_000, interval: 16 }, + ); + if (!element) { + throw new Error(errorMessage); + } + return element; +} + +async function measureTimelineRow(input: { + host: HTMLElement; + props: Omit< + ComponentProps, + "scrollContainer" | "activeThreadEnvironmentId" + >; + targetRowId: string; +}): Promise { + const scrollContainer = await waitForElement( + () => + input.host.querySelector( + '[data-testid="messages-timeline-scroll-container"]', + ), + "Unable to find MessagesTimeline scroll container.", + ); + + const rowSelector = `[data-timeline-row-id="${input.targetRowId}"]`; + const virtualRowSelector = `[data-virtual-row-id="${input.targetRowId}"]`; + + let timelineWidthPx = 0; + let actualHeightPx = 0; + let virtualizerSizePx = 0; + let renderedInVirtualizedRegion = false; + + await vi.waitFor( + async () => { + scrollContainer.scrollTop = 0; + scrollContainer.dispatchEvent(new Event("scroll")); + await waitForLayout(); + + const rowElement = input.host.querySelector(rowSelector); + const virtualRowElement = input.host.querySelector(virtualRowSelector); + const timelineRoot = input.host.querySelector('[data-timeline-root="true"]'); + + expect(rowElement, "Unable to locate target timeline row.").toBeTruthy(); + expect(virtualRowElement, "Unable to locate target virtualized wrapper.").toBeTruthy(); + expect(timelineRoot, "Unable to locate MessagesTimeline root.").toBeTruthy(); + + timelineWidthPx = timelineRoot!.getBoundingClientRect().width; + actualHeightPx = rowElement!.getBoundingClientRect().height; + virtualizerSizePx = Number.parseFloat(virtualRowElement!.dataset.virtualRowSize ?? "0"); + renderedInVirtualizedRegion = virtualRowElement!.hasAttribute("data-index"); + + expect(timelineWidthPx).toBeGreaterThan(0); + expect(actualHeightPx).toBeGreaterThan(0); + expect(virtualizerSizePx).toBeGreaterThan(0); + expect(renderedInVirtualizedRegion).toBe(true); + }, + { timeout: 8_000, interval: 16 }, + ); + + const rows = deriveMessagesTimelineRows({ + timelineEntries: input.props.timelineEntries, + completionDividerBeforeEntryId: input.props.completionDividerBeforeEntryId, + isWorking: input.props.isWorking, + activeTurnStartedAt: input.props.activeTurnStartedAt, + }); + const targetRow = rows.find((row) => row.id === input.targetRowId); + expect(targetRow, `Unable to derive target row ${input.targetRowId}.`).toBeTruthy(); + + return { + actualHeightPx, + estimatedHeightPx: estimateMessagesTimelineRowHeight(targetRow!, { + expandedWorkGroups: input.props.expandedWorkGroups, + timelineWidthPx, + turnDiffSummaryByAssistantMessageId: input.props.turnDiffSummaryByAssistantMessageId, + }), + timelineWidthPx, + virtualizerSizePx, + renderedInVirtualizedRegion, + }; +} + +async function mountMessagesTimeline(input: { + props: Omit< + ComponentProps, + "scrollContainer" | "activeThreadEnvironmentId" + >; + viewport?: { width: number; height: number }; +}) { + const viewport = input.viewport ?? DEFAULT_VIEWPORT; + await setViewport(viewport); + await waitForProductionStyles(); + + const host = document.createElement("div"); + host.style.width = `${viewport.width}px`; + host.style.minWidth = `${viewport.width}px`; + host.style.maxWidth = `${viewport.width}px`; + host.style.height = `${viewport.height}px`; + host.style.minHeight = `${viewport.height}px`; + host.style.maxHeight = `${viewport.height}px`; + host.style.display = "block"; + host.style.overflow = "hidden"; + document.body.append(host); + + const screen = await render(, { + container: host, + }); + await waitForLayout(); + + return { + host, + rerender: async ( + nextProps: Omit< + ComponentProps, + "scrollContainer" | "activeThreadEnvironmentId" + >, + ) => { + await screen.rerender(); + await waitForLayout(); + }, + setContainerSize: async (nextViewport: { width: number; height: number }) => { + await setViewport(nextViewport); + host.style.width = `${nextViewport.width}px`; + host.style.minWidth = `${nextViewport.width}px`; + host.style.maxWidth = `${nextViewport.width}px`; + host.style.height = `${nextViewport.height}px`; + host.style.minHeight = `${nextViewport.height}px`; + host.style.maxHeight = `${nextViewport.height}px`; + await waitForLayout(); + }, + cleanup: async () => { + await screen.unmount(); + host.remove(); + }, + }; +} + +async function measureRenderedRowActualHeight(input: { + host: HTMLElement; + targetRowId: string; +}): Promise { + const rowElement = await waitForElement( + () => input.host.querySelector(`[data-timeline-row-id="${input.targetRowId}"]`), + `Unable to locate rendered row ${input.targetRowId}.`, + ); + return rowElement.getBoundingClientRect().height; +} + +describe("MessagesTimeline virtualization harness", () => { + beforeEach(async () => { + document.body.innerHTML = ""; + await setViewport(DEFAULT_VIEWPORT); + }); + + afterEach(() => { + document.body.innerHTML = ""; + }); + + it.each(buildStaticScenarios())("keeps the $name estimate within tolerance", async (scenario) => { + const mounted = await mountMessagesTimeline({ props: scenario.props }); + + try { + const measurement = await measureTimelineRow({ + host: mounted.host, + props: scenario.props, + targetRowId: scenario.targetRowId, + }); + + expect( + Math.abs(measurement.actualHeightPx - measurement.estimatedHeightPx), + `estimate delta for ${scenario.name}`, + ).toBeLessThanOrEqual(scenario.maxEstimateDeltaPx); + } finally { + await mounted.cleanup(); + } + }); + + it("keeps the changed-files row virtualizer size in sync after collapsing directories", async () => { + const beforeMessages = createFillerMessages({ + prefix: "before-collapse", + startOffsetSeconds: 0, + pairCount: 2, + }); + const afterMessages = createFillerMessages({ + prefix: "after-collapse", + startOffsetSeconds: 40, + pairCount: 8, + }); + const targetMessage = createMessage({ + id: "target-assistant-collapse", + role: "assistant", + text: "Validation passed on the merged tree.", + offsetSeconds: 12, + }); + const props = createBaseTimelineProps({ + messages: [...beforeMessages, targetMessage, ...afterMessages], + turnDiffSummaryByAssistantMessageId: createChangedFilesSummary(targetMessage.id, [ + { path: ".plans/effect-atom.md", additions: 89, deletions: 0 }, + { + path: "apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts", + additions: 4, + deletions: 3, + }, + { + path: "apps/server/src/checkpointing/Layers/CheckpointStore.ts", + additions: 131, + deletions: 128, + }, + { + path: "apps/server/src/checkpointing/Layers/CheckpointStore.test.ts", + additions: 1, + deletions: 1, + }, + { path: "apps/server/src/checkpointing/Errors.ts", additions: 1, deletions: 1 }, + { + path: "apps/server/src/git/Layers/ClaudeTextGeneration.ts", + additions: 106, + deletions: 112, + }, + { path: "apps/server/src/git/Layers/GitCore.ts", additions: 44, deletions: 38 }, + { path: "apps/server/src/git/Layers/GitCore.test.ts", additions: 18, deletions: 9 }, + { + path: "apps/web/src/components/chat/MessagesTimeline.tsx", + additions: 52, + deletions: 7, + }, + { + path: "apps/web/src/components/chat/ChangedFilesTree.tsx", + additions: 32, + deletions: 4, + }, + { path: "packages/contracts/src/orchestration.ts", additions: 13, deletions: 3 }, + { path: "packages/shared/src/git.ts", additions: 8, deletions: 2 }, + ]), + }); + const mounted = await mountMessagesTimeline({ + props, + viewport: { width: 320, height: 700 }, + }); + + try { + const beforeCollapse = await measureTimelineRow({ + host: mounted.host, + props, + targetRowId: targetMessage.id, + }); + const targetRowElement = mounted.host.querySelector( + `[data-timeline-row-id="${targetMessage.id}"]`, + ); + expect(targetRowElement, "Unable to locate target changed-files row.").toBeTruthy(); + + const collapseAllButton = + Array.from(targetRowElement!.querySelectorAll("button")).find( + (button) => button.textContent?.trim() === "Collapse all", + ) ?? null; + expect(collapseAllButton, 'Unable to find "Collapse all" button.').toBeTruthy(); + + collapseAllButton!.click(); + + await vi.waitFor( + async () => { + const afterCollapse = await measureTimelineRow({ + host: mounted.host, + props, + targetRowId: targetMessage.id, + }); + expect(afterCollapse.actualHeightPx).toBeLessThan(beforeCollapse.actualHeightPx - 24); + }, + { timeout: 8_000, interval: 16 }, + ); + + const afterCollapse = await measureTimelineRow({ + host: mounted.host, + props, + targetRowId: targetMessage.id, + }); + expect( + Math.abs(afterCollapse.actualHeightPx - afterCollapse.virtualizerSizePx), + ).toBeLessThanOrEqual(8); + } finally { + await mounted.cleanup(); + } + }); + + it("keeps the work-log row virtualizer size in sync after show more expands the group", async () => { + const beforeMessages = createFillerMessages({ + prefix: "before-worklog-expand", + startOffsetSeconds: 0, + pairCount: 2, + }); + const afterMessages = createFillerMessages({ + prefix: "after-worklog-expand", + startOffsetSeconds: 40, + pairCount: 8, + }); + const workEntries = Array.from({ length: 10 }, (_, index) => + createToolWorkEntry({ + id: `target-work-toggle-${index}`, + offsetSeconds: 12 + index, + detail: `tool output line ${index + 1}`, + }), + ); + const props = createBaseTimelineProps({ + messages: [...beforeMessages, ...afterMessages], + workEntries, + }); + const mounted = await mountMessagesTimeline({ props }); + + try { + const beforeExpand = await measureTimelineRow({ + host: mounted.host, + props, + targetRowId: workEntries[0]!.id, + }); + const targetRowElement = mounted.host.querySelector( + `[data-timeline-row-id="${workEntries[0]!.id}"]`, + ); + expect(targetRowElement, "Unable to locate target work-log row.").toBeTruthy(); + + const showMoreButton = + Array.from(targetRowElement!.querySelectorAll("button")).find((button) => + button.textContent?.includes("Show 4 more"), + ) ?? null; + expect(showMoreButton, 'Unable to find "Show more" button.').toBeTruthy(); + + showMoreButton!.click(); + + await vi.waitFor( + async () => { + const afterExpand = await measureTimelineRow({ + host: mounted.host, + props, + targetRowId: workEntries[0]!.id, + }); + expect(afterExpand.actualHeightPx).toBeGreaterThan(beforeExpand.actualHeightPx + 72); + }, + { timeout: 8_000, interval: 16 }, + ); + + const afterExpand = await measureTimelineRow({ + host: mounted.host, + props, + targetRowId: workEntries[0]!.id, + }); + expect( + Math.abs(afterExpand.actualHeightPx - afterExpand.virtualizerSizePx), + ).toBeLessThanOrEqual(8); + } finally { + await mounted.cleanup(); + } + }); + + it("preserves measured tail row heights when rows transition into virtualization", async () => { + const beforeMessages = createFillerMessages({ + prefix: "tail-transition-before", + startOffsetSeconds: 0, + pairCount: 1, + }); + const afterMessages = createFillerMessages({ + prefix: "tail-transition-after", + startOffsetSeconds: 40, + pairCount: 3, + }); + const targetMessage = createMessage({ + id: "target-tail-transition", + role: "assistant", + text: "Validation passed on the merged tree.", + offsetSeconds: 12, + }); + let latestSnapshot: VirtualizerSnapshot | null = null; + const initialProps = createBaseTimelineProps({ + messages: [...beforeMessages, targetMessage, ...afterMessages], + turnDiffSummaryByAssistantMessageId: createChangedFilesSummary(targetMessage.id, [ + { path: ".plans/effect-atom.md", additions: 89, deletions: 0 }, + { + path: "apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts", + additions: 4, + deletions: 3, + }, + { + path: "apps/server/src/checkpointing/Layers/CheckpointStore.ts", + additions: 131, + deletions: 128, + }, + { + path: "apps/server/src/checkpointing/Layers/CheckpointStore.test.ts", + additions: 1, + deletions: 1, + }, + { path: "apps/server/src/checkpointing/Errors.ts", additions: 1, deletions: 1 }, + { + path: "apps/server/src/git/Layers/ClaudeTextGeneration.ts", + additions: 106, + deletions: 112, + }, + { path: "apps/server/src/git/Layers/GitCore.ts", additions: 44, deletions: 38 }, + { path: "apps/server/src/git/Layers/GitCore.test.ts", additions: 18, deletions: 9 }, + { + path: "apps/web/src/components/chat/MessagesTimeline.tsx", + additions: 52, + deletions: 7, + }, + { + path: "apps/web/src/components/chat/ChangedFilesTree.tsx", + additions: 32, + deletions: 4, + }, + { path: "packages/contracts/src/orchestration.ts", additions: 13, deletions: 3 }, + { path: "packages/shared/src/git.ts", additions: 8, deletions: 2 }, + ]), + onVirtualizerSnapshot: (snapshot) => { + latestSnapshot = { + totalSize: snapshot.totalSize, + measurements: snapshot.measurements, + }; + }, + }); + + const mounted = await mountMessagesTimeline({ props: initialProps }); + + try { + const initiallyRenderedHeight = await measureRenderedRowActualHeight({ + host: mounted.host, + targetRowId: targetMessage.id, + }); + + const appendedProps = createBaseTimelineProps({ + messages: [ + ...beforeMessages, + targetMessage, + ...afterMessages, + ...createFillerMessages({ + prefix: "tail-transition-extra", + startOffsetSeconds: 120, + pairCount: 8, + }), + ], + turnDiffSummaryByAssistantMessageId: initialProps.turnDiffSummaryByAssistantMessageId, + onVirtualizerSnapshot: initialProps.onVirtualizerSnapshot, + }); + await mounted.rerender(appendedProps); + + const scrollContainer = await waitForElement( + () => + mounted.host.querySelector( + '[data-testid="messages-timeline-scroll-container"]', + ), + "Unable to find MessagesTimeline scroll container.", + ); + scrollContainer.scrollTop = scrollContainer.scrollHeight; + scrollContainer.dispatchEvent(new Event("scroll")); + await waitForLayout(); + + await vi.waitFor( + () => { + const measurement = latestSnapshot?.measurements.find( + (entry) => entry.id === targetMessage.id, + ); + expect( + measurement, + "Expected target row to transition into virtualizer cache.", + ).toBeTruthy(); + expect(Math.abs((measurement?.size ?? 0) - initiallyRenderedHeight)).toBeLessThanOrEqual( + 8, + ); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("preserves measured tail image row heights when rows transition into virtualization", async () => { + const beforeMessages = createFillerMessages({ + prefix: "tail-image-before", + startOffsetSeconds: 0, + pairCount: 1, + }); + const afterMessages = createFillerMessages({ + prefix: "tail-image-after", + startOffsetSeconds: 40, + pairCount: 3, + }); + const targetMessage = createMessage({ + id: "target-tail-image-transition", + role: "user", + text: "Here is a narrow screenshot.", + offsetSeconds: 12, + attachments: [ + { + type: "image", + id: "target-tail-image", + name: "narrow.svg", + mimeType: "image/svg+xml", + sizeBytes: 512, + previewUrl: + "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='240' height='72'%3E%3Crect width='240' height='72' fill='%23dbeafe'/%3E%3C/svg%3E", + }, + ], + }); + let latestSnapshot: VirtualizerSnapshot | null = null; + const initialProps = createBaseTimelineProps({ + messages: [...beforeMessages, targetMessage, ...afterMessages], + onVirtualizerSnapshot: (snapshot) => { + latestSnapshot = { + totalSize: snapshot.totalSize, + measurements: snapshot.measurements, + }; + }, + }); + const mounted = await mountMessagesTimeline({ props: initialProps }); + + try { + await vi.waitFor( + () => { + const image = mounted.host.querySelector( + `[data-timeline-row-id="${targetMessage.id}"] img`, + ); + expect(image?.naturalHeight ?? 0).toBeGreaterThan(0); + }, + { timeout: 8_000, interval: 16 }, + ); + + const initiallyRenderedHeight = await measureRenderedRowActualHeight({ + host: mounted.host, + targetRowId: targetMessage.id, + }); + const appendedProps = createBaseTimelineProps({ + messages: [ + ...beforeMessages, + targetMessage, + ...afterMessages, + ...createFillerMessages({ + prefix: "tail-image-extra", + startOffsetSeconds: 120, + pairCount: 8, + }), + ], + onVirtualizerSnapshot: initialProps.onVirtualizerSnapshot, + }); + await mounted.rerender(appendedProps); + + const scrollContainer = await waitForElement( + () => + mounted.host.querySelector( + '[data-testid="messages-timeline-scroll-container"]', + ), + "Unable to find MessagesTimeline scroll container.", + ); + scrollContainer.scrollTop = scrollContainer.scrollHeight; + scrollContainer.dispatchEvent(new Event("scroll")); + await waitForLayout(); + + await vi.waitFor( + () => { + const measurement = latestSnapshot?.measurements.find( + (entry) => entry.id === targetMessage.id, + ); + expect( + measurement, + "Expected target image row to transition into virtualizer cache.", + ).toBeTruthy(); + expect(Math.abs((measurement?.size ?? 0) - initiallyRenderedHeight)).toBeLessThanOrEqual( + 8, + ); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); +}); diff --git a/apps/web/src/components/chat/OpenInPicker.tsx b/apps/web/src/components/chat/OpenInPicker.tsx index 6a956f6f42..d30fa9be04 100644 --- a/apps/web/src/components/chat/OpenInPicker.tsx +++ b/apps/web/src/components/chat/OpenInPicker.tsx @@ -6,9 +6,19 @@ import { ChevronDownIcon, FolderClosedIcon } from "lucide-react"; import { Button } from "../ui/button"; import { Group, GroupSeparator } from "../ui/group"; import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "../ui/menu"; -import { AntigravityIcon, CursorIcon, Icon, VisualStudioCode, Zed } from "../Icons"; +import { + AntigravityIcon, + CursorIcon, + Icon, + TraeIcon, + IntelliJIdeaIcon, + VisualStudioCode, + VisualStudioCodeInsiders, + VSCodium, + Zed, +} from "../Icons"; import { isMacPlatform, isWindowsPlatform } from "~/lib/utils"; -import { readNativeApi } from "~/nativeApi"; +import { readLocalApi } from "~/localApi"; const resolveOptions = (platform: string, availableEditors: ReadonlyArray) => { const baseOptions: ReadonlyArray<{ label: string; Icon: Icon; value: EditorId }> = [ @@ -17,6 +27,11 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray { - const api = readNativeApi(); + const api = readLocalApi(); if (!api || !openInCwd) return; const editor = editorId ?? preferredEditor; if (!editor) return; @@ -90,7 +110,7 @@ export const OpenInPicker = memo(function OpenInPicker({ useEffect(() => { const handler = (e: globalThis.KeyboardEvent) => { - const api = readNativeApi(); + const api = readLocalApi(); if (!isOpenFavoriteEditorShortcut(e, keybindings)) return; if (!api || !openInCwd) return; if (!preferredEditor) return; diff --git a/apps/web/src/components/chat/ProposedPlanCard.tsx b/apps/web/src/components/chat/ProposedPlanCard.tsx index c8956b9cfa..a36cb097cb 100644 --- a/apps/web/src/components/chat/ProposedPlanCard.tsx +++ b/apps/web/src/components/chat/ProposedPlanCard.tsx @@ -1,4 +1,5 @@ import { memo, useState, useId } from "react"; +import type { EnvironmentId } from "@t3tools/contracts"; import { buildCollapsedProposedPlanPreviewMarkdown, buildProposedPlanMarkdownFilename, @@ -24,14 +25,17 @@ import { DialogTitle, } from "../ui/dialog"; import { toastManager } from "../ui/toast"; -import { readNativeApi } from "~/nativeApi"; +import { readEnvironmentApi } from "~/environmentApi"; +import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; export const ProposedPlanCard = memo(function ProposedPlanCard({ planMarkdown, + environmentId, cwd, workspaceRoot, }: { planMarkdown: string; + environmentId: EnvironmentId; cwd: string | undefined; workspaceRoot: string | undefined; }) { @@ -39,6 +43,15 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({ const [isSaveDialogOpen, setIsSaveDialogOpen] = useState(false); const [savePath, setSavePath] = useState(""); const [isSavingToWorkspace, setIsSavingToWorkspace] = useState(false); + const { copyToClipboard, isCopied } = useCopyToClipboard({ + onError: (error) => { + toastManager.add({ + type: "error", + title: "Could not copy plan", + description: error instanceof Error ? error.message : "An error occurred while copying.", + }); + }, + }); const savePathInputId = useId(); const title = proposedPlanTitle(planMarkdown) ?? "Proposed plan"; const lineCount = planMarkdown.split("\n").length; @@ -54,6 +67,10 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({ downloadPlanAsTextFile(downloadFilename, saveContents); }; + const handleCopyPlan = () => { + copyToClipboard(saveContents); + }; + const openSaveDialog = () => { if (!workspaceRoot) { toastManager.add({ @@ -68,7 +85,7 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({ }; const handleSaveToWorkspace = () => { - const api = readNativeApi(); + const api = readEnvironmentApi(environmentId); const relativePath = savePath.trim(); if (!api || !workspaceRoot) { return; @@ -127,6 +144,9 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({