Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f7807e5e8a | ||
|
|
47e5f061a4 | ||
|
|
026007ad9d |
No files matched your search
@@ -1,22 +0,0 @@
|
||||
{
|
||||
"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"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,302 +0,0 @@
|
||||
# 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.
|
||||
@@ -10,7 +10,6 @@ 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
|
||||
@@ -72,12 +71,11 @@ jobs:
|
||||
- name: Verify preload bundle output
|
||||
run: |
|
||||
test -f apps/desktop/dist-electron/preload.js
|
||||
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
|
||||
grep -nE "desktopBridge|getWsUrl|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
|
||||
|
||||
@@ -19,7 +19,6 @@ 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 }}
|
||||
@@ -82,7 +81,6 @@ jobs:
|
||||
name: Build ${{ matrix.label }}
|
||||
needs: preflight
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -229,7 +227,6 @@ jobs:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, build]
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
@@ -263,7 +260,6 @@ 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
|
||||
@@ -311,7 +307,6 @@ jobs:
|
||||
name: Finalize release
|
||||
needs: [preflight, release]
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- id: app_token
|
||||
name: Mint release app token
|
||||
|
||||
@@ -21,4 +21,3 @@ apps/web/src/components/__screenshots__
|
||||
.vitest-*
|
||||
__screenshots__/
|
||||
.tanstack
|
||||
squashfs-root/
|
||||
+1
-2
@@ -9,8 +9,7 @@
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo",
|
||||
"**/routeTree.gen.ts",
|
||||
"apps/web/public/mockServiceWorker.js",
|
||||
"apps/web/src/lib/vendor/qrcodegen.ts"
|
||||
"apps/web/public/mockServiceWorker.js"
|
||||
],
|
||||
"sortPackageJson": {}
|
||||
}
|
||||
@@ -1,823 +0,0 @@
|
||||
# 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:<port>`
|
||||
|
||||
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<AuthCapabilities>;
|
||||
readonly authenticateHttpRequest: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
routeClass: RouteAuthClass,
|
||||
) => Effect.Effect<AuthContext, AuthError>;
|
||||
readonly authenticateWebSocketUpgrade: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthContext, AuthError>;
|
||||
readonly exchangeBootstrapCredential: (
|
||||
input: BootstrapExchangeInput,
|
||||
) => Effect.Effect<SessionGrant, AuthError>;
|
||||
}
|
||||
|
||||
export class ServerAuth extends ServiceMap.Service<ServerAuth, ServerAuthShape>()(
|
||||
"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<BootstrapCredential>;
|
||||
readonly issueOneTimeToken: (
|
||||
input: IssueOneTimeTokenInput,
|
||||
) => Effect.Effect<BootstrapCredential>;
|
||||
readonly consume: (
|
||||
presented: PresentedBootstrapCredential,
|
||||
) => Effect.Effect<ConsumedBootstrapCredential, BootstrapCredentialError>;
|
||||
}
|
||||
```
|
||||
|
||||
### `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<BrowserSessionGrant, SessionCredentialError>;
|
||||
readonly createBearerSession: (
|
||||
input: CreateSessionFromBootstrapInput,
|
||||
) => Effect.Effect<BearerSessionGrant, SessionCredentialError>;
|
||||
readonly authenticateCookie: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthContext, SessionCredentialError>;
|
||||
readonly authenticateBearer: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthContext, SessionCredentialError>;
|
||||
}
|
||||
```
|
||||
|
||||
### `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.
|
||||
@@ -45,8 +45,6 @@ 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.
|
||||
|
||||
@@ -1,87 +1,68 @@
|
||||
# Remote Access
|
||||
# Remote Access Setup
|
||||
|
||||
Use this when you want to connect to a T3 Code server from another device such as a phone, tablet, or separate desktop app.
|
||||
Use this when you want to open T3 Code from another device (phone, tablet, another laptop).
|
||||
|
||||
## Recommended Setup
|
||||
## CLI ↔ Env option map
|
||||
|
||||
Use a trusted private network that meshes your devices together, such as a tailnet.
|
||||
The T3 Code CLI accepts the following configuration options, available either as CLI flags or environment variables:
|
||||
|
||||
That gives you:
|
||||
| CLI flag | Env var | Notes |
|
||||
| ----------------------- | --------------------- | ------------------------------------------------------------------------------------ |
|
||||
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
|
||||
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
|
||||
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
|
||||
| `--base-dir <path>` | `T3CODE_HOME` | Base directory. |
|
||||
| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
|
||||
| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
|
||||
| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. Use this for standard CLI and remote-server flows. |
|
||||
| `--bootstrap-fd <fd>` | `T3CODE_BOOTSTRAP_FD` | Read a one-shot bootstrap envelope from an inherited file descriptor during startup. |
|
||||
|
||||
- a stable address to connect to
|
||||
- transport security at the network layer
|
||||
- less exposure than opening the server to the public internet
|
||||
> TIP: Use the `--help` flag to see all available options and their descriptions.
|
||||
|
||||
## Enabling Network Access
|
||||
## Security First
|
||||
|
||||
There are two ways to expose your server for remote connections: from the desktop app or from the CLI.
|
||||
- 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 <fd>`.
|
||||
With `--bootstrap-fd <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.
|
||||
|
||||
### Option 1: Desktop App
|
||||
## 1) Build + run server for remote access
|
||||
|
||||
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`.
|
||||
Remote access should use the built web app (not local Vite redirect mode).
|
||||
|
||||
```bash
|
||||
npx t3 serve --host "$(tailscale ip -4)"
|
||||
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
|
||||
```
|
||||
|
||||
`t3 serve` starts the server without opening a browser and prints:
|
||||
Then open on your phone:
|
||||
|
||||
- a connection string
|
||||
- a pairing token
|
||||
- a pairing URL
|
||||
- a QR code for the pairing URL
|
||||
`http://<your-machine-ip>:3773`
|
||||
|
||||
From there, connect from another device in either of these ways:
|
||||
Example:
|
||||
|
||||
- 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
|
||||
`http://192.168.1.42:3773`
|
||||
|
||||
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.
|
||||
Notes:
|
||||
|
||||
> 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.
|
||||
- `--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.
|
||||
|
||||
## How Pairing Works
|
||||
## 2) Tailnet / Tailscale access
|
||||
|
||||
The remote device does not need a long-lived secret up front.
|
||||
If you use Tailscale, you can bind directly to your Tailnet address.
|
||||
|
||||
Instead:
|
||||
```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
|
||||
```
|
||||
|
||||
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.
|
||||
Open from any device in your tailnet:
|
||||
|
||||
After pairing, future access is session-based. You do not need to keep reusing the original token unless you are pairing a new device.
|
||||
`http://<tailnet-ip>:3773`
|
||||
|
||||
## 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.
|
||||
You can also bind `--host 0.0.0.0` and connect through the Tailnet IP, but binding directly to the Tailnet IP limits exposure.
|
||||
@@ -5,17 +5,8 @@ import { join } from "node:path";
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
import { waitForResources } from "./wait-for-resources.mjs";
|
||||
|
||||
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 port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
|
||||
const devServerUrl = `http://localhost:${port}`;
|
||||
const requiredFiles = [
|
||||
"dist-electron/main.js",
|
||||
"dist-electron/preload.js",
|
||||
@@ -32,7 +23,6 @@ const childTreeGracePeriodMs = 1_200;
|
||||
await waitForResources({
|
||||
baseDir: desktopDir,
|
||||
files: requiredFiles,
|
||||
tcpHost: devServer.hostname,
|
||||
tcpPort: port,
|
||||
});
|
||||
|
||||
@@ -72,7 +62,10 @@ function startApp() {
|
||||
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
|
||||
{
|
||||
cwd: desktopDir,
|
||||
env: childEnv,
|
||||
env: {
|
||||
...childEnv,
|
||||
VITE_DEV_SERVER_URL: devServerUrl,
|
||||
},
|
||||
stdio: "inherit",
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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 = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
|
||||
const APP_BUNDLE_ID = "com.t3tools.t3code";
|
||||
const LAUNCHER_VERSION = 1;
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
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("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 127.0.0.1 between 65534 and 65535");
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[65534, "127.0.0.1"],
|
||||
[65535, "127.0.0.1"],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,53 +0,0 @@
|
||||
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 canListenOnHost?: (port: number, host: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
const defaultCanListenOnHost = async (port: number, host: string): Promise<boolean> =>
|
||||
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;
|
||||
|
||||
export async function resolveDesktopBackendPort({
|
||||
host,
|
||||
startPort = DEFAULT_DESKTOP_BACKEND_PORT,
|
||||
maxPort = MAX_TCP_PORT,
|
||||
canListenOnHost = defaultCanListenOnHost,
|
||||
}: ResolveDesktopBackendPortOptions): Promise<number> {
|
||||
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}`);
|
||||
}
|
||||
|
||||
// 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 canListenOnHost(port, host)) {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`No desktop backend port is available on ${host} between ${startPort} and ${maxPort}`,
|
||||
);
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
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<typeof fetch>()
|
||||
.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<typeof fetch>()
|
||||
.mockImplementationOnce(
|
||||
(_input, init) =>
|
||||
new Promise((_resolve, reject) => {
|
||||
init?.signal?.addEventListener(
|
||||
"abort",
|
||||
() => {
|
||||
reject(new Error("request timed out"));
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
}) as ReturnType<typeof fetch>,
|
||||
)
|
||||
.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<typeof fetch>().mockImplementation(
|
||||
() =>
|
||||
new Promise((_resolve, reject) => {
|
||||
controller.signal.addEventListener(
|
||||
"abort",
|
||||
() => {
|
||||
reject(new BackendReadinessAbortedError());
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
}) as ReturnType<typeof fetch>,
|
||||
);
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,103 +0,0 @@
|
||||
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<void> {
|
||||
return new Promise<void>((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<void> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,234 +0,0 @@
|
||||
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.makeUnsafe("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");
|
||||
});
|
||||
});
|
||||
@@ -1,216 +0,0 @@
|
||||
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<T>(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<SavedEnvironmentRegistryDocument>(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<ClientSettingsDocument>(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);
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,51 +0,0 @@
|
||||
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);
|
||||
}
|
||||
+42
-466
@@ -7,23 +7,18 @@ 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,
|
||||
@@ -31,27 +26,9 @@ 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 {
|
||||
@@ -81,21 +58,9 @@ 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_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 GET_WS_URL_CHANNEL = "desktop:get-ws-url";
|
||||
const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
|
||||
const STATE_DIR = Path.join(BASE_DIR, "userdata");
|
||||
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);
|
||||
@@ -111,12 +76,10 @@ 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";
|
||||
|
||||
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
|
||||
type LinuxDesktopNamedApp = Electron.App & {
|
||||
@@ -126,13 +89,8 @@ type LinuxDesktopNamedApp = Electron.App & {
|
||||
let mainWindow: BrowserWindow | null = null;
|
||||
let backendProcess: ChildProcess.ChildProcess | null = null;
|
||||
let backendPort = 0;
|
||||
let backendBindHost = DESKTOP_LOOPBACK_HOST;
|
||||
let backendBootstrapToken = "";
|
||||
let backendHttpUrl = "";
|
||||
let backendAuthToken = "";
|
||||
let backendWsUrl = "";
|
||||
let backendEndpointUrl: string | null = null;
|
||||
let backendAdvertisedHost: string | null = null;
|
||||
let backendReadinessAbortController: AbortController | null = null;
|
||||
let restartAttempt = 0;
|
||||
let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let isQuitting = false;
|
||||
@@ -141,12 +99,8 @@ 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<ChildProcess.ChildProcess>();
|
||||
const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
|
||||
platform: process.platform,
|
||||
processArch: process.arch,
|
||||
@@ -167,143 +121,17 @@ 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<DesktopServerExposureState> {
|
||||
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`);
|
||||
@@ -351,27 +179,6 @@ function getSafeTheme(rawTheme: unknown): DesktopTheme | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function waitForBackendHttpReady(baseUrl: string): Promise<void> {
|
||||
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,
|
||||
@@ -716,7 +523,10 @@ function dispatchMenuAction(action: string): void {
|
||||
const send = () => {
|
||||
if (targetWindow.isDestroyed()) return;
|
||||
targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
|
||||
revealWindow(targetWindow);
|
||||
if (!targetWindow.isVisible()) {
|
||||
targetWindow.show();
|
||||
}
|
||||
targetWindow.focus();
|
||||
};
|
||||
|
||||
if (targetWindow.webContents.isLoadingMainFrame()) {
|
||||
@@ -728,15 +538,12 @@ 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.");
|
||||
@@ -940,26 +747,6 @@ 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;
|
||||
@@ -973,8 +760,6 @@ function setUpdateState(patch: Partial<DesktopUpdateState>): void {
|
||||
}
|
||||
|
||||
function shouldEnableAutoUpdates(): boolean {
|
||||
const hasUpdateFeedConfig =
|
||||
readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES);
|
||||
return (
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment,
|
||||
@@ -982,7 +767,6 @@ function shouldEnableAutoUpdates(): boolean {
|
||||
platform: process.platform,
|
||||
appImage: process.env.APPIMAGE,
|
||||
disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
|
||||
hasUpdateFeedConfig,
|
||||
}) === null
|
||||
);
|
||||
}
|
||||
@@ -1066,6 +850,17 @@ 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) {
|
||||
@@ -1090,17 +885,6 @@ 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.
|
||||
@@ -1204,7 +988,6 @@ 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}`);
|
||||
@@ -1232,14 +1015,7 @@ function startBackend(): void {
|
||||
noBrowser: true,
|
||||
port: backendPort,
|
||||
t3Home: BASE_DIR,
|
||||
host: backendBindHost,
|
||||
desktopBootstrapToken: backendBootstrapToken,
|
||||
...(backendObservabilitySettings.otlpTracesUrl
|
||||
? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl }
|
||||
: {}),
|
||||
...(backendObservabilitySettings.otlpMetricsUrl
|
||||
? { otlpMetricsUrl: backendObservabilitySettings.otlpMetricsUrl }
|
||||
: {}),
|
||||
authToken: backendAuthToken,
|
||||
})}\n`,
|
||||
);
|
||||
bootstrapStream.end();
|
||||
@@ -1266,33 +1042,27 @@ 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 || wasExpected) return;
|
||||
if (isQuitting) return;
|
||||
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
|
||||
scheduleBackendRestart(reason);
|
||||
});
|
||||
}
|
||||
|
||||
function stopBackend(): void {
|
||||
cancelBackendReadinessWait();
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
restartTimer = null;
|
||||
@@ -1303,7 +1073,6 @@ 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) {
|
||||
@@ -1314,7 +1083,6 @@ function stopBackend(): void {
|
||||
}
|
||||
|
||||
async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
|
||||
cancelBackendReadinessWait();
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
restartTimer = null;
|
||||
@@ -1325,7 +1093,6 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
|
||||
if (!child) return;
|
||||
const backendChild = child;
|
||||
if (backendChild.exitCode !== null || backendChild.signalCode !== null) return;
|
||||
expectedBackendExitChildren.add(backendChild);
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
let settled = false;
|
||||
@@ -1367,116 +1134,9 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
|
||||
}
|
||||
|
||||
function registerIpcHandlers(): void {
|
||||
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.removeAllListeners(GET_WS_URL_CHANNEL);
|
||||
ipcMain.on(GET_WS_URL_CHANNEL, (event) => {
|
||||
event.returnValue = backendWsUrl;
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
|
||||
@@ -1644,19 +1304,14 @@ function getIconOption(): { icon: string } | Record<string, never> {
|
||||
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: isDevelopment,
|
||||
show: false,
|
||||
autoHideMenuBar: true,
|
||||
backgroundColor: getInitialWindowBackgroundColor(),
|
||||
...getIconOption(),
|
||||
title: APP_DISPLAY_NAME,
|
||||
titleBarStyle: "hiddenInset",
|
||||
@@ -1687,14 +1342,6 @@ 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" },
|
||||
);
|
||||
}
|
||||
|
||||
menuTemplate.push(
|
||||
{ role: "cut", enabled: params.editFlags.canCut },
|
||||
{ role: "copy", enabled: params.editFlags.canCopy },
|
||||
@@ -1721,20 +1368,15 @@ function createWindow(): BrowserWindow {
|
||||
window.setTitle(APP_DISPLAY_NAME);
|
||||
emitUpdateState();
|
||||
});
|
||||
if (!isDevelopment) {
|
||||
window.once("ready-to-show", () => {
|
||||
revealWindow(window);
|
||||
});
|
||||
}
|
||||
window.once("ready-to-show", () => {
|
||||
window.show();
|
||||
});
|
||||
|
||||
if (isDevelopment) {
|
||||
void window.loadURL(resolveDesktopDevServerUrl());
|
||||
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
setImmediate(() => {
|
||||
revealWindow(window);
|
||||
});
|
||||
} else {
|
||||
void window.loadURL(resolveDesktopWindowUrl());
|
||||
void window.loadURL(`${DESKTOP_SCHEME}://app/index.html`);
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
@@ -1746,14 +1388,6 @@ 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()`.
|
||||
@@ -1763,71 +1397,21 @@ configureAppIdentity();
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
writeDesktopLogHeader("bootstrap start");
|
||||
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,
|
||||
}));
|
||||
writeDesktopLogHeader(
|
||||
configuredBackendPort === undefined
|
||||
? `selected backend port via sequential scan startPort=${DEFAULT_DESKTOP_BACKEND_PORT} port=${backendPort}`
|
||||
: `using configured backend port port=${backendPort}`,
|
||||
backendPort = await Effect.service(NetService).pipe(
|
||||
Effect.flatMap((net) => net.reserveLoopbackPort()),
|
||||
Effect.provide(NetService.layer),
|
||||
Effect.runPromise,
|
||||
);
|
||||
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",
|
||||
);
|
||||
}
|
||||
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}`);
|
||||
|
||||
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");
|
||||
}
|
||||
@@ -1837,7 +1421,6 @@ app.on("before-quit", () => {
|
||||
updateInstallInFlight = false;
|
||||
writeDesktopLogHeader("before-quit received");
|
||||
clearUpdatePollTimer();
|
||||
cancelBackendReadinessWait();
|
||||
stopBackend();
|
||||
restoreStdIoCapture?.();
|
||||
});
|
||||
@@ -1851,19 +1434,13 @@ app
|
||||
registerDesktopProtocol();
|
||||
configureAutoUpdater();
|
||||
void bootstrap().catch((error) => {
|
||||
if (isBackendReadinessAborted(error) && isQuitting) {
|
||||
return;
|
||||
}
|
||||
handleFatalStartupError("bootstrap", error);
|
||||
});
|
||||
|
||||
app.on("activate", () => {
|
||||
const existingWindow = mainWindow ?? BrowserWindow.getAllWindows()[0];
|
||||
if (existingWindow) {
|
||||
revealWindow(existingWindow);
|
||||
return;
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
mainWindow = createWindow();
|
||||
}
|
||||
mainWindow = createWindow();
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
@@ -1882,7 +1459,6 @@ if (process.platform !== "win32") {
|
||||
isQuitting = true;
|
||||
writeDesktopLogHeader("SIGINT received");
|
||||
clearUpdatePollTimer();
|
||||
cancelBackendReadinessWait();
|
||||
stopBackend();
|
||||
restoreStdIoCapture?.();
|
||||
app.quit();
|
||||
|
||||
@@ -12,38 +12,13 @@ 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_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 GET_WS_URL_CHANNEL = "desktop:get-ws-url";
|
||||
|
||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
getLocalEnvironmentBootstrap: () => {
|
||||
const result = ipcRenderer.sendSync(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
|
||||
if (typeof result !== "object" || result === null) {
|
||||
return null;
|
||||
}
|
||||
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
|
||||
getWsUrl: () => {
|
||||
const result = ipcRenderer.sendSync(GET_WS_URL_CHANNEL);
|
||||
return typeof result === "string" ? result : null;
|
||||
},
|
||||
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),
|
||||
|
||||
@@ -1,139 +0,0 @@
|
||||
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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,80 +0,0 @@
|
||||
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<NetworkInterfaceInfo[]>,
|
||||
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<NetworkInterfaceInfo[]>;
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -71,37 +71,10 @@ 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({
|
||||
@@ -110,7 +83,6 @@ describe("getAutoUpdateDisabledReason", () => {
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: true,
|
||||
hasUpdateFeedConfig: true,
|
||||
}),
|
||||
).toContain("T3CODE_DISABLE_AUTO_UPDATE");
|
||||
});
|
||||
@@ -123,7 +95,6 @@ describe("getAutoUpdateDisabledReason", () => {
|
||||
platform: "linux",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
hasUpdateFeedConfig: true,
|
||||
}),
|
||||
).toContain("AppImage");
|
||||
});
|
||||
|
||||
@@ -34,11 +34,7 @@ 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.";
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
---
|
||||
import Layout from "../layouts/Layout.astro";
|
||||
import { RELEASES_URL } from "../lib/releases";
|
||||
---
|
||||
|
||||
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
|
||||
@@ -18,11 +17,11 @@ import { RELEASES_URL } from "../lib/releases";
|
||||
<h2 class="platform-name">macOS</h2>
|
||||
</div>
|
||||
<div class="download-cards">
|
||||
<a class="download-card" data-asset="arm64.dmg" href={RELEASES_URL}>
|
||||
<a class="download-card" data-asset="arm64.dmg" href="#">
|
||||
<span class="card-arch">Apple Silicon (arm64)</span>
|
||||
<span class="card-format">.dmg</span>
|
||||
</a>
|
||||
<a class="download-card" data-asset="x64.dmg" href={RELEASES_URL}>
|
||||
<a class="download-card" data-asset="x64.dmg" href="#">
|
||||
<span class="card-arch">Intel (x64)</span>
|
||||
<span class="card-format">.dmg</span>
|
||||
</a>
|
||||
@@ -36,7 +35,7 @@ import { RELEASES_URL } from "../lib/releases";
|
||||
<h2 class="platform-name">Windows</h2>
|
||||
</div>
|
||||
<div class="download-cards">
|
||||
<a class="download-card" data-asset="x64.exe" href={RELEASES_URL}>
|
||||
<a class="download-card" data-asset="x64.exe" href="#">
|
||||
<span class="card-arch">Windows 10, 11</span>
|
||||
<span class="card-format">.exe</span>
|
||||
</a>
|
||||
@@ -50,7 +49,7 @@ import { RELEASES_URL } from "../lib/releases";
|
||||
<h2 class="platform-name">Linux</h2>
|
||||
</div>
|
||||
<div class="download-cards">
|
||||
<a class="download-card" data-asset="x86_64.AppImage" href={RELEASES_URL}>
|
||||
<a class="download-card" data-asset="x86_64.AppImage" href="#">
|
||||
<span class="card-arch">x86_64</span>
|
||||
<span class="card-format">AppImage</span>
|
||||
</a>
|
||||
|
||||
@@ -26,7 +26,6 @@ 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";
|
||||
@@ -46,11 +45,10 @@ 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 { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
|
||||
import { RuntimeReceiptBusLive } 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";
|
||||
@@ -291,15 +289,14 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
);
|
||||
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
|
||||
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
projectionSnapshotQueryLayer,
|
||||
orchestrationLayer.pipe(Layer.provide(projectionSnapshotQueryLayer)),
|
||||
orchestrationLayer,
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
ProjectionCheckpointRepositoryLive,
|
||||
ProjectionPendingApprovalRepositoryLive,
|
||||
checkpointStoreLayer,
|
||||
providerLayer,
|
||||
RuntimeReceiptBusTest,
|
||||
RuntimeReceiptBusLive,
|
||||
);
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest();
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
@@ -322,22 +319,6 @@ 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),
|
||||
@@ -352,11 +333,8 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Layer.provideMerge(providerCommandReactorLayer),
|
||||
Layer.provideMerge(checkpointReactorLayer),
|
||||
);
|
||||
const layer = Layer.empty.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(orchestrationReactorLayer),
|
||||
const layer = orchestrationReactorLayer.pipe(
|
||||
Layer.provide(persistenceLayer),
|
||||
Layer.provideMerge(RepositoryIdentityResolverLive),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
@@ -395,7 +373,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
runtime.runPromise(reactor.start().pipe(Scope.provide(scope))),
|
||||
).pipe(Effect.orDie);
|
||||
const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
|
||||
yield* Stream.runForEach(runtimeReceiptBus.streamEventsForTest, (receipt) =>
|
||||
yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
|
||||
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
|
||||
).pipe(Effect.forkIn(scope));
|
||||
yield* Effect.sleep(10);
|
||||
|
||||
@@ -86,7 +86,6 @@ const collectEventsDuring = <A, E, R>(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
yield* Effect.sleep("50 millis");
|
||||
yield* action;
|
||||
|
||||
return yield* Effect.forEach(
|
||||
@@ -105,6 +104,7 @@ 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,7 +116,7 @@ const runTurn = (input: {
|
||||
);
|
||||
});
|
||||
|
||||
it.live("replays typed runtime fixture events", () =>
|
||||
it.effect("replays typed runtime fixture events", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
|
||||
@@ -149,7 +149,7 @@ it.live("replays typed runtime fixture events", () =>
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.live("replays file-changing fixture turn events", () =>
|
||||
it.effect("replays file-changing fixture turn events", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const { join } = yield* Path.Path;
|
||||
@@ -188,7 +188,7 @@ it.live("replays file-changing fixture turn events", () =>
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.live("runs multi-turn tool/approval flow", () =>
|
||||
it.effect("runs multi-turn tool/approval flow", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const { join } = yield* Path.Path;
|
||||
@@ -242,7 +242,7 @@ it.live("runs multi-turn tool/approval flow", () =>
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.live("rolls back provider conversation state only", () =>
|
||||
it.effect("rolls back provider conversation state only", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const { join } = yield* Path.Path;
|
||||
|
||||
+101
-102
@@ -122,35 +122,34 @@ const buildCmd = Command.make(
|
||||
{
|
||||
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
|
||||
},
|
||||
(config) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const serverDir = path.join(repoRoot, "apps/server");
|
||||
Effect.fn("buildCmd")(function* (config) {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const serverDir = path.join(repoRoot, "apps/server");
|
||||
|
||||
yield* Effect.log("[cli] Running tsdown...");
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
|
||||
shell: process.platform === "win32",
|
||||
})`bun tsdown`,
|
||||
);
|
||||
yield* Effect.log("[cli] Running tsdown...");
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
|
||||
shell: process.platform === "win32",
|
||||
})`bun tsdown`,
|
||||
);
|
||||
|
||||
const webDist = path.join(repoRoot, "apps/web/dist");
|
||||
const clientTarget = path.join(serverDir, "dist/client");
|
||||
const webDist = path.join(repoRoot, "apps/web/dist");
|
||||
const clientTarget = path.join(serverDir, "dist/client");
|
||||
|
||||
if (yield* fs.exists(webDist)) {
|
||||
yield* fs.copy(webDist, clientTarget);
|
||||
yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
|
||||
yield* Effect.log("[cli] Bundled web app into dist/client");
|
||||
} else {
|
||||
yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
|
||||
}
|
||||
}),
|
||||
if (yield* fs.exists(webDist)) {
|
||||
yield* fs.copy(webDist, clientTarget);
|
||||
yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
|
||||
yield* Effect.log("[cli] Bundled web app into dist/client");
|
||||
} else {
|
||||
yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
|
||||
}
|
||||
}),
|
||||
).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -167,87 +166,87 @@ const publishCmd = Command.make(
|
||||
dryRun: Flag.boolean("dry-run").pipe(Flag.withDefault(false)),
|
||||
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
|
||||
},
|
||||
(config) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const serverDir = path.join(repoRoot, "apps/server");
|
||||
const packageJsonPath = path.join(serverDir, "package.json");
|
||||
const backupPath = `${packageJsonPath}.bak`;
|
||||
Effect.fn("publishCmd")(function* (config) {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const serverDir = path.join(repoRoot, "apps/server");
|
||||
const packageJsonPath = path.join(serverDir, "package.json");
|
||||
const backupPath = `${packageJsonPath}.bak`;
|
||||
|
||||
// Assert build assets exist
|
||||
for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
|
||||
const abs = path.join(serverDir, relPath);
|
||||
if (!(yield* fs.exists(abs))) {
|
||||
return yield* new CliError({
|
||||
message: `Missing build asset: ${abs}. Run the build subcommand first.`,
|
||||
});
|
||||
}
|
||||
// Assert build assets exist
|
||||
for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
|
||||
const abs = path.join(serverDir, relPath);
|
||||
if (!(yield* fs.exists(abs))) {
|
||||
return yield* new CliError({
|
||||
message: `Missing build asset: ${abs}. Run the build subcommand first.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
yield* Effect.acquireUseRelease(
|
||||
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
|
||||
Effect.gen(function* () {
|
||||
// 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 = {
|
||||
name: serverPackageJson.name,
|
||||
repository: serverPackageJson.repository,
|
||||
bin: serverPackageJson.bin,
|
||||
type: serverPackageJson.type,
|
||||
version,
|
||||
engines: serverPackageJson.engines,
|
||||
files: serverPackageJson.files,
|
||||
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
|
||||
};
|
||||
yield* Effect.acquireUseRelease(
|
||||
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
|
||||
Effect.fn("publishCmd.acquire")(function* () {
|
||||
// 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 = {
|
||||
name: serverPackageJson.name,
|
||||
repository: serverPackageJson.repository,
|
||||
bin: serverPackageJson.bin,
|
||||
type: serverPackageJson.type,
|
||||
version,
|
||||
engines: serverPackageJson.engines,
|
||||
files: serverPackageJson.files,
|
||||
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
|
||||
};
|
||||
|
||||
pkg.dependencies = resolveCatalogDependencies(
|
||||
pkg.dependencies,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"apps/server dependencies",
|
||||
pkg.dependencies = resolveCatalogDependencies(
|
||||
pkg.dependencies,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"apps/server dependencies",
|
||||
);
|
||||
|
||||
const original = yield* fs.readFileString(packageJsonPath);
|
||||
yield* fs.writeFileString(backupPath, original);
|
||||
yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
|
||||
yield* Effect.log("[cli] Resolved package.json for publish");
|
||||
|
||||
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
|
||||
return { iconBackups };
|
||||
})(),
|
||||
// Use: npm publish
|
||||
() =>
|
||||
Effect.fn("publishCmd.use")(function* () {
|
||||
const args = ["publish", "--access", config.access, "--tag", config.tag];
|
||||
if (config.provenance) args.push("--provenance");
|
||||
if (config.dryRun) args.push("--dry-run");
|
||||
|
||||
yield* Effect.log(`[cli] Running: npm ${args.join(" ")}`);
|
||||
yield* runCommand(
|
||||
ChildProcess.make("npm", [...args], {
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
// Windows needs shell mode to resolve .cmd shims.
|
||||
shell: process.platform === "win32",
|
||||
}),
|
||||
);
|
||||
|
||||
const original = yield* fs.readFileString(packageJsonPath);
|
||||
yield* fs.writeFileString(backupPath, original);
|
||||
yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
|
||||
yield* Effect.log("[cli] Resolved package.json for publish");
|
||||
|
||||
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
|
||||
return { iconBackups };
|
||||
}),
|
||||
// Use: npm publish
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const args = ["publish", "--access", config.access, "--tag", config.tag];
|
||||
if (config.provenance) args.push("--provenance");
|
||||
if (config.dryRun) args.push("--dry-run");
|
||||
|
||||
yield* Effect.log(`[cli] Running: npm ${args.join(" ")}`);
|
||||
yield* runCommand(
|
||||
ChildProcess.make("npm", [...args], {
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
// Windows needs shell mode to resolve .cmd shims.
|
||||
shell: process.platform === "win32",
|
||||
}),
|
||||
);
|
||||
}),
|
||||
// Release: restore
|
||||
(resource: { readonly iconBackups: ReadonlyArray<PublishIconBackup> }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* restorePublishIconOverrides(resource.iconBackups).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logError(`[cli] Failed to restore publish icon overrides: ${String(error)}`),
|
||||
),
|
||||
);
|
||||
yield* fs.rename(backupPath, packageJsonPath);
|
||||
if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
|
||||
}),
|
||||
);
|
||||
}),
|
||||
})(),
|
||||
// Release: restore
|
||||
Effect.fn("publishCmd.release")(function* (resource: {
|
||||
readonly iconBackups: ReadonlyArray<PublishIconBackup>;
|
||||
}) {
|
||||
yield* restorePublishIconOverrides(resource.iconBackups).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logError(`[cli] Failed to restore publish icon overrides: ${String(error)}`),
|
||||
),
|
||||
);
|
||||
yield* fs.rename(backupPath, packageJsonPath);
|
||||
if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
|
||||
}),
|
||||
);
|
||||
}),
|
||||
).pipe(Command.withDescription("Publish the server package to npm."));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
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<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
||||
) =>
|
||||
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<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
||||
) =>
|
||||
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())),
|
||||
);
|
||||
});
|
||||
@@ -1,176 +0,0 @@
|
||||
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),
|
||||
);
|
||||
@@ -1,151 +0,0 @@
|
||||
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<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
||||
) =>
|
||||
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<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
||||
) =>
|
||||
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())),
|
||||
);
|
||||
});
|
||||
@@ -1,296 +0,0 @@
|
||||
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<string, StoredBootstrapGrant>());
|
||||
const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();
|
||||
|
||||
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<string, StoredBootstrapGrant>] => {
|
||||
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));
|
||||
@@ -1,182 +0,0 @@
|
||||
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<ServerConfigShape>) =>
|
||||
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<ServerConfigShape>) =>
|
||||
ServerAuthLive.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
Layer.provide(ServerSecretStoreLive),
|
||||
Layer.provide(makeServerConfigLayer(overrides)),
|
||||
);
|
||||
|
||||
const makeCookieRequest = (
|
||||
sessionToken: string,
|
||||
): Parameters<ServerAuthShape["authenticateHttpRequest"]>[0] =>
|
||||
({
|
||||
cookies: {
|
||||
t3_session: sessionToken,
|
||||
},
|
||||
headers: {},
|
||||
}) as unknown as Parameters<ServerAuthShape["authenticateHttpRequest"]>[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",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,385 +0,0 @@
|
||||
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 { 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<AuthenticatedSession, AuthError> =>
|
||||
sessions.verify(token).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,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
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),
|
||||
);
|
||||
@@ -1,111 +0,0 @@
|
||||
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<ServerConfigShape>) =>
|
||||
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"]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
mode: "desktop",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
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"]);
|
||||
}).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",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,41 +0,0 @@
|
||||
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 { SESSION_COOKIE_NAME } 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: SESSION_COOKIE_NAME,
|
||||
};
|
||||
|
||||
return {
|
||||
getDescriptor: () => Effect.succeed(descriptor),
|
||||
} satisfies ServerAuthPolicyShape;
|
||||
});
|
||||
|
||||
export const ServerAuthPolicyLive = Layer.effect(ServerAuthPolicy, makeServerAuthPolicy);
|
||||
@@ -1,263 +0,0 @@
|
||||
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<void>();
|
||||
|
||||
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())),
|
||||
);
|
||||
});
|
||||
@@ -1,151 +0,0 @@
|
||||
import * as Crypto from "node:crypto";
|
||||
|
||||
import { Effect, FileSystem, Layer, Path } 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 isMissingSecretFileError = (cause: unknown): cause is PlatformError.PlatformError =>
|
||||
cause instanceof PlatformError.PlatformError && cause.reason._tag === "NotFound";
|
||||
|
||||
const isAlreadyExistsSecretFileError = (cause: unknown): cause is PlatformError.PlatformError =>
|
||||
cause instanceof PlatformError.PlatformError && cause.reason._tag === "AlreadyExists";
|
||||
|
||||
const get: ServerSecretStoreShape["get"] = (name) =>
|
||||
fileSystem.readFile(resolveSecretPath(name)).pipe(
|
||||
Effect.map((bytes) => Uint8Array.from(bytes)),
|
||||
Effect.catch((cause) =>
|
||||
isMissingSecretFileError(cause)
|
||||
? 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) =>
|
||||
isAlreadyExistsSecretFileError(error.cause)
|
||||
? 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) =>
|
||||
isMissingSecretFileError(cause)
|
||||
? 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);
|
||||
@@ -1,191 +0,0 @@
|
||||
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<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
||||
) =>
|
||||
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<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
||||
) =>
|
||||
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()))),
|
||||
);
|
||||
});
|
||||
@@ -1,494 +0,0 @@
|
||||
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 { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts";
|
||||
import { AuthSessionRepository } from "../../persistence/Services/AuthSessions.ts";
|
||||
import { ServerSecretStore } from "../Services/ServerSecretStore.ts";
|
||||
import { SESSION_COOKIE_NAME } from "../utils.ts";
|
||||
import {
|
||||
SessionCredentialError,
|
||||
SessionCredentialService,
|
||||
type IssuedSession,
|
||||
type SessionCredentialChange,
|
||||
type SessionCredentialServiceShape,
|
||||
type VerifiedSession,
|
||||
} from "../Services/SessionCredentialService.ts";
|
||||
import {
|
||||
base64UrlDecodeUtf8,
|
||||
base64UrlEncode,
|
||||
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, "current">): AuthClientSession {
|
||||
return {
|
||||
...input,
|
||||
current: false,
|
||||
};
|
||||
}
|
||||
|
||||
export const makeSessionCredentialService = Effect.gen(function* () {
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
const authSessions = yield* AuthSessionRepository;
|
||||
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
|
||||
const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
|
||||
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
|
||||
|
||||
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<AuthClientSession>();
|
||||
}
|
||||
|
||||
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.makeUnsafe(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: SESSION_COOKIE_NAME,
|
||||
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));
|
||||
@@ -1,69 +0,0 @@
|
||||
import type {
|
||||
AuthClientMetadata,
|
||||
AuthClientSession,
|
||||
AuthPairingLink,
|
||||
AuthSessionId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, DateTime, Duration, Effect, ServiceMap } 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<IssuedPairingLink, AuthControlPlaneError>;
|
||||
readonly listPairingLinks: (input?: {
|
||||
readonly role?: SessionRole;
|
||||
readonly excludeSubjects?: ReadonlyArray<string>;
|
||||
}) => Effect.Effect<ReadonlyArray<AuthPairingLink>, AuthControlPlaneError>;
|
||||
readonly revokePairingLink: (id: string) => Effect.Effect<boolean, AuthControlPlaneError>;
|
||||
readonly issueSession: (input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
readonly subject?: string;
|
||||
readonly role?: SessionRole;
|
||||
readonly label?: string;
|
||||
}) => Effect.Effect<IssuedBearerSession, AuthControlPlaneError>;
|
||||
readonly listSessions: () => Effect.Effect<
|
||||
ReadonlyArray<AuthClientSession>,
|
||||
AuthControlPlaneError
|
||||
>;
|
||||
readonly revokeSession: (
|
||||
sessionId: AuthSessionId,
|
||||
) => Effect.Effect<boolean, AuthControlPlaneError>;
|
||||
readonly revokeOtherSessionsExcept: (
|
||||
sessionId: AuthSessionId,
|
||||
) => Effect.Effect<number, AuthControlPlaneError>;
|
||||
}
|
||||
|
||||
export class AuthControlPlane extends ServiceMap.Service<AuthControlPlane, AuthControlPlaneShape>()(
|
||||
"t3/AuthControlPlane",
|
||||
) {}
|
||||
@@ -1,57 +0,0 @@
|
||||
import type { AuthPairingLink, ServerAuthBootstrapMethod } from "@t3tools/contracts";
|
||||
import { Data, DateTime, Duration, ServiceMap } 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<IssuedBootstrapCredential, BootstrapCredentialError>;
|
||||
readonly listActive: () => Effect.Effect<
|
||||
ReadonlyArray<AuthPairingLink>,
|
||||
BootstrapCredentialError
|
||||
>;
|
||||
readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;
|
||||
readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialError>;
|
||||
readonly consume: (credential: string) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
|
||||
}
|
||||
|
||||
export class BootstrapCredentialService extends ServiceMap.Service<
|
||||
BootstrapCredentialService,
|
||||
BootstrapCredentialServiceShape
|
||||
>()("t3/auth/Services/BootstrapCredentialService") {}
|
||||
@@ -1,84 +0,0 @@
|
||||
import type {
|
||||
AuthBearerBootstrapResult,
|
||||
AuthBootstrapResult,
|
||||
AuthClientMetadata,
|
||||
AuthClientSession,
|
||||
AuthCreatePairingCredentialInput,
|
||||
AuthPairingLink,
|
||||
AuthPairingCredentialResult,
|
||||
AuthSessionId,
|
||||
AuthSessionState,
|
||||
ServerAuthDescriptor,
|
||||
ServerAuthSessionMethod,
|
||||
AuthWebSocketTokenResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, DateTime, ServiceMap } 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<ServerAuthDescriptor>;
|
||||
readonly getSessionState: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthSessionState, never>;
|
||||
readonly exchangeBootstrapCredential: (
|
||||
credential: string,
|
||||
requestMetadata: AuthClientMetadata,
|
||||
) => Effect.Effect<
|
||||
{
|
||||
readonly response: AuthBootstrapResult;
|
||||
readonly sessionToken: string;
|
||||
},
|
||||
AuthError
|
||||
>;
|
||||
readonly exchangeBootstrapCredentialForBearerSession: (
|
||||
credential: string,
|
||||
requestMetadata: AuthClientMetadata,
|
||||
) => Effect.Effect<AuthBearerBootstrapResult, AuthError>;
|
||||
readonly issuePairingCredential: (
|
||||
input?: AuthCreatePairingCredentialInput & {
|
||||
readonly role?: SessionRole;
|
||||
},
|
||||
) => Effect.Effect<AuthPairingCredentialResult, AuthError>;
|
||||
readonly listPairingLinks: () => Effect.Effect<ReadonlyArray<AuthPairingLink>, AuthError>;
|
||||
readonly revokePairingLink: (id: string) => Effect.Effect<boolean, AuthError>;
|
||||
readonly listClientSessions: (
|
||||
currentSessionId: AuthSessionId,
|
||||
) => Effect.Effect<ReadonlyArray<AuthClientSession>, AuthError>;
|
||||
readonly revokeClientSession: (
|
||||
currentSessionId: AuthSessionId,
|
||||
targetSessionId: AuthSessionId,
|
||||
) => Effect.Effect<boolean, AuthError>;
|
||||
readonly revokeOtherClientSessions: (
|
||||
currentSessionId: AuthSessionId,
|
||||
) => Effect.Effect<number, AuthError>;
|
||||
readonly authenticateHttpRequest: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthenticatedSession, AuthError>;
|
||||
readonly authenticateWebSocketUpgrade: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthenticatedSession, AuthError>;
|
||||
readonly issueWebSocketToken: (
|
||||
session: AuthenticatedSession,
|
||||
) => Effect.Effect<AuthWebSocketTokenResult, AuthError>;
|
||||
readonly issueStartupPairingUrl: (baseUrl: string) => Effect.Effect<string, AuthError>;
|
||||
}
|
||||
|
||||
export class ServerAuth extends ServiceMap.Service<ServerAuth, ServerAuthShape>()(
|
||||
"t3/auth/Services/ServerAuth",
|
||||
) {}
|
||||
@@ -1,11 +0,0 @@
|
||||
import type { ServerAuthDescriptor } from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export interface ServerAuthPolicyShape {
|
||||
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
|
||||
}
|
||||
|
||||
export class ServerAuthPolicy extends ServiceMap.Service<ServerAuthPolicy, ServerAuthPolicyShape>()(
|
||||
"t3/auth/Services/ServerAuthPolicy",
|
||||
) {}
|
||||
@@ -1,22 +0,0 @@
|
||||
import { Data, ServiceMap } 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<Uint8Array | null, SecretStoreError>;
|
||||
readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
|
||||
readonly getOrCreateRandom: (
|
||||
name: string,
|
||||
bytes: number,
|
||||
) => Effect.Effect<Uint8Array, SecretStoreError>;
|
||||
readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
|
||||
}
|
||||
|
||||
export class ServerSecretStore extends ServiceMap.Service<
|
||||
ServerSecretStore,
|
||||
ServerSecretStoreShape
|
||||
>()("t3/auth/Services/ServerSecretStore") {}
|
||||
@@ -1,87 +0,0 @@
|
||||
import type {
|
||||
AuthClientMetadata,
|
||||
AuthClientSession,
|
||||
AuthSessionId,
|
||||
ServerAuthSessionMethod,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, DateTime, Duration, ServiceMap } 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<IssuedSession, SessionCredentialError>;
|
||||
readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;
|
||||
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<VerifiedSession, SessionCredentialError>;
|
||||
readonly listActive: () => Effect.Effect<
|
||||
ReadonlyArray<AuthClientSession>,
|
||||
SessionCredentialError
|
||||
>;
|
||||
readonly streamChanges: Stream.Stream<SessionCredentialChange>;
|
||||
readonly revoke: (sessionId: AuthSessionId) => Effect.Effect<boolean, SessionCredentialError>;
|
||||
readonly revokeAllExcept: (
|
||||
sessionId: AuthSessionId,
|
||||
) => Effect.Effect<number, SessionCredentialError>;
|
||||
readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
|
||||
readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export class SessionCredentialService extends ServiceMap.Service<
|
||||
SessionCredentialService,
|
||||
SessionCredentialServiceShape
|
||||
>()("t3/auth/Services/SessionCredentialService") {}
|
||||
@@ -1,254 +0,0 @@
|
||||
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))),
|
||||
);
|
||||
@@ -1,26 +0,0 @@
|
||||
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",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,121 +0,0 @@
|
||||
import type { AuthClientMetadata, AuthClientMetadataDeviceType } from "@t3tools/contracts";
|
||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as Crypto from "node:crypto";
|
||||
|
||||
export const SESSION_COOKIE_NAME = "t3_session";
|
||||
|
||||
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 } : {}),
|
||||
};
|
||||
}
|
||||
@@ -1,38 +1,83 @@
|
||||
import { CheckpointRef, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
import {
|
||||
CheckpointRef,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
ProjectionSnapshotQuery,
|
||||
type ProjectionThreadCheckpointContext,
|
||||
} from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { ProjectionSnapshotQuery } 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 makeThreadCheckpointContext(input: {
|
||||
function makeSnapshot(input: {
|
||||
readonly projectId: ProjectId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly workspaceRoot: string;
|
||||
readonly worktreePath: string | null;
|
||||
readonly checkpointTurnCount: number;
|
||||
readonly checkpointRef: CheckpointRef;
|
||||
}): ProjectionThreadCheckpointContext {
|
||||
}): OrchestrationReadModel {
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
projectId: input.projectId,
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
worktreePath: input.worktreePath,
|
||||
checkpoints: [
|
||||
snapshotSequence: 0,
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
projects: [
|
||||
{
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
checkpointTurnCount: input.checkpointTurnCount,
|
||||
checkpointRef: input.checkpointRef,
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: null,
|
||||
completedAt: "2026-01-01T00:00:00.000Z",
|
||||
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,
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -50,7 +95,7 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
readonly cwd: string;
|
||||
}> = [];
|
||||
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
const snapshot = makeSnapshot({
|
||||
projectId,
|
||||
threadId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
@@ -80,12 +125,7 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
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)),
|
||||
getSnapshot: () => Effect.succeed(snapshot),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -135,11 +175,12 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
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.none()),
|
||||
Effect.succeed({
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [],
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
} satisfies OrchestrationReadModel),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -4,11 +4,11 @@ import {
|
||||
type OrchestrationGetFullThreadDiffResult,
|
||||
type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, Option, Schema } from "effect";
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { CheckpointInvariantError, CheckpointUnavailableError } from "../Errors.ts";
|
||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||
import { checkpointRefForThreadTurn, resolveThreadWorkspaceCwd } from "../Utils.ts";
|
||||
import { CheckpointStore } from "../Services/CheckpointStore.ts";
|
||||
import {
|
||||
CheckpointDiffQuery,
|
||||
@@ -41,17 +41,16 @@ const make = Effect.gen(function* () {
|
||||
return emptyDiff;
|
||||
}
|
||||
|
||||
const threadContext = yield* projectionSnapshotQuery.getThreadCheckpointContext(
|
||||
input.threadId,
|
||||
);
|
||||
if (Option.isNone(threadContext)) {
|
||||
const snapshot = yield* projectionSnapshotQuery.getSnapshot();
|
||||
const thread = snapshot.threads.find((entry) => entry.id === input.threadId);
|
||||
if (!thread) {
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
detail: `Thread '${input.threadId}' not found.`,
|
||||
});
|
||||
}
|
||||
|
||||
const maxTurnCount = threadContext.value.checkpoints.reduce(
|
||||
const maxTurnCount = thread.checkpoints.reduce(
|
||||
(max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),
|
||||
0,
|
||||
);
|
||||
@@ -63,7 +62,10 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
|
||||
const workspaceCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: snapshot.projects,
|
||||
});
|
||||
if (!workspaceCwd) {
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
@@ -74,7 +76,7 @@ const make = Effect.gen(function* () {
|
||||
const fromCheckpointRef =
|
||||
input.fromTurnCount === 0
|
||||
? checkpointRefForThreadTurn(input.threadId, 0)
|
||||
: threadContext.value.checkpoints.find(
|
||||
: thread.checkpoints.find(
|
||||
(checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,
|
||||
)?.checkpointRef;
|
||||
if (!fromCheckpointRef) {
|
||||
@@ -85,7 +87,7 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const toCheckpointRef = threadContext.value.checkpoints.find(
|
||||
const toCheckpointRef = thread.checkpoints.find(
|
||||
(checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,
|
||||
)?.checkpointRef;
|
||||
if (!toCheckpointRef) {
|
||||
|
||||
@@ -80,7 +80,7 @@ function initRepoWithCommit(
|
||||
});
|
||||
}
|
||||
|
||||
function buildLargeText(lineCount = 5_000): string {
|
||||
function buildLargeText(lineCount = 20_000): string {
|
||||
return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`)
|
||||
.join("\n")
|
||||
.concat("\n");
|
||||
@@ -115,7 +115,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
|
||||
|
||||
expect(diff).toContain("diff --git");
|
||||
expect(diff).not.toContain("[truncated]");
|
||||
expect(diff).toContain("+line 04999");
|
||||
expect(diff).toContain("+line 19999");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -9,18 +9,6 @@ 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<string, unknown>) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
||||
@@ -40,9 +28,9 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
port: Option.none(),
|
||||
host: Option.none(),
|
||||
baseDir: Option.none(),
|
||||
cwd: Option.none(),
|
||||
devUrl: Option.none(),
|
||||
noBrowser: Option.none(),
|
||||
authToken: Option.none(),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
@@ -61,6 +49,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
T3CODE_HOME: baseDir,
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
T3CODE_AUTH_TOKEN: "env-token",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
|
||||
T3CODE_LOG_WS_EVENTS: "true",
|
||||
},
|
||||
@@ -73,7 +62,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Warn",
|
||||
...defaultObservabilityConfig,
|
||||
mode: "desktop",
|
||||
port: 4001,
|
||||
cwd: process.cwd(),
|
||||
@@ -83,8 +71,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
staticDir: undefined,
|
||||
devUrl: new URL("http://127.0.0.1:5173"),
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
authToken: "env-token",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
@@ -102,9 +89,9 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
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),
|
||||
authToken: Option.some("flag-token"),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.some(true),
|
||||
logWebSocketEvents: Option.some(true),
|
||||
@@ -123,6 +110,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
T3CODE_HOME: join(os.tmpdir(), "ignored-base"),
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||
T3CODE_NO_BROWSER: "false",
|
||||
T3CODE_AUTH_TOKEN: "ignored-token",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
|
||||
T3CODE_LOG_WS_EVENTS: "false",
|
||||
},
|
||||
@@ -135,7 +123,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Debug",
|
||||
...defaultObservabilityConfig,
|
||||
mode: "web",
|
||||
port: 8788,
|
||||
cwd: process.cwd(),
|
||||
@@ -145,8 +132,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
staticDir: undefined,
|
||||
devUrl: new URL("http://127.0.0.1:4173"),
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
authToken: "flag-token",
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
@@ -164,10 +150,9 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
t3Home: baseDir,
|
||||
devUrl: "http://127.0.0.1:5173",
|
||||
noBrowser: true,
|
||||
authToken: "bootstrap-token",
|
||||
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"));
|
||||
|
||||
@@ -177,9 +162,9 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
port: Option.none(),
|
||||
host: Option.none(),
|
||||
baseDir: Option.none(),
|
||||
cwd: Option.none(),
|
||||
devUrl: Option.none(),
|
||||
noBrowser: Option.none(),
|
||||
authToken: Option.none(),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
@@ -202,9 +187,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
|
||||
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(),
|
||||
@@ -214,8 +196,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
staticDir: undefined,
|
||||
devUrl: new URL("http://127.0.0.1:5173"),
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
authToken: "bootstrap-token",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
@@ -228,7 +209,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
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(
|
||||
{
|
||||
@@ -236,9 +216,9 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
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(),
|
||||
authToken: Option.none(),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
@@ -254,7 +234,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
);
|
||||
|
||||
for (const directory of [
|
||||
customCwd,
|
||||
resolved.stateDir,
|
||||
resolved.logsDir,
|
||||
resolved.providerLogsDir,
|
||||
@@ -262,11 +241,9 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
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));
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -281,6 +258,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
t3Home: "/tmp/t3-bootstrap-home",
|
||||
devUrl: "http://127.0.0.1:5173",
|
||||
noBrowser: false,
|
||||
authToken: "bootstrap-token",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
});
|
||||
@@ -292,9 +270,9 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
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(),
|
||||
authToken: Option.some("flag-token"),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
@@ -322,7 +300,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Debug",
|
||||
...defaultObservabilityConfig,
|
||||
mode: "web",
|
||||
port: 8788,
|
||||
cwd: process.cwd(),
|
||||
@@ -332,134 +309,10 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
staticDir: undefined,
|
||||
devUrl: new URL("http://127.0.0.1:4173"),
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
authToken: "flag-token",
|
||||
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,
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
+7
-322
@@ -1,160 +1,28 @@
|
||||
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<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
|
||||
const runCliWithRuntime = (args: ReadonlyArray<string>) =>
|
||||
runCli(args).pipe(Effect.provide(CliRuntimeLayer));
|
||||
|
||||
const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
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 = <A, E, R>(baseDir: string, run: () => Effect.Effect<A, E, R>) =>
|
||||
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"]),
|
||||
Command.runWith(cli, { version: "0.0.0" })(["--log-level", "debug", "--version"]).pipe(
|
||||
Effect.provide(CliRuntimeLayer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects invalid log-level casing before launching the server", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(Effect.flip);
|
||||
const error = yield* Command.runWith(cli, { version: "0.0.0" })([
|
||||
"--log-level",
|
||||
"Debug",
|
||||
]).pipe(Effect.provide(CliRuntimeLayer), Effect.flip);
|
||||
|
||||
if (!CliError.isCliError(error)) {
|
||||
assert.fail(`Expected CliError, got ${String(error)}`);
|
||||
@@ -166,187 +34,4 @@ it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
|
||||
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");
|
||||
}),
|
||||
);
|
||||
});
|
||||
+62
-933
File diff suppressed because it is too large.
Load diff
@@ -1,88 +0,0 @@
|
||||
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");
|
||||
});
|
||||
@@ -1,190 +0,0 @@
|
||||
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<string | null | undefined>) {
|
||||
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<AuthPairingLink>,
|
||||
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<AuthClientSession>,
|
||||
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
|
||||
);
|
||||
}
|
||||
@@ -290,26 +290,20 @@ In Default mode, strongly prefer making reasonable assumptions and executing the
|
||||
</collaboration_mode>`;
|
||||
|
||||
function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
|
||||
readonly approvalPolicy: "untrusted" | "on-request" | "never";
|
||||
readonly sandbox: "read-only" | "workspace-write" | "danger-full-access";
|
||||
readonly approvalPolicy: "on-request" | "never";
|
||||
readonly sandbox: "workspace-write" | "danger-full-access";
|
||||
} {
|
||||
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",
|
||||
};
|
||||
if (runtimeMode === "approval-required") {
|
||||
return {
|
||||
approvalPolicy: "on-request",
|
||||
sandbox: "workspace-write",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
approvalPolicy: "never",
|
||||
sandbox: "danger-full-access",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -13,9 +13,6 @@ export const DEFAULT_PORT = 3773;
|
||||
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.
|
||||
*/
|
||||
@@ -28,14 +25,10 @@ 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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -43,15 +36,6 @@ export interface ServerDerivedPaths {
|
||||
*/
|
||||
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;
|
||||
@@ -60,8 +44,7 @@ export interface ServerConfigShape extends ServerDerivedPaths {
|
||||
readonly staticDir: string | undefined;
|
||||
readonly devUrl: URL | undefined;
|
||||
readonly noBrowser: boolean;
|
||||
readonly startupPresentation: StartupPresentation;
|
||||
readonly desktopBootstrapToken: string | undefined;
|
||||
readonly authToken: string | undefined;
|
||||
readonly autoBootstrapProjectFromCwd: boolean;
|
||||
readonly logWebSocketEvents: boolean;
|
||||
}
|
||||
@@ -85,14 +68,10 @@ 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"),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -111,7 +90,6 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server
|
||||
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" },
|
||||
);
|
||||
@@ -139,15 +117,6 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS
|
||||
|
||||
return {
|
||||
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,
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
@@ -156,11 +125,10 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS
|
||||
logWebSocketEvents: false,
|
||||
port: 0,
|
||||
host: undefined,
|
||||
desktopBootstrapToken: undefined,
|
||||
authToken: undefined,
|
||||
staticDir: undefined,
|
||||
devUrl,
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
} satisfies ServerConfigShape;
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
import * as nodePath from "node:path";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Effect, Exit, FileSystem, Layer, PlatformError } from "effect";
|
||||
|
||||
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "../../config.ts";
|
||||
import { ServerEnvironment } from "../Services/ServerEnvironment.ts";
|
||||
import { ServerEnvironmentLive } from "./ServerEnvironment.ts";
|
||||
|
||||
const makeServerEnvironmentLayer = (baseDir: string) =>
|
||||
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",
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,92 +0,0 @@
|
||||
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.makeUnsafe(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());
|
||||
@@ -1,150 +0,0 @@
|
||||
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");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,104 +0,0 @@
|
||||
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(() =>
|
||||
runProcess(command, args, {
|
||||
allowNonZeroExit: true,
|
||||
}),
|
||||
).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";
|
||||
});
|
||||
@@ -1,13 +0,0 @@
|
||||
import type { EnvironmentId, ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export interface ServerEnvironmentShape {
|
||||
readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
|
||||
readonly getDescriptor: Effect.Effect<ExecutionEnvironmentDescriptor>;
|
||||
}
|
||||
|
||||
export class ServerEnvironment extends ServiceMap.Service<
|
||||
ServerEnvironment,
|
||||
ServerEnvironmentShape
|
||||
>()("t3/environment/Services/ServerEnvironment") {}
|
||||
@@ -85,43 +85,44 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
||||
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
|
||||
const materializeImageAttachments = (
|
||||
_operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle",
|
||||
attachments: BranchNameGenerationInput["attachments"],
|
||||
): Effect.fn.Return<MaterializedImageAttachments, TextGenerationError> {
|
||||
if (!attachments || attachments.length === 0) {
|
||||
return { imagePaths: [] };
|
||||
}
|
||||
|
||||
const imagePaths: string[] = [];
|
||||
for (const attachment of attachments) {
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
): Effect.Effect<MaterializedImageAttachments, TextGenerationError> =>
|
||||
Effect.gen(function* () {
|
||||
if (!attachments || attachments.length === 0) {
|
||||
return { imagePaths: [] };
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
return { imagePaths };
|
||||
});
|
||||
const imagePaths: string[] = [];
|
||||
for (const attachment of attachments) {
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
|
||||
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);
|
||||
}
|
||||
return { imagePaths };
|
||||
});
|
||||
|
||||
const runCodexJson = <S extends Schema.Top>({
|
||||
operation,
|
||||
cwd,
|
||||
prompt,
|
||||
@@ -141,138 +142,139 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
imagePaths?: ReadonlyArray<string>;
|
||||
cleanupPaths?: ReadonlyArray<string>;
|
||||
modelSelection: CodexModelSelection;
|
||||
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
||||
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,
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const schemaPath = yield* writeTempFile(
|
||||
operation,
|
||||
"codex-schema",
|
||||
JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
|
||||
);
|
||||
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]),
|
||||
"-",
|
||||
],
|
||||
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)),
|
||||
{
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
|
||||
},
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdin: {
|
||||
stream: Stream.encodeText(Stream.make(prompt)),
|
||||
},
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
);
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
const child = yield* commandSpawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
|
||||
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 [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"),
|
||||
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,
|
||||
}),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ 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}.`,
|
||||
});
|
||||
}
|
||||
);
|
||||
}).pipe(Effect.ensuring(cleanup));
|
||||
});
|
||||
|
||||
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,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.ensuring(cleanup));
|
||||
});
|
||||
|
||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
|
||||
"CodexTextGeneration.generateCommitMessage",
|
||||
)(function* (input) {
|
||||
|
||||
@@ -59,23 +59,6 @@ function git(
|
||||
});
|
||||
}
|
||||
|
||||
function configureRemote(
|
||||
cwd: string,
|
||||
remoteName: string,
|
||||
remotePath: string,
|
||||
fetchNamespace: string,
|
||||
): Effect.Effect<string, GitCommandError, GitCore> {
|
||||
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;
|
||||
@@ -386,36 +369,6 @@ 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();
|
||||
@@ -561,41 +514,6 @@ 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 ──
|
||||
@@ -669,7 +587,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("statusDetails remains successful when upstream refresh fails after checkout", () =>
|
||||
it.effect("keeps checkout successful when upstream refresh fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
@@ -694,7 +612,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
const realGitCore = yield* GitCore;
|
||||
let refreshFetchAttempts = 0;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
if (input.args[0] === "fetch") {
|
||||
refreshFetchAttempts += 1;
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
@@ -708,15 +626,16 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
return realGitCore.execute(input);
|
||||
});
|
||||
yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
|
||||
const status = yield* core.statusDetails(source);
|
||||
expect(refreshFetchAttempts).toBe(1);
|
||||
expect(status.branch).toBe(featureBranch);
|
||||
expect(status.upstreamRef).toBe(`origin/${featureBranch}`);
|
||||
yield* Effect.promise(() =>
|
||||
vi.waitFor(() => {
|
||||
expect(refreshFetchAttempts).toBe(1);
|
||||
}),
|
||||
);
|
||||
expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("defers upstream refresh until statusDetails is requested", () =>
|
||||
it.effect("refresh fetch is scoped to the checked out branch upstream refspec", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
@@ -738,10 +657,10 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
yield* git(source, ["checkout", defaultBranch]);
|
||||
|
||||
const realGitCore = yield* GitCore;
|
||||
let refreshFetchAttempts = 0;
|
||||
let fetchArgs: readonly string[] | null = null;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
refreshFetchAttempts += 1;
|
||||
if (input.args[0] === "fetch") {
|
||||
fetchArgs = [...input.args];
|
||||
return Effect.succeed({
|
||||
code: 0,
|
||||
stdout: "",
|
||||
@@ -753,137 +672,73 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
return realGitCore.execute(input);
|
||||
});
|
||||
yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
|
||||
yield* Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, 50)));
|
||||
expect(refreshFetchAttempts).toBe(0);
|
||||
const status = yield* core.statusDetails(source);
|
||||
expect(status.branch).toBe(featureBranch);
|
||||
expect(refreshFetchAttempts).toBe(1);
|
||||
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}`,
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("shares upstream refreshes across worktrees that use the same git common dir", () =>
|
||||
it.effect("returns checkout result before background upstream refresh completes", () =>
|
||||
Effect.gen(function* () {
|
||||
const ok = (stdout = "") =>
|
||||
Effect.succeed({
|
||||
code: 0,
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
|
||||
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;
|
||||
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* 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<void>((resolve) => {
|
||||
releaseFetch = resolve;
|
||||
});
|
||||
|
||||
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",
|
||||
}),
|
||||
if (input.args[0] === "fetch") {
|
||||
fetchStarted = true;
|
||||
return Effect.promise(() =>
|
||||
waitForReleasePromise.then(() => ({
|
||||
code: 0,
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
})),
|
||||
);
|
||||
}
|
||||
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.",
|
||||
}),
|
||||
);
|
||||
return realGitCore.execute(input);
|
||||
});
|
||||
|
||||
yield* core.statusDetails("/repo/worktrees/main");
|
||||
yield* core.statusDetails("/repo/worktrees/pr-123");
|
||||
expect(fetchCount).toBe(1);
|
||||
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();
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -924,21 +779,16 @@ 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* configureRemote(source, prefixRemoteName, prefixRemote, prefixFetchNamespace);
|
||||
yield* configureRemote(source, remoteName, remote, remoteName);
|
||||
yield* git(source, ["remote", "add", remoteName, remote]);
|
||||
yield* git(source, ["push", "-u", remoteName, defaultBranch]);
|
||||
|
||||
yield* git(source, ["checkout", "-b", featureBranch]);
|
||||
@@ -949,41 +799,12 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
yield* git(source, ["checkout", defaultBranch]);
|
||||
yield* git(source, ["branch", "-D", featureBranch]);
|
||||
|
||||
const checkoutResult = yield* (yield* GitCore).checkoutBranch({
|
||||
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}`,
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1870,47 +1691,6 @@ 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();
|
||||
|
||||
@@ -18,10 +18,7 @@ import {
|
||||
} from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
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 { GitCommandError } from "@t3tools/contracts";
|
||||
import {
|
||||
GitCore,
|
||||
type ExecuteGitProgress,
|
||||
@@ -30,11 +27,6 @@ import {
|
||||
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";
|
||||
|
||||
@@ -49,10 +41,8 @@ const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
|
||||
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
|
||||
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
|
||||
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
|
||||
const STATUS_UPSTREAM_REFRESH_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;
|
||||
|
||||
type TraceTailState = {
|
||||
processedChars: number;
|
||||
@@ -60,7 +50,7 @@ type TraceTailState = {
|
||||
};
|
||||
|
||||
class StatusUpstreamRefreshCacheKey extends Data.Class<{
|
||||
gitCommonDir: string;
|
||||
cwd: string;
|
||||
upstreamRef: string;
|
||||
remoteName: string;
|
||||
upstreamBranch: string;
|
||||
@@ -187,38 +177,12 @@ function parseBranchLine(line: string): { name: string; current: boolean } | nul
|
||||
};
|
||||
}
|
||||
|
||||
function filterBranchesForListQuery(
|
||||
branches: ReadonlyArray<GitBranch>,
|
||||
query?: string,
|
||||
): ReadonlyArray<GitBranch> {
|
||||
if (!query) {
|
||||
return branches;
|
||||
}
|
||||
|
||||
const normalizedQuery = query.toLowerCase();
|
||||
return branches.filter((branch) => branch.name.toLowerCase().includes(normalizedQuery));
|
||||
}
|
||||
|
||||
function paginateBranches(input: {
|
||||
branches: ReadonlyArray<GitBranch>;
|
||||
cursor?: number | undefined;
|
||||
limit?: number | undefined;
|
||||
}): {
|
||||
branches: ReadonlyArray<GitBranch>;
|
||||
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 parseRemoteNames(stdout: string): ReadonlyArray<string> {
|
||||
return stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.toSorted((a, b) => b.length - a.length);
|
||||
}
|
||||
|
||||
function sanitizeRemoteName(value: string): string {
|
||||
@@ -253,41 +217,30 @@ function parseRemoteFetchUrls(stdout: string): Map<string, string> {
|
||||
return remotes;
|
||||
}
|
||||
|
||||
function parseUpstreamRefWithRemoteNames(
|
||||
upstreamRef: string,
|
||||
function parseRemoteRefWithRemoteNames(
|
||||
branchName: string,
|
||||
remoteNames: ReadonlyArray<string>,
|
||||
): { upstreamRef: string; remoteName: string; upstreamBranch: string } | null {
|
||||
const parsed = parseRemoteRefWithRemoteNames(upstreamRef, remoteNames);
|
||||
if (!parsed) {
|
||||
return null;
|
||||
): { 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,
|
||||
};
|
||||
}
|
||||
|
||||
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,
|
||||
};
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null {
|
||||
@@ -374,18 +327,6 @@ interface Trace2Monitor {
|
||||
readonly flush: Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
const nowUnixNano = (): bigint => BigInt(Date.now()) * 1_000_000n;
|
||||
|
||||
const addCurrentSpanEvent = (name: string, attributes: Record<string, unknown>) =>
|
||||
Effect.currentSpan.pipe(
|
||||
Effect.tap((span) =>
|
||||
Effect.sync(() => {
|
||||
span.event(name, nowUnixNano(), compactTraceAttributes(attributes));
|
||||
}),
|
||||
),
|
||||
Effect.catch(() => Effect.void),
|
||||
);
|
||||
|
||||
function trace2ChildKey(record: Record<string, unknown>): string | null {
|
||||
const childId = record.child_id;
|
||||
if (typeof childId === "number" || typeof childId === "string") {
|
||||
@@ -458,9 +399,6 @@ 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);
|
||||
}
|
||||
@@ -469,19 +407,12 @@ 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,
|
||||
durationMs,
|
||||
exitCode: typeof code === "number" && Number.isInteger(code) ? code : null,
|
||||
durationMs: started ? Math.max(0, Date.now() - started.startedAtMs) : null,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -633,13 +564,13 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
const path = yield* Path.Path;
|
||||
const { worktreesDir } = yield* ServerConfig;
|
||||
|
||||
let executeRaw: GitCoreShape["execute"];
|
||||
let execute: GitCoreShape["execute"];
|
||||
|
||||
if (options?.executeOverride) {
|
||||
executeRaw = options.executeOverride;
|
||||
execute = options.executeOverride;
|
||||
} else {
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
executeRaw = Effect.fnUntraced(function* (input) {
|
||||
execute = Effect.fnUntraced(function* (input) {
|
||||
const commandInput = {
|
||||
...input,
|
||||
args: [...input.args],
|
||||
@@ -740,25 +671,6 @@ 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,
|
||||
@@ -880,27 +792,45 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
return null;
|
||||
}
|
||||
|
||||
const remoteNames = yield* runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe(
|
||||
Effect.map(parseRemoteNames),
|
||||
Effect.catch(() => Effect.succeed<ReadonlyArray<string>>([])),
|
||||
);
|
||||
return (
|
||||
parseUpstreamRefWithRemoteNames(upstreamRef, remoteNames) ??
|
||||
parseUpstreamRefByFirstSeparator(upstreamRef)
|
||||
);
|
||||
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 fetchUpstreamRefForStatus = (
|
||||
gitCommonDir: string,
|
||||
const fetchUpstreamRef = (
|
||||
cwd: string,
|
||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
||||
): Effect.Effect<void, GitCommandError> => {
|
||||
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
|
||||
return runGit(
|
||||
"GitCore.fetchUpstreamRef",
|
||||
cwd,
|
||||
["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
|
||||
true,
|
||||
);
|
||||
};
|
||||
|
||||
const fetchUpstreamRefForStatus = (
|
||||
cwd: string,
|
||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
||||
): Effect.Effect<void, GitCommandError> => {
|
||||
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
|
||||
const fetchCwd =
|
||||
path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
|
||||
return executeGit(
|
||||
"GitCore.fetchUpstreamRefForStatus",
|
||||
fetchCwd,
|
||||
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
|
||||
cwd,
|
||||
["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
|
||||
@@ -908,18 +838,10 @@ 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.gitCommonDir, {
|
||||
yield* fetchUpstreamRefForStatus(cacheKey.cwd, {
|
||||
upstreamRef: cacheKey.upstreamRef,
|
||||
remoteName: cacheKey.remoteName,
|
||||
upstreamBranch: cacheKey.upstreamBranch,
|
||||
@@ -930,11 +852,8 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
const statusUpstreamRefreshCache = yield* Cache.makeWith({
|
||||
capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
|
||||
lookup: refreshStatusUpstreamCacheEntry,
|
||||
// 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,
|
||||
// Keep successful refreshes warm; drop failures immediately so next request can retry.
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_UPSTREAM_REFRESH_INTERVAL : Duration.zero),
|
||||
});
|
||||
|
||||
const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* (
|
||||
@@ -942,11 +861,10 @@ 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({
|
||||
gitCommonDir,
|
||||
cwd,
|
||||
upstreamRef: upstream.upstreamRef,
|
||||
remoteName: upstream.remoteName,
|
||||
upstreamBranch: upstream.upstreamBranch,
|
||||
@@ -954,6 +872,14 @@ 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,
|
||||
@@ -993,7 +919,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
|
||||
const listRemoteNames = (cwd: string): Effect.Effect<ReadonlyArray<string>, GitCommandError> =>
|
||||
runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe(
|
||||
Effect.map(parseRemoteNamesInGitOrder),
|
||||
Effect.map((stdout) => parseRemoteNames(stdout).toReversed()),
|
||||
);
|
||||
|
||||
const resolvePrimaryRemoteName = Effect.fn("resolvePrimaryRemoteName")(function* (cwd: string) {
|
||||
@@ -1177,53 +1103,18 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
return branchLastCommit;
|
||||
});
|
||||
|
||||
const readStatusDetailsLocal = Effect.fn("readStatusDetailsLocal")(function* (cwd: string) {
|
||||
const statusResult = yield* executeGit(
|
||||
"GitCore.statusDetails.status",
|
||||
cwd,
|
||||
["status", "--porcelain=2", "--branch"],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) {
|
||||
yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true }));
|
||||
|
||||
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all(
|
||||
[
|
||||
runGitStdout("GitCore.statusDetails.status", cwd, ["status", "--porcelain=2", "--branch"]),
|
||||
runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]),
|
||||
runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, ["diff", "--cached", "--numstat"]),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
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;
|
||||
let aheadCount = 0;
|
||||
@@ -1290,12 +1181,6 @@ 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,
|
||||
@@ -1310,23 +1195,9 @@ 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.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,
|
||||
@@ -1475,7 +1346,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
"push",
|
||||
"-u",
|
||||
publishRemoteName,
|
||||
`HEAD:refs/heads/${branch}`,
|
||||
branch,
|
||||
]);
|
||||
return {
|
||||
status: "pushed" as const,
|
||||
@@ -1705,13 +1576,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
if (localBranchResult.code !== 0) {
|
||||
const stderr = localBranchResult.stderr.trim();
|
||||
if (stderr.toLowerCase().includes("not a git repository")) {
|
||||
return {
|
||||
branches: [],
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
nextCursor: null,
|
||||
totalCount: 0,
|
||||
};
|
||||
return { branches: [], isRepo: false, hasOriginRemote: false };
|
||||
}
|
||||
return yield* createGitCommandError(
|
||||
"GitCore.listBranches",
|
||||
@@ -1875,22 +1740,9 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
})
|
||||
: [];
|
||||
|
||||
const branches = paginateBranches({
|
||||
branches: filterBranchesForListQuery(
|
||||
dedupeRemoteBranchesWithLocalMatches([...localBranches, ...remoteBranches]),
|
||||
input.query,
|
||||
),
|
||||
cursor: input.cursor,
|
||||
limit: input.limit,
|
||||
});
|
||||
const branches = [...localBranches, ...remoteBranches];
|
||||
|
||||
return {
|
||||
branches: [...branches.branches],
|
||||
isRepo: true,
|
||||
hasOriginRemote: remoteNames.includes("origin"),
|
||||
nextCursor: branches.nextCursor,
|
||||
totalCount: branches.totalCount,
|
||||
};
|
||||
return { branches, isRepo: true, hasOriginRemote: remoteNames.includes("origin") };
|
||||
});
|
||||
|
||||
const createWorktree: GitCoreShape["createWorktree"] = Effect.fn("createWorktree")(
|
||||
@@ -2009,6 +1861,12 @@ 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(
|
||||
@@ -2082,27 +1940,14 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
fallbackErrorMessage: "git checkout failed",
|
||||
});
|
||||
|
||||
const branch = yield* runGitStdout("GitCore.checkoutBranch.currentBranch", input.cwd, [
|
||||
"branch",
|
||||
"--show-current",
|
||||
]).pipe(Effect.map((stdout) => stdout.trim() || null));
|
||||
|
||||
return { branch };
|
||||
// Refresh upstream refs in the background so checkout remains responsive.
|
||||
yield* refreshCheckedOutBranchUpstream(input.cwd).pipe(
|
||||
Effect.ignoreCause({ log: true }),
|
||||
Effect.forkDetach({ startImmediately: true }),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
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,
|
||||
@@ -2128,7 +1973,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
execute,
|
||||
status,
|
||||
statusDetails,
|
||||
statusDetailsLocal,
|
||||
prepareCommitContext,
|
||||
commit,
|
||||
pushCurrentBranch,
|
||||
|
||||
@@ -168,7 +168,6 @@ const makeGitHubCli = Effect.sync(() => {
|
||||
runProcess("gh", input.args, {
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
shell: false,
|
||||
}),
|
||||
catch: (error) => normalizeGitHubCliError("execute", error),
|
||||
});
|
||||
@@ -188,7 +187,7 @@ const makeGitHubCli = Effect.sync(() => {
|
||||
"--limit",
|
||||
String(input.limit ?? 1),
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
||||
"number,title,url,baseRefName,headRefName",
|
||||
],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,312 +0,0 @@
|
||||
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<GitStatusStreamEvent>();
|
||||
const remoteUpdatedDeferred = yield* Deferred.make<GitStatusStreamEvent>();
|
||||
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<void, never> | null = null;
|
||||
let remoteStartedDeferred: Deferred.Deferred<void, never> | 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<GitStatusRemoteResult | null, never>),
|
||||
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<void>();
|
||||
const remoteStarted = yield* Deferred.make<void>();
|
||||
remoteInterruptedDeferred = remoteInterrupted;
|
||||
remoteStartedDeferred = remoteStarted;
|
||||
|
||||
const broadcaster = yield* GitStatusBroadcaster;
|
||||
const firstSnapshot = yield* Deferred.make<GitStatusStreamEvent>();
|
||||
const secondSnapshot = yield* Deferred.make<GitStatusStreamEvent>();
|
||||
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));
|
||||
});
|
||||
});
|
||||
@@ -1,311 +0,0 @@
|
||||
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<T> {
|
||||
readonly fingerprint: string;
|
||||
readonly value: T;
|
||||
}
|
||||
|
||||
interface CachedGitStatus {
|
||||
readonly local: CachedValue<GitStatusLocalResult> | null;
|
||||
readonly remote: CachedValue<GitStatusRemoteResult | null> | null;
|
||||
}
|
||||
|
||||
interface ActiveRemotePoller {
|
||||
readonly fiber: Fiber.Fiber<void, never>;
|
||||
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<GitStatusChange>(),
|
||||
(pubsub) => PubSub.shutdown(pubsub),
|
||||
);
|
||||
const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
|
||||
Scope.close(scope, Exit.void),
|
||||
);
|
||||
const cacheRef = yield* Ref.make(new Map<string, CachedGitStatus>());
|
||||
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
|
||||
|
||||
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<GitStatusLocalResult>;
|
||||
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<GitStatusRemoteResult | null>;
|
||||
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;
|
||||
}),
|
||||
);
|
||||
@@ -7,12 +7,10 @@
|
||||
* @module GitCore
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type { Effect, Scope } from "effect";
|
||||
import type {
|
||||
GitCheckoutInput,
|
||||
GitCheckoutResult,
|
||||
GitCreateBranchInput,
|
||||
GitCreateBranchResult,
|
||||
GitCreateWorktreeInput,
|
||||
GitCreateWorktreeResult,
|
||||
GitInitInput,
|
||||
@@ -158,11 +156,6 @@ export interface GitCoreShape {
|
||||
*/
|
||||
readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Read detailed working tree / branch status without refreshing remote tracking refs.
|
||||
*/
|
||||
readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Build staged change context for commit generation.
|
||||
*/
|
||||
@@ -285,16 +278,14 @@ export interface GitCoreShape {
|
||||
/**
|
||||
* Create a local branch.
|
||||
*/
|
||||
readonly createBranch: (
|
||||
input: GitCreateBranchInput,
|
||||
) => Effect.Effect<GitCreateBranchResult, GitCommandError>;
|
||||
readonly createBranch: (input: GitCreateBranchInput) => Effect.Effect<void, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Checkout an existing branch and refresh its upstream metadata in background.
|
||||
*/
|
||||
readonly checkoutBranch: (
|
||||
input: GitCheckoutInput,
|
||||
) => Effect.Effect<GitCheckoutResult, GitCommandError>;
|
||||
) => Effect.Effect<void, GitCommandError, Scope.Scope>;
|
||||
|
||||
/**
|
||||
* Initialize a repository in the provided directory.
|
||||
|
||||
@@ -14,8 +14,6 @@ import {
|
||||
GitResolvePullRequestResult,
|
||||
GitRunStackedActionInput,
|
||||
GitRunStackedActionResult,
|
||||
GitStatusLocalResult,
|
||||
GitStatusRemoteResult,
|
||||
GitStatusInput,
|
||||
GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -43,35 +41,6 @@ export interface GitManagerShape {
|
||||
input: GitStatusInput,
|
||||
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
|
||||
|
||||
/**
|
||||
* Read local repository status without remote hosting enrichment.
|
||||
*/
|
||||
readonly localStatus: (
|
||||
input: GitStatusInput,
|
||||
) => Effect.Effect<GitStatusLocalResult, GitManagerServiceError>;
|
||||
|
||||
/**
|
||||
* Read remote tracking / PR status for a repository.
|
||||
*/
|
||||
readonly remoteStatus: (
|
||||
input: GitStatusInput,
|
||||
) => Effect.Effect<GitStatusRemoteResult | null, GitManagerServiceError>;
|
||||
|
||||
/**
|
||||
* Clear any cached local status snapshot for a repository.
|
||||
*/
|
||||
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
|
||||
/**
|
||||
* Clear any cached remote status snapshot for a repository.
|
||||
*/
|
||||
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
|
||||
/**
|
||||
* Clear any cached status snapshot for a repository so the next read is fresh.
|
||||
*/
|
||||
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
|
||||
/**
|
||||
* Resolve a pull request by URL/number against the current repository.
|
||||
*/
|
||||
@@ -87,7 +56,7 @@ export interface GitManagerShape {
|
||||
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
|
||||
|
||||
/**
|
||||
* Run a Git action (`commit`, `push`, `create_pr`, `commit_push`, `commit_push_pr`).
|
||||
* Run a stacked Git action (`commit`, `commit_push`, `commit_push_pr`).
|
||||
* When `featureBranch` is set, creates and checks out a feature branch first.
|
||||
*/
|
||||
readonly runStackedAction: (
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
import { ServiceMap } 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<GitStatusResult, GitManagerServiceError>;
|
||||
readonly refreshLocalStatus: (
|
||||
cwd: string,
|
||||
) => Effect.Effect<GitStatusLocalResult, GitManagerServiceError>;
|
||||
readonly refreshStatus: (cwd: string) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
|
||||
readonly streamStatus: (
|
||||
input: GitStatusInput,
|
||||
) => Stream.Stream<GitStatusStreamEvent, GitManagerServiceError>;
|
||||
}
|
||||
|
||||
export class GitStatusBroadcaster extends ServiceMap.Service<
|
||||
GitStatusBroadcaster,
|
||||
GitStatusBroadcasterShape
|
||||
>()("t3/git/Services/GitStatusBroadcaster") {}
|
||||
@@ -1,67 +0,0 @@
|
||||
export function parseRemoteNamesInGitOrder(stdout: string): ReadonlyArray<string> {
|
||||
return stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0);
|
||||
}
|
||||
|
||||
export function parseRemoteNames(stdout: string): ReadonlyArray<string> {
|
||||
return parseRemoteNamesInGitOrder(stdout).toSorted((a, b) => b.length - a.length);
|
||||
}
|
||||
|
||||
export function parseRemoteRefWithRemoteNames(
|
||||
ref: string,
|
||||
remoteNames: ReadonlyArray<string>,
|
||||
): { 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>;
|
||||
},
|
||||
): 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();
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
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",
|
||||
);
|
||||
});
|
||||
});
|
||||
+9
-123
@@ -1,15 +1,6 @@
|
||||
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 { Effect, FileSystem, Option, Path } from "effect";
|
||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
|
||||
import {
|
||||
ATTACHMENTS_ROUTE_PREFIX,
|
||||
@@ -17,117 +8,16 @@ import {
|
||||
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 { ServerConfig } from "./config";
|
||||
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 = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></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<unknown, OtlpTracer.TraceData>(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)) {
|
||||
@@ -176,14 +66,13 @@ export const attachmentsRouteLayer = HttpRouter.add(
|
||||
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)) {
|
||||
@@ -217,7 +106,7 @@ export const projectFaviconRouteLayer = HttpRouter.add(
|
||||
Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.catchTag("AuthError", respondToAuthError)),
|
||||
}),
|
||||
);
|
||||
|
||||
export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
@@ -231,14 +120,11 @@ export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
}
|
||||
|
||||
const config = yield* ServerConfig;
|
||||
if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
|
||||
return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
|
||||
status: 302,
|
||||
});
|
||||
if (config.devUrl) {
|
||||
return HttpServerResponse.redirect(config.devUrl.href, { status: 302 });
|
||||
}
|
||||
|
||||
const staticDir = config.staticDir ?? (config.devUrl ? yield* resolveStaticDir() : undefined);
|
||||
if (!staticDir) {
|
||||
if (!config.staticDir) {
|
||||
return HttpServerResponse.text("No static directory configured and no dev URL set.", {
|
||||
status: 503,
|
||||
});
|
||||
@@ -246,7 +132,7 @@ export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const staticRoot = path.resolve(staticDir);
|
||||
const staticRoot = path.resolve(config.staticDir);
|
||||
const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
|
||||
const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
|
||||
const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
|
||||
|
||||
@@ -2,7 +2,7 @@ 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 { Cause, Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
|
||||
import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
|
||||
import { ServerConfig } from "./config";
|
||||
|
||||
import {
|
||||
@@ -149,23 +149,6 @@ 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;
|
||||
|
||||
@@ -322,7 +322,7 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
|
||||
Predicate.isNotNull,
|
||||
() =>
|
||||
new SchemaIssue.InvalidValue(Option.some(rule), {
|
||||
message: "Invalid keybinding rule",
|
||||
title: "Invalid keybinding rule",
|
||||
}),
|
||||
),
|
||||
Effect.map((resolved) => resolved),
|
||||
@@ -334,7 +334,7 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
|
||||
if (!key) {
|
||||
return yield* Effect.fail(
|
||||
new SchemaIssue.InvalidValue(Option.some(resolved), {
|
||||
message: "Resolved shortcut cannot be encoded to key string",
|
||||
title: "Resolved shortcut cannot be encoded to key string",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
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<unknown> = ["alpha"];
|
||||
array.push(array);
|
||||
|
||||
const map = new Map<string, unknown>();
|
||||
map.set("self", map);
|
||||
|
||||
const set = new Set<unknown>();
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -1,128 +0,0 @@
|
||||
import { Cause, Exit } from "effect";
|
||||
|
||||
export type MetricAttributeValue = string;
|
||||
export type MetricAttributes = Readonly<Record<string, MetricAttributeValue>>;
|
||||
export type TraceAttributes = Readonly<Record<string, unknown>>;
|
||||
export type ObservabilityOutcome = "success" | "failure" | "interrupt";
|
||||
|
||||
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function markSeen(value: object, seen: WeakSet<object>): boolean {
|
||||
if (seen.has(value)) {
|
||||
return true;
|
||||
}
|
||||
seen.add(value);
|
||||
return false;
|
||||
}
|
||||
|
||||
function normalizeJsonValue(value: unknown, seen: WeakSet<object> = 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<Record<string, unknown>>,
|
||||
): TraceAttributes {
|
||||
return Object.fromEntries(
|
||||
Object.entries(attributes)
|
||||
.filter(([, value]) => value !== undefined)
|
||||
.map(([key, value]) => [key, normalizeJsonValue(value)]),
|
||||
);
|
||||
}
|
||||
|
||||
export function compactMetricAttributes(
|
||||
attributes: Readonly<Record<string, unknown>>,
|
||||
): 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<unknown, unknown>): 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";
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
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);
|
||||
}),
|
||||
);
|
||||
@@ -1,117 +0,0 @@
|
||||
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<EffectTraceRecord> =>
|
||||
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 });
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,107 +0,0 @@
|
||||
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<Tracer.AnySpan>;
|
||||
readonly annotations: Tracer.Span["annotations"];
|
||||
readonly links: Array<Tracer.SpanLink>;
|
||||
readonly sampled: boolean;
|
||||
readonly kind: Tracer.SpanKind;
|
||||
|
||||
status: Tracer.SpanStatus;
|
||||
attributes: Map<string, unknown>;
|
||||
events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown>]>;
|
||||
|
||||
constructor(
|
||||
options: Parameters<Tracer.Tracer["span"]>[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<unknown, unknown>): 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<string, unknown>): void {
|
||||
const nextAttributes = attributes ?? {};
|
||||
this.events.push([name, startTime, nextAttributes]);
|
||||
this.delegate.event(name, startTime, nextAttributes);
|
||||
}
|
||||
|
||||
addLinks(links: ReadonlyArray<Tracer.SpanLink>): 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 } : {}),
|
||||
});
|
||||
});
|
||||
@@ -1,111 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect, Metric } from "effect";
|
||||
|
||||
import { withMetrics } from "./Metrics.ts";
|
||||
|
||||
const hasMetricSnapshot = (
|
||||
snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
|
||||
id: string,
|
||||
attributes: Readonly<Record<string, string>>,
|
||||
) =>
|
||||
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,
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,160 +0,0 @@
|
||||
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<Record<string, unknown>>,
|
||||
): ReadonlyArray<[string, string]> => Object.entries(compactMetricAttributes(attributes));
|
||||
|
||||
export const increment = (
|
||||
metric: Metric.Metric<number, unknown>,
|
||||
attributes: Readonly<Record<string, unknown>>,
|
||||
amount = 1,
|
||||
) => Metric.update(Metric.withAttributes(metric, metricAttributes(attributes)), amount);
|
||||
|
||||
export interface WithMetricsOptions {
|
||||
readonly counter?: Metric.Metric<number, unknown>;
|
||||
readonly timer?: Metric.Metric<Duration.Duration, unknown>;
|
||||
readonly attributes?:
|
||||
| Readonly<Record<string, unknown>>
|
||||
| (() => Readonly<Record<string, unknown>>);
|
||||
readonly outcomeAttributes?: (
|
||||
outcome: ReturnType<typeof outcomeFromExit>,
|
||||
) => Readonly<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
const withMetricsImpl = <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
options: WithMetricsOptions,
|
||||
): Effect.Effect<A, E, R> =>
|
||||
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: {
|
||||
<A, E, R>(
|
||||
options: WithMetricsOptions,
|
||||
): (effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
|
||||
<A, E, R>(effect: Effect.Effect<A, E, R>, options: WithMetricsOptions): Effect.Effect<A, E, R>;
|
||||
} = dual(2, withMetricsImpl);
|
||||
|
||||
export const providerMetricAttributes = (
|
||||
provider: string,
|
||||
extra?: Readonly<Record<string, unknown>>,
|
||||
) =>
|
||||
compactMetricAttributes({
|
||||
provider,
|
||||
...extra,
|
||||
});
|
||||
|
||||
export const providerTurnMetricAttributes = (input: {
|
||||
readonly provider: string;
|
||||
readonly model: string | null | undefined;
|
||||
readonly extra?: Readonly<Record<string, unknown>>;
|
||||
}) => {
|
||||
const modelFamily = normalizeModelMetricLabel(input.model);
|
||||
return compactMetricAttributes({
|
||||
provider: input.provider,
|
||||
...(modelFamily ? { modelFamily } : {}),
|
||||
...input.extra,
|
||||
});
|
||||
};
|
||||
@@ -1,161 +0,0 @@
|
||||
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<Metric.Metric.Snapshot>,
|
||||
id: string,
|
||||
attributes: Readonly<Record<string, string>>,
|
||||
) =>
|
||||
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,
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,89 +0,0 @@
|
||||
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<Record<string, unknown>>,
|
||||
): Effect.Effect<void, never, never> =>
|
||||
Effect.annotateCurrentSpan({
|
||||
"rpc.method": method,
|
||||
...traceAttributes,
|
||||
});
|
||||
|
||||
const recordRpcStreamMetrics = <E>(
|
||||
method: string,
|
||||
startedAt: number,
|
||||
exit: Exit.Exit<unknown, E>,
|
||||
): Effect.Effect<void, never, never> =>
|
||||
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 = <A, E, R>(
|
||||
method: string,
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
traceAttributes?: Readonly<Record<string, unknown>>,
|
||||
): Effect.Effect<A, E, R> =>
|
||||
Effect.gen(function* () {
|
||||
yield* annotateRpcSpan(method, traceAttributes);
|
||||
|
||||
return yield* effect.pipe(
|
||||
withMetrics({
|
||||
counter: rpcRequestsTotal,
|
||||
timer: rpcRequestDuration,
|
||||
attributes: {
|
||||
method,
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
export const observeRpcStream = <A, E, R>(
|
||||
method: string,
|
||||
stream: Stream.Stream<A, E, R>,
|
||||
traceAttributes?: Readonly<Record<string, unknown>>,
|
||||
): Stream.Stream<A, E, R> =>
|
||||
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 = <A, StreamError, StreamContext, EffectError, EffectContext>(
|
||||
method: string,
|
||||
effect: Effect.Effect<Stream.Stream<A, StreamError, StreamContext>, EffectError, EffectContext>,
|
||||
traceAttributes?: Readonly<Record<string, unknown>>,
|
||||
): Stream.Stream<A, StreamError | EffectError, StreamContext | EffectContext> =>
|
||||
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)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -1,13 +0,0 @@
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { TraceRecord } from "../TraceRecord.ts";
|
||||
|
||||
export interface BrowserTraceCollectorShape {
|
||||
readonly record: (records: ReadonlyArray<TraceRecord>) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class BrowserTraceCollector extends ServiceMap.Service<
|
||||
BrowserTraceCollector,
|
||||
BrowserTraceCollectorShape
|
||||
>()("t3/observability/Services/BrowserTraceCollector") {}
|
||||
@@ -1,287 +0,0 @@
|
||||
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<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
interface TraceRecordLink {
|
||||
readonly traceId: string;
|
||||
readonly spanId: string;
|
||||
readonly attributes: Readonly<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
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<Record<string, unknown>>;
|
||||
readonly events: ReadonlyArray<TraceRecordEvent>;
|
||||
readonly links: ReadonlyArray<TraceRecordLink>;
|
||||
}
|
||||
|
||||
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<Record<string, unknown>>;
|
||||
readonly scope: Readonly<{
|
||||
readonly name?: string;
|
||||
readonly version?: string;
|
||||
readonly attributes: Readonly<Record<string, unknown>>;
|
||||
}>;
|
||||
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<Tracer.AnySpan>;
|
||||
readonly status: Tracer.SpanStatus;
|
||||
readonly sampled: boolean;
|
||||
readonly kind: Tracer.SpanKind;
|
||||
readonly attributes: ReadonlyMap<string, unknown>;
|
||||
readonly links: ReadonlyArray<Tracer.SpanLink>;
|
||||
readonly events: ReadonlyArray<
|
||||
readonly [name: string, startTime: bigint, attributes: Record<string, unknown>]
|
||||
>;
|
||||
}
|
||||
|
||||
function formatTraceExit(exit: Exit.Exit<unknown, unknown>): 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<Tracer.SpanStatus, { _tag: "Ended" }>;
|
||||
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<number, OtlpTraceRecord["kind"]> = {
|
||||
1: "internal",
|
||||
2: "server",
|
||||
3: "client",
|
||||
4: "producer",
|
||||
5: "consumer",
|
||||
};
|
||||
|
||||
export function decodeOtlpTraceRecords(
|
||||
payload: OtlpTracer.TraceData,
|
||||
): ReadonlyArray<OtlpTraceRecord> {
|
||||
const records: Array<OtlpTraceRecord> = [];
|
||||
|
||||
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<Record<string, unknown>>;
|
||||
readonly scopeAttributes: Readonly<Record<string, unknown>>;
|
||||
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<OtlpSpanEvent>): ReadonlyArray<TraceRecordEvent> {
|
||||
return input.map((current) => ({
|
||||
name: current.name,
|
||||
timeUnixNano: current.timeUnixNano,
|
||||
attributes: decodeAttributes(current.attributes),
|
||||
}));
|
||||
}
|
||||
|
||||
function decodeLinks(input: ReadonlyArray<OtlpSpanLink>): ReadonlyArray<TraceRecordLink> {
|
||||
return input.flatMap((current) => {
|
||||
const traceId = current.traceId;
|
||||
const spanId = current.spanId;
|
||||
return {
|
||||
traceId,
|
||||
spanId,
|
||||
attributes: decodeAttributes(current.attributes),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function decodeAttributes(
|
||||
input: ReadonlyArray<OtlpResource.KeyValue>,
|
||||
): Readonly<Record<string, unknown>> {
|
||||
const entries: Record<string, unknown> = {};
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
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<unknown> = [];
|
||||
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 });
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,68 +0,0 @@
|
||||
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<void>;
|
||||
close: () => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
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<string> = [];
|
||||
|
||||
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;
|
||||
});
|
||||
@@ -16,7 +16,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
const antigravityLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "antigravity" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(antigravityLaunch, {
|
||||
command: "agy",
|
||||
@@ -26,7 +25,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
const cursorLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "cursor" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(cursorLaunch, {
|
||||
command: "cursor",
|
||||
@@ -45,7 +43,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
const vscodeLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(vscodeLaunch, {
|
||||
command: "code",
|
||||
@@ -73,30 +70,19 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
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", () =>
|
||||
it.effect("uses --goto when editor supports line/column suffixes", () =>
|
||||
Effect.gen(function* () {
|
||||
const lineOnly = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(lineOnly, {
|
||||
command: "cursor",
|
||||
@@ -106,7 +92,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
const lineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(lineAndColumn, {
|
||||
command: "cursor",
|
||||
@@ -125,7 +110,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(vscodeLineAndColumn, {
|
||||
command: "code",
|
||||
@@ -153,71 +137,11 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
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"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -226,7 +150,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
const launch1 = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(launch1, {
|
||||
command: "open",
|
||||
@@ -236,7 +159,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
const launch2 = yield* resolveEditorLaunch(
|
||||
{ cwd: "C:\\workspace", editor: "file-manager" },
|
||||
"win32",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(launch2, {
|
||||
command: "explorer",
|
||||
@@ -246,7 +168,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
const launch3 = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||
"linux",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(launch3, {
|
||||
command: "xdg-open",
|
||||
@@ -364,29 +285,4 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
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, []);
|
||||
});
|
||||
});
|
||||
+10
-74
@@ -34,57 +34,10 @@ interface CommandAvailabilityOptions {
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
}
|
||||
|
||||
const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
|
||||
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
|
||||
|
||||
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 resolveCommandEditorArgs(
|
||||
editor: (typeof EDITORS)[number],
|
||||
target: string,
|
||||
): ReadonlyArray<string> {
|
||||
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<string>,
|
||||
options: CommandAvailabilityOptions = {},
|
||||
): string | null {
|
||||
for (const command of commands) {
|
||||
if (isCommandAvailable(command, options)) {
|
||||
return command;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean {
|
||||
return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target);
|
||||
}
|
||||
|
||||
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
|
||||
@@ -210,16 +163,8 @@ export function resolveAvailableEditors(
|
||||
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) {
|
||||
const command = editor.command ?? fileManagerCommandForPlatform(platform);
|
||||
if (isCommandAvailable(command, { platform, env })) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
}
|
||||
@@ -253,28 +198,19 @@ export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
|
||||
// Implementations
|
||||
// ==============================
|
||||
|
||||
export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
|
||||
export const resolveEditorLaunch = Effect.fnUntraced(function* (
|
||||
input: OpenInEditorInput,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): Effect.fn.Return<EditorLaunch, OpenError> {
|
||||
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 (editorDef.commands) {
|
||||
const command =
|
||||
resolveAvailableCommand(editorDef.commands, { platform, env }) ?? editorDef.commands[0];
|
||||
return {
|
||||
command,
|
||||
args: resolveCommandEditorArgs(editorDef, input.cwd),
|
||||
};
|
||||
if (editorDef.command) {
|
||||
return shouldUseGotoFlag(editorDef, input.cwd)
|
||||
? { command: editorDef.command, args: ["--goto", input.cwd] }
|
||||
: { command: editorDef.command, args: [input.cwd] };
|
||||
}
|
||||
|
||||
if (editorDef.id !== "file-manager") {
|
||||
|
||||
@@ -20,12 +20,9 @@ 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";
|
||||
@@ -98,9 +95,7 @@ function createProviderServiceHarness(
|
||||
listSessions,
|
||||
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
|
||||
rollbackConversation,
|
||||
get streamEvents() {
|
||||
return Stream.fromPubSub(runtimeEventPubSub);
|
||||
},
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
};
|
||||
|
||||
const emit = (event: LegacyProviderRuntimeEvent): void => {
|
||||
@@ -244,7 +239,6 @@ describe("CheckpointReactor", () => {
|
||||
readonly threadWorktreePath?: string | null;
|
||||
readonly providerSessionCwd?: string;
|
||||
readonly providerName?: ProviderKind;
|
||||
readonly gitStatusRefreshCalls?: Array<string>;
|
||||
}) {
|
||||
const cwd = createGitRepository();
|
||||
tempDirs.push(cwd);
|
||||
@@ -255,41 +249,20 @@ 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.pipe(Layer.provide(WorkspacePathsLive))),
|
||||
Layer.provideMerge(WorkspacePathsLive),
|
||||
@@ -447,28 +420,6 @@ describe("CheckpointReactor", () => {
|
||||
).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.makeUnsafe("evt-turn-completed-refresh-local-status"),
|
||||
provider: "codex",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("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();
|
||||
|
||||
@@ -24,7 +24,6 @@ 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 =
|
||||
@@ -70,7 +69,6 @@ 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;
|
||||
@@ -121,7 +119,7 @@ const make = Effect.gen(function* () {
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
|
||||
const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* (
|
||||
const resolveSessionRuntimeForThread = Effect.fnUntraced(function* (
|
||||
threadId: ThreadId,
|
||||
): Effect.fn.Return<Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>> {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
@@ -155,7 +153,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.fn("resolveCheckpointCwd")(function* (input: {
|
||||
const resolveCheckpointCwd = Effect.fnUntraced(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null };
|
||||
readonly projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>;
|
||||
@@ -190,7 +188,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.fn("captureAndDispatchCheckpoint")(function* (input: {
|
||||
const captureAndDispatchCheckpoint = Effect.fnUntraced(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId;
|
||||
readonly thread: {
|
||||
@@ -323,70 +321,70 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
// Captures a real git checkpoint when a turn completes via a runtime event.
|
||||
const captureCheckpointFromTurnCompletion = Effect.fn("captureCheckpointFromTurnCompletion")(
|
||||
function* (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>) {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (!turnId) {
|
||||
return;
|
||||
}
|
||||
const captureCheckpointFromTurnCompletion = Effect.fnUntraced(function* (
|
||||
event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>,
|
||||
) {
|
||||
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
|
||||
@@ -396,7 +394,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.fn("captureCheckpointFromPlaceholder")(function* (
|
||||
const captureCheckpointFromPlaceholder = Effect.fnUntraced(function* (
|
||||
event: Extract<OrchestrationEvent, { type: "thread.turn-diff-completed" }>,
|
||||
) {
|
||||
const { threadId, turnId, checkpointTurnCount, status } = event.payload;
|
||||
@@ -450,79 +448,57 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
const ensurePreTurnBaselineFromTurnStart = Effect.fn("ensurePreTurnBaselineFromTurnStart")(
|
||||
function* (event: Extract<ProviderRuntimeEvent, { type: "turn.started" }>) {
|
||||
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<ProviderRuntimeEvent, { type: "turn.completed" }>) {
|
||||
const sessionRuntime = yield* resolveSessionRuntimeForThread(event.threadId);
|
||||
if (Option.isNone(sessionRuntime)) {
|
||||
const ensurePreTurnBaselineFromTurnStart = Effect.fnUntraced(function* (
|
||||
event: Extract<ProviderRuntimeEvent, { type: "turn.started" }>,
|
||||
) {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (!turnId) {
|
||||
return;
|
||||
}
|
||||
|
||||
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 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 ensurePreTurnBaselineFromDomainTurnStart = Effect.fn(
|
||||
"ensurePreTurnBaselineFromDomainTurnStart",
|
||||
)(function* (
|
||||
const ensurePreTurnBaselineFromDomainTurnStart = Effect.fnUntraced(function* (
|
||||
event: Extract<
|
||||
OrchestrationEvent,
|
||||
{ type: "thread.turn-start-requested" | "thread.message-sent" }
|
||||
@@ -581,7 +557,7 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
const handleRevertRequested = Effect.fn("handleRevertRequested")(function* (
|
||||
const handleRevertRequested = Effect.fnUntraced(function* (
|
||||
event: Extract<OrchestrationEvent, { type: "thread.checkpoint-revert-requested" }>,
|
||||
) {
|
||||
const now = new Date().toISOString();
|
||||
@@ -709,7 +685,7 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
});
|
||||
|
||||
const processDomainEvent = Effect.fn("processDomainEvent")(function* (event: OrchestrationEvent) {
|
||||
const processDomainEvent = Effect.fnUntraced(function* (event: OrchestrationEvent) {
|
||||
if (event.type === "thread.turn-start-requested" || event.type === "thread.message-sent") {
|
||||
yield* ensurePreTurnBaselineFromDomainTurnStart(event);
|
||||
return;
|
||||
@@ -748,9 +724,7 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* (
|
||||
event: ProviderRuntimeEvent,
|
||||
) {
|
||||
const processRuntimeEvent = Effect.fnUntraced(function* (event: ProviderRuntimeEvent) {
|
||||
if (event.type === "turn.started") {
|
||||
yield* ensurePreTurnBaselineFromTurnStart(event);
|
||||
return;
|
||||
@@ -758,7 +732,6 @@ 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({
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
TurnId,
|
||||
type OrchestrationEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect";
|
||||
import { Effect, Layer, ManagedRuntime, Queue, Stream } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { PersistenceSqlError } from "../../persistence/Errors.ts";
|
||||
@@ -19,16 +19,13 @@ 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";
|
||||
|
||||
@@ -42,11 +39,9 @@ async function createOrchestrationSystem() {
|
||||
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),
|
||||
@@ -64,117 +59,7 @@ function now() {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
const hasMetricSnapshot = (
|
||||
snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
|
||||
id: string,
|
||||
attributes: Readonly<Record<string, string>>,
|
||||
) =>
|
||||
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.makeUnsafe("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();
|
||||
@@ -421,95 +306,6 @@ 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.makeUnsafe("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.makeUnsafe("cmd-thread-ack-create"),
|
||||
threadId: ThreadId.makeUnsafe("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.makeUnsafe("cmd-thread-missing-project"),
|
||||
threadId: ThreadId.makeUnsafe("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;
|
||||
@@ -621,11 +417,9 @@ 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),
|
||||
@@ -718,11 +512,9 @@ 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),
|
||||
),
|
||||
);
|
||||
@@ -861,11 +653,9 @@ 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),
|
||||
),
|
||||
);
|
||||
|
||||
Loaded 100 of 386 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user