Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e9fa2b75dc | ||
|
|
885a825bdb | ||
|
|
0ea58f2dbf | ||
|
|
1f83f781d7 | ||
|
|
ad4eb99e22 | ||
|
|
4bf8d7b74c | ||
|
|
971df8206d | ||
|
|
eecc2bc28d | ||
|
|
1bf048eb8b | ||
|
|
f7fa62aaf9 | ||
|
|
57d7746a5d | ||
|
|
850c912556 | ||
|
|
dff8784aef | ||
|
|
96c9306dbd | ||
|
|
94d13a2b75 | ||
|
|
7a008461fc | ||
|
|
f59ee36bf1 | ||
|
|
2fce84a1d4 | ||
|
|
f9019cd63f | ||
|
|
f9372a4c3d | ||
|
|
934037cb66 | ||
|
|
5467d11980 | ||
|
|
1f4a3f65bf | ||
|
|
26cc1fffb3 | ||
|
|
97880e8870 | ||
|
|
b80e8476b8 | ||
|
|
e0e01b4a54 | ||
|
|
58e5f714b0 | ||
|
|
4ae9de311b | ||
|
|
5fa09fa2d9 | ||
|
|
12c3af7821 | ||
|
|
e2316814da | ||
|
|
678f827f0b | ||
|
|
a3dadf311e | ||
|
|
e3004ae806 | ||
|
|
9385314d26 | ||
|
|
a3f292770e | ||
|
|
2028d57e88 | ||
|
|
3405a64dd8 | ||
|
|
1cba2f64d3 | ||
|
|
1a05d8ca1a | ||
|
|
cf9f236c80 | ||
|
|
e82b987386 | ||
|
|
ea9e61b266 | ||
|
|
e32077cee7 | ||
|
|
5d9eb18312 | ||
|
|
abb84c09e3 | ||
|
|
65d797c13e | ||
|
|
7c0849fe2e | ||
|
|
592c234fd5 | ||
|
|
66d76b5d02 | ||
|
|
528bb2a1fa | ||
|
|
869789b4ed | ||
|
|
9bedd7140c | ||
|
|
70f5dfcef7 | ||
|
|
9847e9b621 | ||
|
|
b547fee77e | ||
|
|
7b3cdc6a8c | ||
|
|
386eb18a58 | ||
|
|
7372184d06 | ||
|
|
d9ded65dfe | ||
|
|
2aa73985ea | ||
|
|
5b3b31b6e6 | ||
|
|
b7559c4678 | ||
|
|
b96308fc5a | ||
|
|
72b7f90c50 | ||
|
|
1ec346c22e | ||
|
|
28e481eb24 | ||
|
|
b1934b925a | ||
|
|
8244fb80e6 | ||
|
|
afc3924393 | ||
|
|
11d456f6c8 | ||
|
|
a221542921 | ||
|
|
226ed997e1 | ||
|
|
c6f57a1064 | ||
|
|
340dbbb36e | ||
|
|
53a552e80d | ||
|
|
cf2c628bc0 | ||
|
|
e0874b651d | ||
|
|
12347082ef | ||
|
|
740d7a3216 | ||
|
|
cd7980b457 | ||
|
|
f2cd53f232 | ||
|
|
04a1ae77e6 | ||
|
|
6de4b47ecb | ||
|
|
27c2b145f8 | ||
|
|
8515f02770 | ||
|
|
e9ed849b53 | ||
|
|
e8f5b4ad5b | ||
|
|
752f96e9ae | ||
|
|
1b272fd709 | ||
|
|
9013c07f6d | ||
|
|
085340588a | ||
|
|
48481aa923 | ||
|
|
da107f315c | ||
|
|
d2822a8883 | ||
|
|
ae3ea3980d | ||
|
|
915a0548c0 | ||
|
|
5ce5472bc3 | ||
|
|
9ea443d73a | ||
|
|
60f7ae86bb | ||
|
|
867cf4cf09 | ||
|
|
ae6f9715c6 | ||
|
|
b92c78f552 | ||
|
|
801dfe5b41 | ||
|
|
823d69f621 | ||
|
|
4963fccb05 | ||
|
|
dd89d5ce1a | ||
|
|
9132c37c86 | ||
|
|
b9c7ea0581 | ||
|
|
556a195c9d | ||
|
|
80b282ece7 | ||
|
|
d15075b32d | ||
|
|
9f6686a13d | ||
|
|
c6ff7c0d5b | ||
|
|
a9e5a84c03 | ||
|
|
67ca528fea | ||
|
|
6d9b21c5d0 | ||
|
|
ddffdfc095 | ||
|
|
a58290ed79 |
No files matched your search
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "T3 Code Dev",
|
||||
"image": "debian:bookworm",
|
||||
"features": {
|
||||
"ghcr.io/devcontainers-extra/features/bun:1": {},
|
||||
"ghcr.io/devcontainers/features/node:1": {
|
||||
"version": "24",
|
||||
"nodeGypDependencies": true
|
||||
},
|
||||
"ghcr.io/devcontainers/features/python:1": {
|
||||
"version": "3.12"
|
||||
}
|
||||
},
|
||||
"postCreateCommand": {
|
||||
"bun-install": "bun install --backend=copyfile --frozen-lockfile"
|
||||
},
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
"extensions": ["oxc.oxc-vscode"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
# Remote Architecture
|
||||
|
||||
This document describes the target architecture for first-class remote environments in T3 Code.
|
||||
|
||||
It is intentionally architecture-first. It does not define a complete implementation plan or user-facing rollout checklist. The goal is to establish the core model so remote support can be added without another broad rewrite.
|
||||
|
||||
## Goals
|
||||
|
||||
- Treat remote environments as first-class product primitives, not special cases.
|
||||
- Support multiple ways to reach the same environment.
|
||||
- Keep the T3 server as the execution boundary.
|
||||
- Let desktop, mobile, and web all share the same conceptual model.
|
||||
- Avoid introducing a local control plane unless product pressure proves it is necessary.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Replacing the existing WebSocket server boundary with a custom transport protocol.
|
||||
- Making SSH the only remote story.
|
||||
- Syncing provider auth across machines.
|
||||
- Shipping every access method in the first iteration.
|
||||
|
||||
## High-level architecture
|
||||
|
||||
T3 already has a clean runtime boundary: the client talks to a T3 server over HTTP/WebSocket, and the server owns orchestration, providers, terminals, git, and filesystem operations.
|
||||
|
||||
Remote support should preserve that boundary.
|
||||
|
||||
```text
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ Client (desktop / mobile / web) │
|
||||
│ │
|
||||
│ - known environments │
|
||||
│ - connection manager │
|
||||
│ - environment-aware routing │
|
||||
└───────────────┬──────────────────────────────┘
|
||||
│
|
||||
│ resolves one access endpoint
|
||||
│
|
||||
┌───────────────▼──────────────────────────────┐
|
||||
│ Access method │
|
||||
│ │
|
||||
│ - direct ws / wss │
|
||||
│ - tunneled ws / wss │
|
||||
│ - desktop-managed ssh bootstrap + forward │
|
||||
└───────────────┬──────────────────────────────┘
|
||||
│
|
||||
│ connects to one T3 server
|
||||
│
|
||||
┌───────────────▼──────────────────────────────┐
|
||||
│ Execution environment = one T3 server │
|
||||
│ │
|
||||
│ - environment identity │
|
||||
│ - provider state │
|
||||
│ - projects / threads / terminals │
|
||||
│ - git / filesystem / process runtime │
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
The important decision is that remoteness is expressed at the environment connection layer, not by splitting the T3 runtime itself.
|
||||
|
||||
## Domain model
|
||||
|
||||
### ExecutionEnvironment
|
||||
|
||||
An `ExecutionEnvironment` is one running T3 server instance.
|
||||
|
||||
It is the unit that owns:
|
||||
|
||||
- provider availability and auth state
|
||||
- model availability
|
||||
- projects and threads
|
||||
- terminal processes
|
||||
- filesystem access
|
||||
- git operations
|
||||
- server settings
|
||||
|
||||
It is identified by a stable `environmentId`.
|
||||
|
||||
This is the shared cross-client primitive. Desktop, mobile, and web should all reason about the same concept here.
|
||||
|
||||
### KnownEnvironment
|
||||
|
||||
A `KnownEnvironment` is a client-side saved entry for an environment the client knows how to reach.
|
||||
|
||||
It is not server-authored. It is local to a device or client profile.
|
||||
|
||||
Examples:
|
||||
|
||||
- a saved LAN URL
|
||||
- a saved public `wss://` endpoint
|
||||
- a desktop-managed SSH host entry
|
||||
- a saved tunneled environment
|
||||
|
||||
A known environment may or may not know the target `environmentId` before first successful connect.
|
||||
|
||||
### AccessEndpoint
|
||||
|
||||
An `AccessEndpoint` is one concrete way to reach a known environment.
|
||||
|
||||
This is the key abstraction that keeps SSH from taking over the model.
|
||||
|
||||
A single environment may have many endpoints:
|
||||
|
||||
- `wss://t3.example.com`
|
||||
- `ws://10.0.0.25:3773`
|
||||
- a tunneled relay URL
|
||||
- a desktop-managed SSH tunnel that resolves to a local forwarded WebSocket URL
|
||||
|
||||
The environment stays the same. Only the access path changes.
|
||||
|
||||
### RepositoryIdentity
|
||||
|
||||
`RepositoryIdentity` remains a best-effort logical repo grouping mechanism across environments.
|
||||
|
||||
It is not used for routing. It is only used for UI grouping and correlation between local and remote clones of the same repository.
|
||||
|
||||
### Workspace / Project
|
||||
|
||||
The current `Project` model remains environment-local.
|
||||
|
||||
That means:
|
||||
|
||||
- a local clone and a remote clone are different projects
|
||||
- they may share a `RepositoryIdentity`
|
||||
- threads still bind to one project in one environment
|
||||
|
||||
## Access methods
|
||||
|
||||
Access methods answer one question:
|
||||
|
||||
How does the client speak WebSocket to a T3 server?
|
||||
|
||||
They do not answer:
|
||||
|
||||
- how the server got started
|
||||
- who manages the server process
|
||||
- whether the environment is local or remote
|
||||
|
||||
### 1. Direct WebSocket access
|
||||
|
||||
Examples:
|
||||
|
||||
- `ws://10.0.0.15:3773`
|
||||
- `wss://t3.example.com`
|
||||
|
||||
This is the base model and should be the first-class default.
|
||||
|
||||
Benefits:
|
||||
|
||||
- works for desktop, mobile, and web
|
||||
- no client-specific process management required
|
||||
- best fit for hosted or self-managed remote T3 deployments
|
||||
|
||||
### 2. Tunneled WebSocket access
|
||||
|
||||
Examples:
|
||||
|
||||
- public relay URLs
|
||||
- private network relay URLs
|
||||
- local tunnel products such as pipenet
|
||||
|
||||
This is still direct WebSocket access from the client's perspective. The difference is that the route is mediated by a tunnel or relay.
|
||||
|
||||
For T3, tunnels are best modeled as another `AccessEndpoint`, not as a different kind of environment.
|
||||
|
||||
This is especially useful when:
|
||||
|
||||
- the host is behind NAT
|
||||
- inbound ports are unavailable
|
||||
- mobile must reach a desktop-hosted environment
|
||||
- a machine should be reachable without exposing raw LAN or public ports
|
||||
|
||||
### 3. Desktop-managed SSH access
|
||||
|
||||
SSH is an access and launch helper, not a separate environment type.
|
||||
|
||||
The desktop main process can use SSH to:
|
||||
|
||||
- reach a machine
|
||||
- probe it
|
||||
- launch or reuse a remote T3 server
|
||||
- establish a local port forward
|
||||
|
||||
After that, the renderer should still connect using an ordinary WebSocket URL against the forwarded local port.
|
||||
|
||||
This keeps the renderer transport model consistent with every other access method.
|
||||
|
||||
## Launch methods
|
||||
|
||||
Launch methods answer a different question:
|
||||
|
||||
How does a T3 server come to exist on the target machine?
|
||||
|
||||
Launch and access should stay separate in the design.
|
||||
|
||||
### 1. Pre-existing server
|
||||
|
||||
The simplest launch method is no launch at all.
|
||||
|
||||
The user or operator already runs T3 on the target machine, and the client connects through a direct or tunneled WebSocket endpoint.
|
||||
|
||||
This should be the first remote mode shipped because it validates the environment model with minimal extra machinery.
|
||||
|
||||
### 2. Desktop-managed remote launch over SSH
|
||||
|
||||
This is the main place where Zed is a useful reference.
|
||||
|
||||
Useful ideas to borrow from Zed:
|
||||
|
||||
- remote probing
|
||||
- platform detection
|
||||
- session directories with pid/log metadata
|
||||
- reconnect-friendly launcher behavior
|
||||
- desktop-owned connection UX
|
||||
|
||||
What should be different in T3:
|
||||
|
||||
- no custom stdio/socket proxy protocol between renderer and remote runtime
|
||||
- no attempt to make the remote runtime look like an editor transport
|
||||
- keep the final client-to-server connection as WebSocket
|
||||
|
||||
The recommended T3 flow is:
|
||||
|
||||
1. Desktop connects over SSH.
|
||||
2. Desktop probes the remote machine and verifies T3 availability.
|
||||
3. Desktop launches or reuses a remote T3 server.
|
||||
4. Desktop establishes local port forwarding.
|
||||
5. Renderer connects to the forwarded WebSocket endpoint as a normal environment.
|
||||
|
||||
### 3. Client-managed local publish
|
||||
|
||||
This is the inverse of remote launch: a local T3 server is already running, and the client publishes it through a tunnel.
|
||||
|
||||
This is useful for:
|
||||
|
||||
- exposing a desktop-hosted environment to mobile
|
||||
- temporary remote access without changing router or firewall settings
|
||||
|
||||
This is still a launch concern, not a new environment kind.
|
||||
|
||||
## Why access and launch must stay separate
|
||||
|
||||
These concerns are easy to conflate, but separating them prevents architectural drift.
|
||||
|
||||
Examples:
|
||||
|
||||
- A manually hosted T3 server might be reached through direct `wss`.
|
||||
- The same server might also be reachable through a tunnel.
|
||||
- An SSH-managed server might be launched over SSH but then reached through forwarded WebSocket.
|
||||
- A local desktop server might be published through a tunnel for mobile.
|
||||
|
||||
In all of those cases, the `ExecutionEnvironment` is the same kind of thing.
|
||||
|
||||
Only the launch and access paths differ.
|
||||
|
||||
## Security model
|
||||
|
||||
Remote support must assume that some environments will be reachable over untrusted networks.
|
||||
|
||||
That means:
|
||||
|
||||
- remote-capable environments should require explicit authentication
|
||||
- tunnel exposure should not rely on obscurity
|
||||
- client-saved endpoints should carry enough auth metadata to reconnect safely
|
||||
|
||||
T3 already supports a WebSocket auth token on the server. That should become a first-class part of environment access rather than remaining an incidental query parameter convention.
|
||||
|
||||
For publicly reachable environments, authenticated access should be treated as required.
|
||||
|
||||
## Relationship to Zed
|
||||
|
||||
Zed is a useful reference implementation for managed remote launch and reconnect behavior.
|
||||
|
||||
The relevant lessons are:
|
||||
|
||||
- remote bootstrap should be explicit
|
||||
- reconnect should be first-class
|
||||
- connection UX belongs in the client shell
|
||||
- runtime ownership should stay clearly on the remote host
|
||||
|
||||
The important mismatch is transport shape.
|
||||
|
||||
Zed needs a custom proxy/server protocol because its remote boundary sits below the editor and project runtime.
|
||||
|
||||
T3 should not copy that part.
|
||||
|
||||
T3 already has the right runtime boundary:
|
||||
|
||||
- one T3 server per environment
|
||||
- ordinary HTTP/WebSocket between client and environment
|
||||
|
||||
So T3 should borrow Zed's launch discipline, not its transport protocol.
|
||||
|
||||
## Recommended rollout
|
||||
|
||||
1. First-class known environments and access endpoints.
|
||||
2. Direct `ws` / `wss` remote environments.
|
||||
3. Authenticated tunnel-backed environments.
|
||||
4. Desktop-managed SSH launch and forwarding.
|
||||
5. Multi-environment UI improvements after the base runtime path is proven.
|
||||
|
||||
This ordering keeps the architecture network-first and transport-agnostic while still leaving room for richer managed remote flows.
|
||||
@@ -10,6 +10,7 @@ jobs:
|
||||
quality:
|
||||
name: Format, Lint, Typecheck, Test, Browser Test, Build
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
@@ -71,11 +72,12 @@ jobs:
|
||||
- name: Verify preload bundle output
|
||||
run: |
|
||||
test -f apps/desktop/dist-electron/preload.js
|
||||
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
|
||||
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
|
||||
|
||||
release_smoke:
|
||||
name: Release Smoke
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
@@ -19,6 +19,7 @@ jobs:
|
||||
preflight:
|
||||
name: Preflight
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
outputs:
|
||||
version: ${{ steps.release_meta.outputs.version }}
|
||||
tag: ${{ steps.release_meta.outputs.tag }}
|
||||
@@ -81,6 +82,7 @@ jobs:
|
||||
name: Build ${{ matrix.label }}
|
||||
needs: preflight
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -227,6 +229,7 @@ jobs:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, build]
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
@@ -260,6 +263,7 @@ jobs:
|
||||
name: Publish GitHub Release
|
||||
needs: [preflight, build, publish_cli]
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
@@ -307,6 +311,7 @@ jobs:
|
||||
name: Finalize release
|
||||
needs: [preflight, release]
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- id: app_token
|
||||
name: Mint release app token
|
||||
|
||||
@@ -21,3 +21,5 @@ apps/web/src/components/__screenshots__
|
||||
.vitest-*
|
||||
__screenshots__/
|
||||
.tanstack
|
||||
squashfs-root/
|
||||
artifacts/
|
||||
+2
-1
@@ -9,7 +9,8 @@
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo",
|
||||
"**/routeTree.gen.ts",
|
||||
"apps/web/public/mockServiceWorker.js"
|
||||
"apps/web/public/mockServiceWorker.js",
|
||||
"apps/web/src/lib/vendor/qrcodegen.ts"
|
||||
],
|
||||
"sortPackageJson": {}
|
||||
}
|
||||
@@ -0,0 +1,823 @@
|
||||
# Server Auth Model Plan
|
||||
|
||||
## Purpose
|
||||
|
||||
Define the long-term server auth architecture for T3 Code before first-class remote environments ship.
|
||||
|
||||
This plan is deliberately broader than the current WebSocket token check and narrower than a complete remote collaboration system. The goal is to make the server secure by default, keep local desktop UX frictionless, and leave clean integration points for future remote access methods.
|
||||
|
||||
This document is written in terms of Effect-native services and layers because auth needs to be a core runtime concern, not route-local glue code.
|
||||
|
||||
## Primary goals
|
||||
|
||||
- Make auth server-wide, not WebSocket-only.
|
||||
- Make insecure exposure hard to do accidentally.
|
||||
- Preserve zero-login local desktop UX for desktop-managed environments.
|
||||
- Support browser-native pairing and session auth.
|
||||
- Leave room for native/mobile credentials later without rewriting the server boundary.
|
||||
- Keep auth separate from transport and launch method.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Full multi-user authorization and RBAC.
|
||||
- OAuth / SSO / enterprise identity.
|
||||
- Passkeys or biometric UX in v1.
|
||||
- Syncing auth state across environments.
|
||||
- Designing the full remote environment product in this document.
|
||||
|
||||
## Core decisions
|
||||
|
||||
### 1. Auth is a server concern
|
||||
|
||||
Every privileged surface of the T3 server must go through the same auth policy engine:
|
||||
|
||||
- HTTP routes
|
||||
- WebSocket upgrades
|
||||
- RPC methods reached through WebSocket
|
||||
|
||||
The current split where [`/ws`](../apps/server/src/ws.ts) checks `authToken` but routes in [`http.ts`](../apps/server/src/http.ts) do not is not sufficient for a remote-capable product.
|
||||
|
||||
### 2. Pairing and session are different things
|
||||
|
||||
The system should distinguish:
|
||||
|
||||
- bootstrap credentials
|
||||
- session credentials
|
||||
|
||||
Bootstrap credentials are short-lived and high-trust. They allow a client to become authenticated.
|
||||
|
||||
Session credentials are the durable credentials used after pairing.
|
||||
|
||||
Bootstrap should never become the long-lived request credential.
|
||||
|
||||
### 3. Auth and transport are separate
|
||||
|
||||
Auth must not be defined by how the client reached the server.
|
||||
|
||||
Examples:
|
||||
|
||||
- local desktop-managed server
|
||||
- LAN `ws://`
|
||||
- public `wss://`
|
||||
- tunneled `wss://`
|
||||
- SSH-forwarded `ws://127.0.0.1:<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.
|
||||
@@ -23,6 +23,7 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`](
|
||||
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
|
||||
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
|
||||
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
|
||||
{ "key": "mod+k", "command": "commandPalette.toggle", "when": "!terminalFocus" },
|
||||
{ "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
|
||||
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
|
||||
{ "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" },
|
||||
@@ -50,6 +51,7 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
|
||||
- `terminal.split`: split terminal (in focused terminal context by default)
|
||||
- `terminal.new`: create new terminal (in focused terminal context by default)
|
||||
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
|
||||
- `commandPalette.toggle`: open or close the global command palette
|
||||
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
|
||||
- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`))
|
||||
- `editor.openFavorite`: open current project/worktree in the last-used editor
|
||||
|
||||
@@ -45,6 +45,12 @@ We are very very early in this project. Expect bugs.
|
||||
|
||||
We are not accepting contributions yet.
|
||||
|
||||
Observability guide: [docs/observability.md](./docs/observability.md)
|
||||
|
||||
## Performance benchmarks
|
||||
|
||||
See [docs/perf-benchmarks.md](./docs/perf-benchmarks.md) for the local perf harness, seeded scenarios, artifact format, and the commands for automated and manual benchmark runs.
|
||||
|
||||
## If you REALLY want to contribute still.... read this first
|
||||
|
||||
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
|
||||
|
||||
@@ -1,68 +1,87 @@
|
||||
# Remote Access Setup
|
||||
# Remote Access
|
||||
|
||||
Use this when you want to open T3 Code from another device (phone, tablet, another laptop).
|
||||
Use this when you want to connect to a T3 Code server from another device such as a phone, tablet, or separate desktop app.
|
||||
|
||||
## CLI ↔ Env option map
|
||||
## Recommended Setup
|
||||
|
||||
The T3 Code CLI accepts the following configuration options, available either as CLI flags or environment variables:
|
||||
Use a trusted private network that meshes your devices together, such as a tailnet.
|
||||
|
||||
| CLI flag | Env var | Notes |
|
||||
| ----------------------- | --------------------- | ------------------------------------------------------------------------------------ |
|
||||
| `--mode <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. |
|
||||
That gives you:
|
||||
|
||||
> TIP: Use the `--help` flag to see all available options and their descriptions.
|
||||
- a stable address to connect to
|
||||
- transport security at the network layer
|
||||
- less exposure than opening the server to the public internet
|
||||
|
||||
## Security First
|
||||
## Enabling Network Access
|
||||
|
||||
- Always set `--auth-token` before exposing the server outside localhost.
|
||||
- When you control the process launcher, prefer sending the auth token in a JSON envelope via `--bootstrap-fd <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.
|
||||
There are two ways to expose your server for remote connections: from the desktop app or from the CLI.
|
||||
|
||||
## 1) Build + run server for remote access
|
||||
### Option 1: Desktop App
|
||||
|
||||
Remote access should use the built web app (not local Vite redirect mode).
|
||||
If you are already running the desktop app and want to make it reachable from other devices:
|
||||
|
||||
1. Open **Settings** → **Connections**.
|
||||
2. Under **Manage Local Backend**, toggle **Network access** on. This will restart the app and run the backend on all network interfaces.
|
||||
3. The settings panel will show the address the server is reachable at (e.g. `http://192.168.x.y:3773`).
|
||||
4. Use **Create Link** to generate a pairing link you can share with another device.
|
||||
|
||||
### Option 2: Headless Server (CLI)
|
||||
|
||||
Use this when you want to run the server without a GUI, for example on a remote machine over SSH.
|
||||
|
||||
Run the server with `t3 serve`.
|
||||
|
||||
```bash
|
||||
bun run build
|
||||
TOKEN="$(openssl rand -hex 24)"
|
||||
bun run --cwd apps/server start -- --host 0.0.0.0 --port 3773 --auth-token "$TOKEN" --no-browser
|
||||
npx t3 serve --host "$(tailscale ip -4)"
|
||||
```
|
||||
|
||||
Then open on your phone:
|
||||
`t3 serve` starts the server without opening a browser and prints:
|
||||
|
||||
`http://<your-machine-ip>:3773`
|
||||
- a connection string
|
||||
- a pairing token
|
||||
- a pairing URL
|
||||
- a QR code for the pairing URL
|
||||
|
||||
Example:
|
||||
From there, connect from another device in either of these ways:
|
||||
|
||||
`http://192.168.1.42:3773`
|
||||
- scan the QR code on your phone
|
||||
- in the desktop app, enter the full pairing URL
|
||||
- in the desktop app, enter the host and token separately
|
||||
|
||||
Notes:
|
||||
Use `t3 serve --help` for the full flag reference. It supports the same general startup options as the normal server command, including an optional `cwd` argument.
|
||||
|
||||
- `--host 0.0.0.0` listens on all IPv4 interfaces.
|
||||
- `--no-browser` prevents local auto-open, which is usually better for headless/remote sessions.
|
||||
- Ensure your OS firewall allows inbound TCP on the selected port.
|
||||
> Note
|
||||
> The GUIs do not currently support adding projects on remote environments.
|
||||
> For now, use `t3 project ...` on the server machine instead.
|
||||
> Full GUI support for remote project management is coming soon.
|
||||
|
||||
## 2) Tailnet / Tailscale access
|
||||
## How Pairing Works
|
||||
|
||||
If you use Tailscale, you can bind directly to your Tailnet address.
|
||||
The remote device does not need a long-lived secret up front.
|
||||
|
||||
```bash
|
||||
TAILNET_IP="$(tailscale ip -4)"
|
||||
TOKEN="$(openssl rand -hex 24)"
|
||||
bun run --cwd apps/server start -- --host "$(tailscale ip -4)" --port 3773 --auth-token "$TOKEN" --no-browser
|
||||
```
|
||||
Instead:
|
||||
|
||||
Open from any device in your tailnet:
|
||||
1. `t3 serve` issues a one-time owner pairing token.
|
||||
2. The remote device exchanges that token with the server.
|
||||
3. The server creates an authenticated session for that device.
|
||||
|
||||
`http://<tailnet-ip>:3773`
|
||||
After pairing, future access is session-based. You do not need to keep reusing the original token unless you are pairing a new device.
|
||||
|
||||
You can also bind `--host 0.0.0.0` and connect through the Tailnet IP, but binding directly to the Tailnet IP limits exposure.
|
||||
## Managing Access Later
|
||||
|
||||
Use `t3 auth` to manage access after the initial pairing flow.
|
||||
|
||||
Typical uses:
|
||||
|
||||
- issue additional pairing credentials
|
||||
- inspect active sessions
|
||||
- revoke old pairing links or sessions
|
||||
|
||||
Use `t3 auth --help` and the nested subcommand help pages for the full reference.
|
||||
|
||||
## Security Notes
|
||||
|
||||
- Treat pairing URLs and pairing tokens like passwords.
|
||||
- Prefer binding `--host` to a trusted private address, such as a Tailnet IP, instead of exposing the server broadly.
|
||||
- Anyone with a valid pairing credential can create a session until that credential expires or is revoked.
|
||||
- Use `t3 auth` to revoke credentials or sessions you no longer trust.
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.15",
|
||||
"version": "0.0.17",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -5,8 +5,17 @@ import { join } from "node:path";
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
import { waitForResources } from "./wait-for-resources.mjs";
|
||||
|
||||
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
|
||||
const devServerUrl = `http://localhost:${port}`;
|
||||
const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
|
||||
if (!devServerUrl) {
|
||||
throw new Error("VITE_DEV_SERVER_URL is required for desktop development.");
|
||||
}
|
||||
|
||||
const devServer = new URL(devServerUrl);
|
||||
const port = Number.parseInt(devServer.port, 10);
|
||||
if (!Number.isInteger(port) || port <= 0) {
|
||||
throw new Error(`VITE_DEV_SERVER_URL must include an explicit port: ${devServerUrl}`);
|
||||
}
|
||||
|
||||
const requiredFiles = [
|
||||
"dist-electron/main.js",
|
||||
"dist-electron/preload.js",
|
||||
@@ -23,6 +32,7 @@ const childTreeGracePeriodMs = 1_200;
|
||||
await waitForResources({
|
||||
baseDir: desktopDir,
|
||||
files: requiredFiles,
|
||||
tcpHost: devServer.hostname,
|
||||
tcpPort: port,
|
||||
});
|
||||
|
||||
@@ -62,10 +72,7 @@ function startApp() {
|
||||
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
|
||||
{
|
||||
cwd: desktopDir,
|
||||
env: {
|
||||
...childEnv,
|
||||
VITE_DEV_SERVER_URL: devServerUrl,
|
||||
},
|
||||
env: childEnv,
|
||||
stdio: "inherit",
|
||||
},
|
||||
);
|
||||
|
||||
@@ -18,7 +18,7 @@ import { fileURLToPath } from "node:url";
|
||||
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_BUNDLE_ID = "com.t3tools.t3code";
|
||||
const APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
|
||||
const LAUNCHER_VERSION = 1;
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { resolveDesktopBackendPort } from "./backendPort";
|
||||
|
||||
describe("resolveDesktopBackendPort", () => {
|
||||
it("returns the starting port when it is available", async () => {
|
||||
const canListenOnHost = vi.fn(async (port: number) => port === 3773);
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
startPort: 3773,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).resolves.toBe(3773);
|
||||
|
||||
expect(canListenOnHost).toHaveBeenCalledTimes(1);
|
||||
expect(canListenOnHost).toHaveBeenCalledWith(3773, "127.0.0.1");
|
||||
});
|
||||
|
||||
it("increments sequentially until it finds an available port", async () => {
|
||||
const canListenOnHost = vi.fn(async (port: number) => port === 3775);
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
startPort: 3773,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).resolves.toBe(3775);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[3773, "127.0.0.1"],
|
||||
[3774, "127.0.0.1"],
|
||||
[3775, "127.0.0.1"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("treats wildcard-bound ports as unavailable even when loopback probing succeeds", async () => {
|
||||
const canListenOnHost = vi.fn(async (port: number, host: string) => {
|
||||
if (port === 3773 && host === "127.0.0.1") return true;
|
||||
if (port === 3773 && host === "0.0.0.0") return false;
|
||||
return port === 3774;
|
||||
});
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
requiredHosts: ["0.0.0.0"],
|
||||
startPort: 3773,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).resolves.toBe(3774);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[3773, "127.0.0.1"],
|
||||
[3773, "0.0.0.0"],
|
||||
[3774, "127.0.0.1"],
|
||||
[3774, "0.0.0.0"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("checks overlapping hosts sequentially to avoid self-interference", async () => {
|
||||
let inFlightCount = 0;
|
||||
const canListenOnHost = vi.fn(async (_port: number, _host: string) => {
|
||||
inFlightCount += 1;
|
||||
const overlapped = inFlightCount > 1;
|
||||
await Promise.resolve();
|
||||
inFlightCount -= 1;
|
||||
return !overlapped;
|
||||
});
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
requiredHosts: ["0.0.0.0", "::"],
|
||||
startPort: 3773,
|
||||
maxPort: 3773,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).resolves.toBe(3773);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[3773, "127.0.0.1"],
|
||||
[3773, "0.0.0.0"],
|
||||
[3773, "::"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("fails when the scan range is exhausted", async () => {
|
||||
const canListenOnHost = vi.fn(async () => false);
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
startPort: 65534,
|
||||
maxPort: 65535,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
"No desktop backend port is available on hosts 127.0.0.1 between 65534 and 65535",
|
||||
);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[65534, "127.0.0.1"],
|
||||
[65535, "127.0.0.1"],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
export const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
|
||||
const MAX_TCP_PORT = 65_535;
|
||||
|
||||
export interface ResolveDesktopBackendPortOptions {
|
||||
readonly host: string;
|
||||
readonly startPort?: number;
|
||||
readonly maxPort?: number;
|
||||
readonly requiredHosts?: ReadonlyArray<string>;
|
||||
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;
|
||||
|
||||
const normalizeHosts = (
|
||||
host: string,
|
||||
requiredHosts: ReadonlyArray<string>,
|
||||
): ReadonlyArray<string> =>
|
||||
Array.from(
|
||||
new Set(
|
||||
[host, ...requiredHosts]
|
||||
.map((candidate) => candidate.trim())
|
||||
.filter((candidate) => candidate.length > 0),
|
||||
),
|
||||
);
|
||||
|
||||
async function canListenOnAllHosts(
|
||||
port: number,
|
||||
hosts: ReadonlyArray<string>,
|
||||
canListenOnHost: (port: number, host: string) => Promise<boolean>,
|
||||
): Promise<boolean> {
|
||||
for (const candidateHost of hosts) {
|
||||
if (!(await canListenOnHost(port, candidateHost))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function resolveDesktopBackendPort({
|
||||
host,
|
||||
startPort = DEFAULT_DESKTOP_BACKEND_PORT,
|
||||
maxPort = MAX_TCP_PORT,
|
||||
requiredHosts = [],
|
||||
canListenOnHost = defaultCanListenOnHost,
|
||||
}: ResolveDesktopBackendPortOptions): Promise<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}`);
|
||||
}
|
||||
|
||||
const hostsToCheck = normalizeHosts(host, requiredHosts);
|
||||
|
||||
// Keep desktop startup predictable across app restarts by probing upward from
|
||||
// the same preferred port instead of picking a fresh ephemeral port.
|
||||
for (let port = startPort; port <= maxPort; port += 1) {
|
||||
if (await canListenOnAllHosts(port, hostsToCheck, canListenOnHost)) {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`No desktop backend port is available on hosts ${hostsToCheck.join(", ")} between ${startPort} and ${maxPort}`,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
BackendReadinessAbortedError,
|
||||
isBackendReadinessAborted,
|
||||
waitForHttpReady,
|
||||
} from "./backendReadiness";
|
||||
|
||||
describe("waitForHttpReady", () => {
|
||||
it("returns once the backend reports a successful session endpoint", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn<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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
export interface WaitForHttpReadyOptions {
|
||||
readonly timeoutMs?: number;
|
||||
readonly intervalMs?: number;
|
||||
readonly requestTimeoutMs?: number;
|
||||
readonly fetchImpl?: typeof fetch;
|
||||
readonly signal?: AbortSignal;
|
||||
}
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
|
||||
import {
|
||||
EnvironmentId,
|
||||
type ClientSettings,
|
||||
type PersistedSavedEnvironmentRecord,
|
||||
} from "@t3tools/contracts";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
readClientSettings,
|
||||
readSavedEnvironmentRegistry,
|
||||
readSavedEnvironmentSecret,
|
||||
removeSavedEnvironmentSecret,
|
||||
writeClientSettings,
|
||||
writeSavedEnvironmentRegistry,
|
||||
writeSavedEnvironmentSecret,
|
||||
type DesktopSecretStorage,
|
||||
} from "./clientPersistence";
|
||||
|
||||
const tempDirectories: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const directory of tempDirectories.splice(0)) {
|
||||
fs.rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function makeTempPath(fileName: string): string {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "t3-client-persistence-test-"));
|
||||
tempDirectories.push(directory);
|
||||
return path.join(directory, fileName);
|
||||
}
|
||||
|
||||
function makeSecretStorage(available: boolean): DesktopSecretStorage {
|
||||
return {
|
||||
isEncryptionAvailable: () => available,
|
||||
encryptString: (value) => Buffer.from(`enc:${value}`, "utf8"),
|
||||
decryptString: (value) => {
|
||||
const decoded = value.toString("utf8");
|
||||
if (!decoded.startsWith("enc:")) {
|
||||
throw new Error("invalid secret");
|
||||
}
|
||||
return decoded.slice("enc:".length);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const clientSettings: ClientSettings = {
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
diffWordWrap: true,
|
||||
sidebarProjectSortOrder: "manual",
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
timestampFormat: "24-hour",
|
||||
};
|
||||
|
||||
const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
label: "Remote environment",
|
||||
httpBaseUrl: "https://remote.example.com/",
|
||||
wsBaseUrl: "wss://remote.example.com/",
|
||||
createdAt: "2026-04-09T00:00:00.000Z",
|
||||
lastConnectedAt: "2026-04-09T01:00:00.000Z",
|
||||
};
|
||||
|
||||
describe("clientPersistence", () => {
|
||||
it("persists and reloads client settings", () => {
|
||||
const settingsPath = makeTempPath("client-settings.json");
|
||||
|
||||
writeClientSettings(settingsPath, clientSettings);
|
||||
|
||||
expect(readClientSettings(settingsPath)).toEqual(clientSettings);
|
||||
});
|
||||
|
||||
it("persists and reloads saved environment metadata", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
expect(readSavedEnvironmentRegistry(registryPath)).toEqual([savedRegistryRecord]);
|
||||
});
|
||||
|
||||
it("persists encrypted saved environment secrets when encryption is available", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
const secretStorage = makeSecretStorage(true);
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
expect(
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "bearer-token",
|
||||
secretStorage,
|
||||
}),
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
readSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secretStorage,
|
||||
}),
|
||||
).toBe("bearer-token");
|
||||
|
||||
expect(JSON.parse(fs.readFileSync(registryPath, "utf8"))).toEqual({
|
||||
records: [
|
||||
{
|
||||
...savedRegistryRecord,
|
||||
encryptedBearerToken: Buffer.from("enc:bearer-token", "utf8").toString("base64"),
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves existing secrets when encryption is unavailable", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
const availableSecretStorage = makeSecretStorage(true);
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "bearer-token",
|
||||
secretStorage: availableSecretStorage,
|
||||
});
|
||||
|
||||
expect(
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "next-token",
|
||||
secretStorage: makeSecretStorage(false),
|
||||
}),
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
readSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secretStorage: availableSecretStorage,
|
||||
}),
|
||||
).toBe("bearer-token");
|
||||
});
|
||||
|
||||
it("removes saved environment secrets", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
const secretStorage = makeSecretStorage(true);
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "bearer-token",
|
||||
secretStorage,
|
||||
});
|
||||
|
||||
removeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
});
|
||||
|
||||
expect(
|
||||
readSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secretStorage,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("treats malformed secrets documents as empty", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
fs.writeFileSync(registryPath, "{}\n", "utf8");
|
||||
|
||||
expect(
|
||||
readSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secretStorage: makeSecretStorage(true),
|
||||
}),
|
||||
).toBeNull();
|
||||
|
||||
expect(() =>
|
||||
removeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it("returns false when writing a secret without metadata", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
|
||||
expect(
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "bearer-token",
|
||||
secretStorage: makeSecretStorage(true),
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("preserves encrypted secrets when metadata is rewritten", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
const secretStorage = makeSecretStorage(true);
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "bearer-token",
|
||||
secretStorage,
|
||||
});
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
expect(readSavedEnvironmentRegistry(registryPath)).toEqual([savedRegistryRecord]);
|
||||
expect(
|
||||
readSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secretStorage,
|
||||
}),
|
||||
).toBe("bearer-token");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,216 @@
|
||||
import * as FS from "node:fs";
|
||||
import * as Path from "node:path";
|
||||
|
||||
import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
|
||||
import { Predicate } from "effect";
|
||||
|
||||
interface ClientSettingsDocument {
|
||||
readonly settings: ClientSettings;
|
||||
}
|
||||
|
||||
interface PersistedSavedEnvironmentStorageRecord extends PersistedSavedEnvironmentRecord {
|
||||
readonly encryptedBearerToken?: string;
|
||||
}
|
||||
|
||||
interface SavedEnvironmentRegistryDocument {
|
||||
readonly records: readonly PersistedSavedEnvironmentStorageRecord[];
|
||||
}
|
||||
|
||||
export interface DesktopSecretStorage {
|
||||
readonly isEncryptionAvailable: () => boolean;
|
||||
readonly encryptString: (value: string) => Buffer;
|
||||
readonly decryptString: (value: Buffer) => string;
|
||||
}
|
||||
|
||||
function readJsonFile<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);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
DEFAULT_DESKTOP_SETTINGS,
|
||||
readDesktopSettings,
|
||||
setDesktopServerExposurePreference,
|
||||
writeDesktopSettings,
|
||||
} from "./desktopSettings";
|
||||
|
||||
const tempDirectories: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const directory of tempDirectories.splice(0)) {
|
||||
fs.rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function makeSettingsPath() {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "t3-desktop-settings-test-"));
|
||||
tempDirectories.push(directory);
|
||||
return path.join(directory, "desktop-settings.json");
|
||||
}
|
||||
|
||||
describe("desktopSettings", () => {
|
||||
it("returns defaults when no settings file exists", () => {
|
||||
expect(readDesktopSettings(makeSettingsPath())).toEqual(DEFAULT_DESKTOP_SETTINGS);
|
||||
});
|
||||
|
||||
it("persists and reloads the configured server exposure mode", () => {
|
||||
const settingsPath = makeSettingsPath();
|
||||
|
||||
writeDesktopSettings(settingsPath, {
|
||||
serverExposureMode: "network-accessible",
|
||||
});
|
||||
|
||||
expect(readDesktopSettings(settingsPath)).toEqual({
|
||||
serverExposureMode: "network-accessible",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves the requested network-accessible preference across temporary fallback", () => {
|
||||
expect(
|
||||
setDesktopServerExposurePreference(
|
||||
{
|
||||
serverExposureMode: "local-only",
|
||||
},
|
||||
"network-accessible",
|
||||
),
|
||||
).toEqual({
|
||||
serverExposureMode: "network-accessible",
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to defaults when the settings file is malformed", () => {
|
||||
const settingsPath = makeSettingsPath();
|
||||
fs.writeFileSync(settingsPath, "{not-json", "utf8");
|
||||
|
||||
expect(readDesktopSettings(settingsPath)).toEqual(DEFAULT_DESKTOP_SETTINGS);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import * as FS from "node:fs";
|
||||
import * as Path from "node:path";
|
||||
import type { DesktopServerExposureMode } from "@t3tools/contracts";
|
||||
|
||||
export interface DesktopSettings {
|
||||
readonly serverExposureMode: DesktopServerExposureMode;
|
||||
}
|
||||
|
||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
serverExposureMode: "local-only",
|
||||
};
|
||||
|
||||
export function setDesktopServerExposurePreference(
|
||||
settings: DesktopSettings,
|
||||
requestedMode: DesktopServerExposureMode,
|
||||
): DesktopSettings {
|
||||
return settings.serverExposureMode === requestedMode
|
||||
? settings
|
||||
: {
|
||||
...settings,
|
||||
serverExposureMode: requestedMode,
|
||||
};
|
||||
}
|
||||
|
||||
export function readDesktopSettings(settingsPath: string): DesktopSettings {
|
||||
try {
|
||||
if (!FS.existsSync(settingsPath)) {
|
||||
return DEFAULT_DESKTOP_SETTINGS;
|
||||
}
|
||||
|
||||
const raw = FS.readFileSync(settingsPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as {
|
||||
readonly serverExposureMode?: unknown;
|
||||
};
|
||||
|
||||
return {
|
||||
serverExposureMode:
|
||||
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
|
||||
};
|
||||
} catch {
|
||||
return DEFAULT_DESKTOP_SETTINGS;
|
||||
}
|
||||
}
|
||||
|
||||
export function writeDesktopSettings(settingsPath: string, settings: DesktopSettings): void {
|
||||
const directory = Path.dirname(settingsPath);
|
||||
const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`;
|
||||
FS.mkdirSync(directory, { recursive: true });
|
||||
FS.writeFileSync(tempPath, `${JSON.stringify(settings, null, 2)}\n`, "utf8");
|
||||
FS.renameSync(tempPath, settingsPath);
|
||||
}
|
||||
+528
-45
@@ -7,18 +7,24 @@ import * as Path from "node:path";
|
||||
import {
|
||||
app,
|
||||
BrowserWindow,
|
||||
type BrowserWindowConstructorOptions,
|
||||
clipboard,
|
||||
dialog,
|
||||
ipcMain,
|
||||
Menu,
|
||||
nativeImage,
|
||||
nativeTheme,
|
||||
protocol,
|
||||
safeStorage,
|
||||
shell,
|
||||
} from "electron";
|
||||
import type { MenuItemConstructorOptions } from "electron";
|
||||
import * as Effect from "effect/Effect";
|
||||
import type {
|
||||
ClientSettings,
|
||||
DesktopTheme,
|
||||
DesktopServerExposureMode,
|
||||
DesktopServerExposureState,
|
||||
PersistedSavedEnvironmentRecord,
|
||||
DesktopUpdateActionResult,
|
||||
DesktopUpdateCheckResult,
|
||||
DesktopUpdateState,
|
||||
@@ -26,9 +32,27 @@ import type {
|
||||
import { autoUpdater } from "electron-updater";
|
||||
|
||||
import type { ContextMenuItem } from "@t3tools/contracts";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
|
||||
import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort";
|
||||
import {
|
||||
DEFAULT_DESKTOP_SETTINGS,
|
||||
readDesktopSettings,
|
||||
setDesktopServerExposurePreference,
|
||||
writeDesktopSettings,
|
||||
} from "./desktopSettings";
|
||||
import {
|
||||
readClientSettings,
|
||||
readSavedEnvironmentRegistry,
|
||||
readSavedEnvironmentSecret,
|
||||
removeSavedEnvironmentSecret,
|
||||
writeClientSettings,
|
||||
writeSavedEnvironmentRegistry,
|
||||
writeSavedEnvironmentSecret,
|
||||
} from "./clientPersistence";
|
||||
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness";
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
import { resolveDesktopServerExposure } from "./serverExposure";
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment";
|
||||
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
|
||||
import {
|
||||
@@ -58,14 +82,26 @@ const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
||||
const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
|
||||
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
|
||||
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
|
||||
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
|
||||
const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
|
||||
const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
|
||||
const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
|
||||
const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
|
||||
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
|
||||
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
|
||||
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
|
||||
const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
|
||||
const STATE_DIR = Path.join(BASE_DIR, "userdata");
|
||||
const DESKTOP_SETTINGS_PATH = Path.join(STATE_DIR, "desktop-settings.json");
|
||||
const CLIENT_SETTINGS_PATH = Path.join(STATE_DIR, "client-settings.json");
|
||||
const SAVED_ENVIRONMENT_REGISTRY_PATH = Path.join(STATE_DIR, "saved-environments.json");
|
||||
const DESKTOP_SCHEME = "t3";
|
||||
const ROOT_DIR = Path.resolve(__dirname, "../../..");
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_USER_MODEL_ID = "com.t3tools.t3code";
|
||||
const APP_USER_MODEL_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
|
||||
const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop";
|
||||
const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code";
|
||||
const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";
|
||||
@@ -76,10 +112,22 @@ const LOG_DIR = Path.join(STATE_DIR, "logs");
|
||||
const LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||
const LOG_FILE_MAX_FILES = 10;
|
||||
const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
|
||||
const SERVER_SETTINGS_PATH = Path.join(STATE_DIR, "settings.json");
|
||||
const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
|
||||
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
|
||||
const DESKTOP_UPDATE_CHANNEL = "latest";
|
||||
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
|
||||
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
|
||||
const DESKTOP_REQUIRED_PORT_PROBE_HOSTS = ["0.0.0.0", "::"] as const;
|
||||
const TITLEBAR_HEIGHT = 40;
|
||||
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
|
||||
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
|
||||
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
|
||||
|
||||
type WindowTitleBarOptions = Pick<
|
||||
BrowserWindowConstructorOptions,
|
||||
"titleBarOverlay" | "titleBarStyle" | "trafficLightPosition"
|
||||
>;
|
||||
|
||||
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
|
||||
type LinuxDesktopNamedApp = Electron.App & {
|
||||
@@ -89,8 +137,13 @@ type LinuxDesktopNamedApp = Electron.App & {
|
||||
let mainWindow: BrowserWindow | null = null;
|
||||
let backendProcess: ChildProcess.ChildProcess | null = null;
|
||||
let backendPort = 0;
|
||||
let backendAuthToken = "";
|
||||
let backendBindHost = DESKTOP_LOOPBACK_HOST;
|
||||
let backendBootstrapToken = "";
|
||||
let backendHttpUrl = "";
|
||||
let backendWsUrl = "";
|
||||
let backendEndpointUrl: string | null = null;
|
||||
let backendAdvertisedHost: string | null = null;
|
||||
let backendReadinessAbortController: AbortController | null = null;
|
||||
let restartAttempt = 0;
|
||||
let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let isQuitting = false;
|
||||
@@ -99,8 +152,12 @@ let aboutCommitHashCache: string | null | undefined;
|
||||
let desktopLogSink: RotatingFileSink | null = null;
|
||||
let backendLogSink: RotatingFileSink | null = null;
|
||||
let restoreStdIoCapture: (() => void) | null = null;
|
||||
let backendObservabilitySettings = readPersistedBackendObservabilitySettings();
|
||||
let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH);
|
||||
let desktopServerExposureMode: DesktopServerExposureMode = desktopSettings.serverExposureMode;
|
||||
|
||||
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
|
||||
const expectedBackendExitChildren = new WeakSet<ChildProcess.ChildProcess>();
|
||||
const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
|
||||
platform: process.platform,
|
||||
processArch: process.arch,
|
||||
@@ -121,17 +178,143 @@ function sanitizeLogValue(value: string): string {
|
||||
return value.replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
function readPersistedBackendObservabilitySettings(): {
|
||||
readonly otlpTracesUrl: string | undefined;
|
||||
readonly otlpMetricsUrl: string | undefined;
|
||||
} {
|
||||
try {
|
||||
if (!FS.existsSync(SERVER_SETTINGS_PATH)) {
|
||||
return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
|
||||
}
|
||||
return parsePersistedServerObservabilitySettings(FS.readFileSync(SERVER_SETTINGS_PATH, "utf8"));
|
||||
} catch (error) {
|
||||
console.warn("[desktop] failed to read persisted backend observability settings", error);
|
||||
return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
|
||||
}
|
||||
}
|
||||
|
||||
function resolveConfiguredDesktopBackendPort(rawPort: string | undefined): number | undefined {
|
||||
if (!rawPort) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const parsedPort = Number.parseInt(rawPort, 10);
|
||||
if (!Number.isInteger(parsedPort) || parsedPort < 1 || parsedPort > 65_535) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return parsedPort;
|
||||
}
|
||||
|
||||
function resolveDesktopDevServerUrl(): string {
|
||||
const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
|
||||
if (!devServerUrl) {
|
||||
throw new Error("VITE_DEV_SERVER_URL is required in desktop development.");
|
||||
}
|
||||
|
||||
return devServerUrl;
|
||||
}
|
||||
|
||||
function backendChildEnv(): NodeJS.ProcessEnv {
|
||||
const env = { ...process.env };
|
||||
delete env.T3CODE_PORT;
|
||||
delete env.T3CODE_AUTH_TOKEN;
|
||||
delete env.T3CODE_MODE;
|
||||
delete env.T3CODE_NO_BROWSER;
|
||||
delete env.T3CODE_HOST;
|
||||
delete env.T3CODE_DESKTOP_WS_URL;
|
||||
delete env.T3CODE_DESKTOP_LAN_ACCESS;
|
||||
delete env.T3CODE_DESKTOP_LAN_HOST;
|
||||
return env;
|
||||
}
|
||||
|
||||
function getDesktopServerExposureState(): DesktopServerExposureState {
|
||||
return {
|
||||
mode: desktopServerExposureMode,
|
||||
endpointUrl: backendEndpointUrl,
|
||||
advertisedHost: backendAdvertisedHost,
|
||||
};
|
||||
}
|
||||
|
||||
function getDesktopSecretStorage() {
|
||||
return {
|
||||
isEncryptionAvailable: () => safeStorage.isEncryptionAvailable(),
|
||||
encryptString: (value: string) => safeStorage.encryptString(value),
|
||||
decryptString: (value: Buffer) => safeStorage.decryptString(value),
|
||||
} as const;
|
||||
}
|
||||
|
||||
function resolveAdvertisedHostOverride(): string | undefined {
|
||||
const override = process.env.T3CODE_DESKTOP_LAN_HOST?.trim();
|
||||
return override && override.length > 0 ? override : undefined;
|
||||
}
|
||||
|
||||
async function applyDesktopServerExposureMode(
|
||||
mode: DesktopServerExposureMode,
|
||||
options?: { readonly persist?: boolean; readonly rejectIfUnavailable?: boolean },
|
||||
): Promise<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`);
|
||||
@@ -179,6 +362,27 @@ 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,
|
||||
@@ -523,10 +727,7 @@ function dispatchMenuAction(action: string): void {
|
||||
const send = () => {
|
||||
if (targetWindow.isDestroyed()) return;
|
||||
targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
|
||||
if (!targetWindow.isVisible()) {
|
||||
targetWindow.show();
|
||||
}
|
||||
targetWindow.focus();
|
||||
revealWindow(targetWindow);
|
||||
};
|
||||
|
||||
if (targetWindow.webContents.isLoadingMainFrame()) {
|
||||
@@ -538,12 +739,15 @@ function dispatchMenuAction(action: string): void {
|
||||
}
|
||||
|
||||
function handleCheckForUpdatesMenuClick(): void {
|
||||
const hasUpdateFeedConfig =
|
||||
readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES);
|
||||
const disabledReason = getAutoUpdateDisabledReason({
|
||||
isDevelopment,
|
||||
isPackaged: app.isPackaged,
|
||||
platform: process.platform,
|
||||
appImage: process.env.APPIMAGE,
|
||||
disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
|
||||
hasUpdateFeedConfig,
|
||||
});
|
||||
if (disabledReason) {
|
||||
console.info("[desktop-updater] Manual update check requested, but updates are disabled.");
|
||||
@@ -747,6 +951,26 @@ function clearUpdatePollTimer(): void {
|
||||
}
|
||||
}
|
||||
|
||||
function revealWindow(window: BrowserWindow): void {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.isMinimized()) {
|
||||
window.restore();
|
||||
}
|
||||
|
||||
if (!window.isVisible()) {
|
||||
window.show();
|
||||
}
|
||||
|
||||
if (process.platform === "darwin") {
|
||||
app.focus({ steal: true });
|
||||
}
|
||||
|
||||
window.focus();
|
||||
}
|
||||
|
||||
function emitUpdateState(): void {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (window.isDestroyed()) continue;
|
||||
@@ -760,6 +984,8 @@ function setUpdateState(patch: Partial<DesktopUpdateState>): void {
|
||||
}
|
||||
|
||||
function shouldEnableAutoUpdates(): boolean {
|
||||
const hasUpdateFeedConfig =
|
||||
readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES);
|
||||
return (
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment,
|
||||
@@ -767,6 +993,7 @@ function shouldEnableAutoUpdates(): boolean {
|
||||
platform: process.platform,
|
||||
appImage: process.env.APPIMAGE,
|
||||
disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
|
||||
hasUpdateFeedConfig,
|
||||
}) === null
|
||||
);
|
||||
}
|
||||
@@ -850,17 +1077,6 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed
|
||||
}
|
||||
|
||||
function configureAutoUpdater(): void {
|
||||
const enabled = shouldEnableAutoUpdates();
|
||||
setUpdateState({
|
||||
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
|
||||
enabled,
|
||||
status: enabled ? "idle" : "disabled",
|
||||
});
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
updaterConfigured = true;
|
||||
|
||||
const githubToken =
|
||||
process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || "";
|
||||
if (githubToken) {
|
||||
@@ -885,6 +1101,17 @@ function configureAutoUpdater(): void {
|
||||
});
|
||||
}
|
||||
|
||||
const enabled = shouldEnableAutoUpdates();
|
||||
setUpdateState({
|
||||
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
|
||||
enabled,
|
||||
status: enabled ? "idle" : "disabled",
|
||||
});
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
updaterConfigured = true;
|
||||
|
||||
autoUpdater.autoDownload = false;
|
||||
autoUpdater.autoInstallOnAppQuit = false;
|
||||
// Keep alpha branding, but force all installs onto the stable update track.
|
||||
@@ -988,6 +1215,7 @@ function scheduleBackendRestart(reason: string): void {
|
||||
function startBackend(): void {
|
||||
if (isQuitting || backendProcess) return;
|
||||
|
||||
backendObservabilitySettings = readPersistedBackendObservabilitySettings();
|
||||
const backendEntry = resolveBackendEntry();
|
||||
if (!FS.existsSync(backendEntry)) {
|
||||
scheduleBackendRestart(`missing server entry at ${backendEntry}`);
|
||||
@@ -1015,7 +1243,14 @@ function startBackend(): void {
|
||||
noBrowser: true,
|
||||
port: backendPort,
|
||||
t3Home: BASE_DIR,
|
||||
authToken: backendAuthToken,
|
||||
host: backendBindHost,
|
||||
desktopBootstrapToken: backendBootstrapToken,
|
||||
...(backendObservabilitySettings.otlpTracesUrl
|
||||
? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl }
|
||||
: {}),
|
||||
...(backendObservabilitySettings.otlpMetricsUrl
|
||||
? { otlpMetricsUrl: backendObservabilitySettings.otlpMetricsUrl }
|
||||
: {}),
|
||||
})}\n`,
|
||||
);
|
||||
bootstrapStream.end();
|
||||
@@ -1042,27 +1277,33 @@ function startBackend(): void {
|
||||
});
|
||||
|
||||
child.on("error", (error) => {
|
||||
const wasExpected = expectedBackendExitChildren.has(child);
|
||||
if (backendProcess === child) {
|
||||
backendProcess = null;
|
||||
}
|
||||
closeBackendSession(`pid=${child.pid ?? "unknown"} error=${error.message}`);
|
||||
if (wasExpected) {
|
||||
return;
|
||||
}
|
||||
scheduleBackendRestart(error.message);
|
||||
});
|
||||
|
||||
child.on("exit", (code, signal) => {
|
||||
const wasExpected = expectedBackendExitChildren.has(child);
|
||||
if (backendProcess === child) {
|
||||
backendProcess = null;
|
||||
}
|
||||
closeBackendSession(
|
||||
`pid=${child.pid ?? "unknown"} code=${code ?? "null"} signal=${signal ?? "null"}`,
|
||||
);
|
||||
if (isQuitting) return;
|
||||
if (isQuitting || wasExpected) return;
|
||||
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
|
||||
scheduleBackendRestart(reason);
|
||||
});
|
||||
}
|
||||
|
||||
function stopBackend(): void {
|
||||
cancelBackendReadinessWait();
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
restartTimer = null;
|
||||
@@ -1073,6 +1314,7 @@ function stopBackend(): void {
|
||||
if (!child) return;
|
||||
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
expectedBackendExitChildren.add(child);
|
||||
child.kill("SIGTERM");
|
||||
setTimeout(() => {
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
@@ -1083,6 +1325,7 @@ function stopBackend(): void {
|
||||
}
|
||||
|
||||
async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
|
||||
cancelBackendReadinessWait();
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
restartTimer = null;
|
||||
@@ -1093,6 +1336,7 @@ 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;
|
||||
@@ -1134,9 +1378,116 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
|
||||
}
|
||||
|
||||
function registerIpcHandlers(): void {
|
||||
ipcMain.removeAllListeners(GET_WS_URL_CHANNEL);
|
||||
ipcMain.on(GET_WS_URL_CHANNEL, (event) => {
|
||||
event.returnValue = backendWsUrl;
|
||||
ipcMain.removeAllListeners(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
|
||||
ipcMain.on(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL, (event) => {
|
||||
event.returnValue = {
|
||||
label: "Local environment",
|
||||
httpBaseUrl: backendHttpUrl || null,
|
||||
wsBaseUrl: backendWsUrl || null,
|
||||
bootstrapToken: backendBootstrapToken || undefined,
|
||||
} as const;
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(GET_CLIENT_SETTINGS_CHANNEL);
|
||||
ipcMain.handle(GET_CLIENT_SETTINGS_CHANNEL, async () => readClientSettings(CLIENT_SETTINGS_PATH));
|
||||
|
||||
ipcMain.removeHandler(SET_CLIENT_SETTINGS_CHANNEL);
|
||||
ipcMain.handle(SET_CLIENT_SETTINGS_CHANNEL, async (_event, rawSettings: unknown) => {
|
||||
if (typeof rawSettings !== "object" || rawSettings === null) {
|
||||
throw new Error("Invalid client settings payload.");
|
||||
}
|
||||
|
||||
writeClientSettings(CLIENT_SETTINGS_PATH, rawSettings as ClientSettings);
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL);
|
||||
ipcMain.handle(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, async () =>
|
||||
readSavedEnvironmentRegistry(SAVED_ENVIRONMENT_REGISTRY_PATH),
|
||||
);
|
||||
|
||||
ipcMain.removeHandler(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL);
|
||||
ipcMain.handle(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, async (_event, rawRecords: unknown) => {
|
||||
if (!Array.isArray(rawRecords)) {
|
||||
throw new Error("Invalid saved environment registry payload.");
|
||||
}
|
||||
|
||||
writeSavedEnvironmentRegistry(
|
||||
SAVED_ENVIRONMENT_REGISTRY_PATH,
|
||||
rawRecords as readonly PersistedSavedEnvironmentRecord[],
|
||||
);
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(GET_SAVED_ENVIRONMENT_SECRET_CHANNEL);
|
||||
ipcMain.handle(
|
||||
GET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
|
||||
async (_event, rawEnvironmentId: unknown) => {
|
||||
if (typeof rawEnvironmentId !== "string" || rawEnvironmentId.trim().length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return readSavedEnvironmentSecret({
|
||||
registryPath: SAVED_ENVIRONMENT_REGISTRY_PATH,
|
||||
environmentId: rawEnvironmentId,
|
||||
secretStorage: getDesktopSecretStorage(),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
ipcMain.removeHandler(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL);
|
||||
ipcMain.handle(
|
||||
SET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
|
||||
async (_event, rawEnvironmentId: unknown, rawSecret: unknown) => {
|
||||
if (typeof rawEnvironmentId !== "string" || rawEnvironmentId.trim().length === 0) {
|
||||
throw new Error("Invalid saved environment id.");
|
||||
}
|
||||
if (typeof rawSecret !== "string" || rawSecret.trim().length === 0) {
|
||||
throw new Error("Invalid saved environment secret.");
|
||||
}
|
||||
|
||||
return writeSavedEnvironmentSecret({
|
||||
registryPath: SAVED_ENVIRONMENT_REGISTRY_PATH,
|
||||
environmentId: rawEnvironmentId,
|
||||
secret: rawSecret,
|
||||
secretStorage: getDesktopSecretStorage(),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
ipcMain.removeHandler(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL);
|
||||
ipcMain.handle(
|
||||
REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL,
|
||||
async (_event, rawEnvironmentId: unknown) => {
|
||||
if (typeof rawEnvironmentId !== "string" || rawEnvironmentId.trim().length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
removeSavedEnvironmentSecret({
|
||||
registryPath: SAVED_ENVIRONMENT_REGISTRY_PATH,
|
||||
environmentId: rawEnvironmentId,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
ipcMain.removeHandler(GET_SERVER_EXPOSURE_STATE_CHANNEL);
|
||||
ipcMain.handle(GET_SERVER_EXPOSURE_STATE_CHANNEL, async () => getDesktopServerExposureState());
|
||||
|
||||
ipcMain.removeHandler(SET_SERVER_EXPOSURE_MODE_CHANNEL);
|
||||
ipcMain.handle(SET_SERVER_EXPOSURE_MODE_CHANNEL, async (_event, rawMode: unknown) => {
|
||||
if (rawMode !== "local-only" && rawMode !== "network-accessible") {
|
||||
throw new Error("Invalid desktop server exposure input.");
|
||||
}
|
||||
|
||||
const nextMode = rawMode as DesktopServerExposureMode;
|
||||
if (nextMode === desktopServerExposureMode) {
|
||||
return getDesktopServerExposureState();
|
||||
}
|
||||
|
||||
const nextState = await applyDesktopServerExposureMode(nextMode, {
|
||||
persist: true,
|
||||
rejectIfUnavailable: true,
|
||||
});
|
||||
relaunchDesktopApp(`serverExposureMode=${nextMode}`);
|
||||
return nextState;
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
|
||||
@@ -1304,18 +1655,62 @@ function getIconOption(): { icon: string } | Record<string, never> {
|
||||
return iconPath ? { icon: iconPath } : {};
|
||||
}
|
||||
|
||||
function getInitialWindowBackgroundColor(): string {
|
||||
return nativeTheme.shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
|
||||
}
|
||||
|
||||
function getWindowTitleBarOptions(): WindowTitleBarOptions {
|
||||
if (process.platform === "darwin") {
|
||||
return {
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
titleBarStyle: "hidden",
|
||||
titleBarOverlay: {
|
||||
color: TITLEBAR_COLOR,
|
||||
height: TITLEBAR_HEIGHT,
|
||||
symbolColor: nativeTheme.shouldUseDarkColors
|
||||
? TITLEBAR_DARK_SYMBOL_COLOR
|
||||
: TITLEBAR_LIGHT_SYMBOL_COLOR,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function syncWindowAppearance(window: BrowserWindow): void {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.setBackgroundColor(getInitialWindowBackgroundColor());
|
||||
const { titleBarOverlay } = getWindowTitleBarOptions();
|
||||
if (typeof titleBarOverlay === "object") {
|
||||
window.setTitleBarOverlay(titleBarOverlay);
|
||||
}
|
||||
}
|
||||
|
||||
function syncAllWindowAppearance(): void {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
syncWindowAppearance(window);
|
||||
}
|
||||
}
|
||||
|
||||
nativeTheme.on("updated", syncAllWindowAppearance);
|
||||
|
||||
function createWindow(): BrowserWindow {
|
||||
const window = new BrowserWindow({
|
||||
width: 1100,
|
||||
height: 780,
|
||||
minWidth: 840,
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
show: isDevelopment,
|
||||
autoHideMenuBar: true,
|
||||
backgroundColor: getInitialWindowBackgroundColor(),
|
||||
...getIconOption(),
|
||||
title: APP_DISPLAY_NAME,
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
...getWindowTitleBarOptions(),
|
||||
webPreferences: {
|
||||
preload: Path.join(__dirname, "preload.js"),
|
||||
contextIsolation: true,
|
||||
@@ -1342,6 +1737,22 @@ function createWindow(): BrowserWindow {
|
||||
menuTemplate.push({ type: "separator" });
|
||||
}
|
||||
|
||||
const externalUrl = getSafeExternalUrl(params.linkURL);
|
||||
if (externalUrl) {
|
||||
menuTemplate.push(
|
||||
{ label: "Copy Link", click: () => clipboard.writeText(params.linkURL) },
|
||||
{ type: "separator" },
|
||||
);
|
||||
}
|
||||
|
||||
if (params.mediaType === "image") {
|
||||
menuTemplate.push({
|
||||
label: "Copy Image",
|
||||
click: () => window.webContents.copyImageAt(params.x, params.y),
|
||||
});
|
||||
menuTemplate.push({ type: "separator" });
|
||||
}
|
||||
|
||||
menuTemplate.push(
|
||||
{ role: "cut", enabled: params.editFlags.canCut },
|
||||
{ role: "copy", enabled: params.editFlags.canCopy },
|
||||
@@ -1368,15 +1779,20 @@ function createWindow(): BrowserWindow {
|
||||
window.setTitle(APP_DISPLAY_NAME);
|
||||
emitUpdateState();
|
||||
});
|
||||
window.once("ready-to-show", () => {
|
||||
window.show();
|
||||
});
|
||||
if (!isDevelopment) {
|
||||
window.once("ready-to-show", () => {
|
||||
revealWindow(window);
|
||||
});
|
||||
}
|
||||
|
||||
if (isDevelopment) {
|
||||
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
|
||||
void window.loadURL(resolveDesktopDevServerUrl());
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
setImmediate(() => {
|
||||
revealWindow(window);
|
||||
});
|
||||
} else {
|
||||
void window.loadURL(`${DESKTOP_SCHEME}://app/index.html`);
|
||||
void window.loadURL(resolveDesktopWindowUrl());
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
@@ -1388,6 +1804,14 @@ function createWindow(): BrowserWindow {
|
||||
return window;
|
||||
}
|
||||
|
||||
function resolveDesktopWindowUrl(): string {
|
||||
if (backendHttpUrl) {
|
||||
return backendHttpUrl;
|
||||
}
|
||||
|
||||
return `${DESKTOP_SCHEME}://app`;
|
||||
}
|
||||
|
||||
// Override Electron's userData path before the `ready` event so that
|
||||
// Chromium session data uses a filesystem-friendly directory name.
|
||||
// Must be called synchronously at the top level — before `app.whenReady()`.
|
||||
@@ -1397,21 +1821,72 @@ configureAppIdentity();
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
writeDesktopLogHeader("bootstrap start");
|
||||
backendPort = await Effect.service(NetService).pipe(
|
||||
Effect.flatMap((net) => net.reserveLoopbackPort()),
|
||||
Effect.provide(NetService.layer),
|
||||
Effect.runPromise,
|
||||
const configuredBackendPort = resolveConfiguredDesktopBackendPort(process.env.T3CODE_PORT);
|
||||
if (isDevelopment && configuredBackendPort === undefined) {
|
||||
throw new Error("T3CODE_PORT is required in desktop development.");
|
||||
}
|
||||
|
||||
backendPort =
|
||||
configuredBackendPort ??
|
||||
(await resolveDesktopBackendPort({
|
||||
host: DESKTOP_LOOPBACK_HOST,
|
||||
startPort: DEFAULT_DESKTOP_BACKEND_PORT,
|
||||
requiredHosts: DESKTOP_REQUIRED_PORT_PROBE_HOSTS,
|
||||
}));
|
||||
writeDesktopLogHeader(
|
||||
configuredBackendPort === undefined
|
||||
? `selected backend port via sequential scan startPort=${DEFAULT_DESKTOP_BACKEND_PORT} port=${backendPort}`
|
||||
: `using configured backend port port=${backendPort}`,
|
||||
);
|
||||
writeDesktopLogHeader(`reserved backend port via NetService port=${backendPort}`);
|
||||
backendAuthToken = Crypto.randomBytes(24).toString("hex");
|
||||
const baseUrl = `ws://127.0.0.1:${backendPort}`;
|
||||
backendWsUrl = `${baseUrl}/?token=${encodeURIComponent(backendAuthToken)}`;
|
||||
writeDesktopLogHeader(`bootstrap resolved websocket endpoint baseUrl=${baseUrl}`);
|
||||
backendBootstrapToken = Crypto.randomBytes(24).toString("hex");
|
||||
if (desktopSettings.serverExposureMode !== DEFAULT_DESKTOP_SETTINGS.serverExposureMode) {
|
||||
writeDesktopLogHeader(
|
||||
`bootstrap restoring persisted server exposure mode mode=${desktopSettings.serverExposureMode}`,
|
||||
);
|
||||
}
|
||||
const serverExposureState = await applyDesktopServerExposureMode(
|
||||
desktopSettings.serverExposureMode,
|
||||
{
|
||||
persist: desktopSettings.serverExposureMode !== DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
|
||||
},
|
||||
);
|
||||
writeDesktopLogHeader(`bootstrap resolved backend endpoint baseUrl=${backendHttpUrl}`);
|
||||
if (serverExposureState.endpointUrl) {
|
||||
writeDesktopLogHeader(
|
||||
`bootstrap enabled network access endpointUrl=${serverExposureState.endpointUrl}`,
|
||||
);
|
||||
} else if (desktopSettings.serverExposureMode === "network-accessible") {
|
||||
writeDesktopLogHeader(
|
||||
"bootstrap fell back to local-only because no advertised network host was available",
|
||||
);
|
||||
}
|
||||
|
||||
registerIpcHandlers();
|
||||
writeDesktopLogHeader("bootstrap ipc handlers registered");
|
||||
startBackend();
|
||||
writeDesktopLogHeader("bootstrap backend start requested");
|
||||
|
||||
if (isDevelopment) {
|
||||
mainWindow = createWindow();
|
||||
writeDesktopLogHeader("bootstrap main window created");
|
||||
void waitForBackendHttpReady(backendHttpUrl)
|
||||
.then(() => {
|
||||
writeDesktopLogHeader("bootstrap backend ready");
|
||||
})
|
||||
.catch((error) => {
|
||||
if (isBackendReadinessAborted(error)) {
|
||||
return;
|
||||
}
|
||||
writeDesktopLogHeader(
|
||||
`bootstrap backend readiness warning message=${formatErrorMessage(error)}`,
|
||||
);
|
||||
console.warn("[desktop] backend readiness check timed out during dev bootstrap", error);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await waitForBackendHttpReady(backendHttpUrl);
|
||||
writeDesktopLogHeader("bootstrap backend ready");
|
||||
mainWindow = createWindow();
|
||||
writeDesktopLogHeader("bootstrap main window created");
|
||||
}
|
||||
@@ -1421,6 +1896,7 @@ app.on("before-quit", () => {
|
||||
updateInstallInFlight = false;
|
||||
writeDesktopLogHeader("before-quit received");
|
||||
clearUpdatePollTimer();
|
||||
cancelBackendReadinessWait();
|
||||
stopBackend();
|
||||
restoreStdIoCapture?.();
|
||||
});
|
||||
@@ -1434,13 +1910,19 @@ app
|
||||
registerDesktopProtocol();
|
||||
configureAutoUpdater();
|
||||
void bootstrap().catch((error) => {
|
||||
if (isBackendReadinessAborted(error) && isQuitting) {
|
||||
return;
|
||||
}
|
||||
handleFatalStartupError("bootstrap", error);
|
||||
});
|
||||
|
||||
app.on("activate", () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
mainWindow = createWindow();
|
||||
const existingWindow = mainWindow ?? BrowserWindow.getAllWindows()[0];
|
||||
if (existingWindow) {
|
||||
revealWindow(existingWindow);
|
||||
return;
|
||||
}
|
||||
mainWindow = createWindow();
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
@@ -1459,6 +1941,7 @@ if (process.platform !== "win32") {
|
||||
isQuitting = true;
|
||||
writeDesktopLogHeader("SIGINT received");
|
||||
clearUpdatePollTimer();
|
||||
cancelBackendReadinessWait();
|
||||
stopBackend();
|
||||
restoreStdIoCapture?.();
|
||||
app.quit();
|
||||
|
||||
@@ -12,13 +12,38 @@ const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
||||
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
|
||||
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
|
||||
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
|
||||
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
|
||||
const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
|
||||
const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
|
||||
const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
|
||||
const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
|
||||
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
|
||||
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
|
||||
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
|
||||
|
||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
getWsUrl: () => {
|
||||
const result = ipcRenderer.sendSync(GET_WS_URL_CHANNEL);
|
||||
return typeof result === "string" ? result : null;
|
||||
getLocalEnvironmentBootstrap: () => {
|
||||
const result = ipcRenderer.sendSync(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
|
||||
if (typeof result !== "object" || result === null) {
|
||||
return null;
|
||||
}
|
||||
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
|
||||
},
|
||||
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),
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure";
|
||||
|
||||
describe("resolveLanAdvertisedHost", () => {
|
||||
it("prefers an explicit host override", () => {
|
||||
expect(
|
||||
resolveLanAdvertisedHost(
|
||||
{
|
||||
en0: [
|
||||
{
|
||||
address: "192.168.1.44",
|
||||
family: "IPv4",
|
||||
internal: false,
|
||||
netmask: "255.255.255.0",
|
||||
cidr: "192.168.1.44/24",
|
||||
mac: "00:00:00:00:00:00",
|
||||
},
|
||||
],
|
||||
},
|
||||
"10.0.0.9",
|
||||
),
|
||||
).toBe("10.0.0.9");
|
||||
});
|
||||
|
||||
it("returns the first usable non-internal IPv4 address", () => {
|
||||
expect(
|
||||
resolveLanAdvertisedHost(
|
||||
{
|
||||
lo0: [
|
||||
{
|
||||
address: "127.0.0.1",
|
||||
family: "IPv4",
|
||||
internal: true,
|
||||
netmask: "255.0.0.0",
|
||||
cidr: "127.0.0.1/8",
|
||||
mac: "00:00:00:00:00:00",
|
||||
},
|
||||
],
|
||||
en0: [
|
||||
{
|
||||
address: "192.168.1.44",
|
||||
family: "IPv4",
|
||||
internal: false,
|
||||
netmask: "255.255.255.0",
|
||||
cidr: "192.168.1.44/24",
|
||||
mac: "00:00:00:00:00:00",
|
||||
},
|
||||
],
|
||||
},
|
||||
undefined,
|
||||
),
|
||||
).toBe("192.168.1.44");
|
||||
});
|
||||
|
||||
it("returns null when no usable network address is available", () => {
|
||||
expect(
|
||||
resolveLanAdvertisedHost(
|
||||
{
|
||||
lo0: [
|
||||
{
|
||||
address: "127.0.0.1",
|
||||
family: "IPv4",
|
||||
internal: true,
|
||||
netmask: "255.0.0.0",
|
||||
cidr: "127.0.0.1/8",
|
||||
mac: "00:00:00:00:00:00",
|
||||
},
|
||||
],
|
||||
},
|
||||
undefined,
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDesktopServerExposure", () => {
|
||||
it("keeps the desktop server loopback-only when local-only mode is selected", () => {
|
||||
expect(
|
||||
resolveDesktopServerExposure({
|
||||
mode: "local-only",
|
||||
port: 3773,
|
||||
networkInterfaces: {},
|
||||
}),
|
||||
).toEqual({
|
||||
mode: "local-only",
|
||||
bindHost: "127.0.0.1",
|
||||
localHttpUrl: "http://127.0.0.1:3773",
|
||||
localWsUrl: "ws://127.0.0.1:3773",
|
||||
endpointUrl: null,
|
||||
advertisedHost: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("binds to all interfaces in network-accessible mode", () => {
|
||||
expect(
|
||||
resolveDesktopServerExposure({
|
||||
mode: "network-accessible",
|
||||
port: 3773,
|
||||
networkInterfaces: {
|
||||
en0: [
|
||||
{
|
||||
address: "192.168.1.44",
|
||||
family: "IPv4",
|
||||
internal: false,
|
||||
netmask: "255.255.255.0",
|
||||
cidr: "192.168.1.44/24",
|
||||
mac: "00:00:00:00:00:00",
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
mode: "network-accessible",
|
||||
bindHost: "0.0.0.0",
|
||||
localHttpUrl: "http://127.0.0.1:3773",
|
||||
localWsUrl: "ws://127.0.0.1:3773",
|
||||
endpointUrl: "http://192.168.1.44:3773",
|
||||
advertisedHost: "192.168.1.44",
|
||||
});
|
||||
});
|
||||
|
||||
it("stays network-accessible even when no LAN address is currently detectable", () => {
|
||||
expect(
|
||||
resolveDesktopServerExposure({
|
||||
mode: "network-accessible",
|
||||
port: 3773,
|
||||
networkInterfaces: {},
|
||||
}),
|
||||
).toEqual({
|
||||
mode: "network-accessible",
|
||||
bindHost: "0.0.0.0",
|
||||
localHttpUrl: "http://127.0.0.1:3773",
|
||||
localWsUrl: "ws://127.0.0.1:3773",
|
||||
endpointUrl: null,
|
||||
advertisedHost: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import type { NetworkInterfaceInfo } from "node:os";
|
||||
import type { DesktopServerExposureMode } from "@t3tools/contracts";
|
||||
|
||||
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
|
||||
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
|
||||
|
||||
export interface DesktopServerExposure {
|
||||
readonly mode: DesktopServerExposureMode;
|
||||
readonly bindHost: string;
|
||||
readonly localHttpUrl: string;
|
||||
readonly localWsUrl: string;
|
||||
readonly endpointUrl: string | null;
|
||||
readonly advertisedHost: string | null;
|
||||
}
|
||||
|
||||
const normalizeOptionalHost = (value: string | undefined): string | undefined => {
|
||||
const normalized = value?.trim();
|
||||
return normalized && normalized.length > 0 ? normalized : undefined;
|
||||
};
|
||||
|
||||
const isUsableLanIpv4Address = (address: string): boolean =>
|
||||
!address.startsWith("127.") && !address.startsWith("169.254.");
|
||||
|
||||
export function resolveLanAdvertisedHost(
|
||||
networkInterfaces: NodeJS.Dict<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,10 +71,37 @@ describe("getAutoUpdateDisabledReason", () => {
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
hasUpdateFeedConfig: true,
|
||||
}),
|
||||
).toContain("packaged production builds");
|
||||
});
|
||||
|
||||
it("reports packaged local builds without an update feed as disabled", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment: false,
|
||||
isPackaged: true,
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
hasUpdateFeedConfig: false,
|
||||
}),
|
||||
).toContain("no update feed");
|
||||
});
|
||||
|
||||
it("allows packaged builds with an update feed", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment: false,
|
||||
isPackaged: true,
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
hasUpdateFeedConfig: true,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("reports env-disabled auto updates", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
@@ -83,6 +110,7 @@ describe("getAutoUpdateDisabledReason", () => {
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: true,
|
||||
hasUpdateFeedConfig: true,
|
||||
}),
|
||||
).toContain("T3CODE_DISABLE_AUTO_UPDATE");
|
||||
});
|
||||
@@ -95,6 +123,7 @@ describe("getAutoUpdateDisabledReason", () => {
|
||||
platform: "linux",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
hasUpdateFeedConfig: true,
|
||||
}),
|
||||
).toContain("AppImage");
|
||||
});
|
||||
|
||||
@@ -34,7 +34,11 @@ export function getAutoUpdateDisabledReason(args: {
|
||||
platform: NodeJS.Platform;
|
||||
appImage?: string | undefined;
|
||||
disabledByEnv: boolean;
|
||||
hasUpdateFeedConfig: boolean;
|
||||
}): string | null {
|
||||
if (!args.hasUpdateFeedConfig) {
|
||||
return "Automatic updates are not available because no update feed is configured.";
|
||||
}
|
||||
if (args.isDevelopment || !args.isPackaged) {
|
||||
return "Automatic updates are only available in packaged production builds.";
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
---
|
||||
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.">
|
||||
@@ -17,11 +18,11 @@ import Layout from "../layouts/Layout.astro";
|
||||
<h2 class="platform-name">macOS</h2>
|
||||
</div>
|
||||
<div class="download-cards">
|
||||
<a class="download-card" data-asset="arm64.dmg" href="#">
|
||||
<a class="download-card" data-asset="arm64.dmg" href={RELEASES_URL}>
|
||||
<span class="card-arch">Apple Silicon (arm64)</span>
|
||||
<span class="card-format">.dmg</span>
|
||||
</a>
|
||||
<a class="download-card" data-asset="x64.dmg" href="#">
|
||||
<a class="download-card" data-asset="x64.dmg" href={RELEASES_URL}>
|
||||
<span class="card-arch">Intel (x64)</span>
|
||||
<span class="card-format">.dmg</span>
|
||||
</a>
|
||||
@@ -35,7 +36,7 @@ import Layout from "../layouts/Layout.astro";
|
||||
<h2 class="platform-name">Windows</h2>
|
||||
</div>
|
||||
<div class="download-cards">
|
||||
<a class="download-card" data-asset="x64.exe" href="#">
|
||||
<a class="download-card" data-asset="x64.exe" href={RELEASES_URL}>
|
||||
<span class="card-arch">Windows 10, 11</span>
|
||||
<span class="card-format">.exe</span>
|
||||
</a>
|
||||
@@ -49,7 +50,7 @@ import Layout from "../layouts/Layout.astro";
|
||||
<h2 class="platform-name">Linux</h2>
|
||||
</div>
|
||||
<div class="download-cards">
|
||||
<a class="download-card" data-asset="x86_64.AppImage" href="#">
|
||||
<a class="download-card" data-asset="x86_64.AppImage" href={RELEASES_URL}>
|
||||
<span class="card-arch">x86_64</span>
|
||||
<span class="card-format">AppImage</span>
|
||||
</a>
|
||||
|
||||
@@ -26,6 +26,7 @@ import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore
|
||||
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
|
||||
import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
|
||||
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
|
||||
import { GitStatusBroadcaster } from "../src/git/Services/GitStatusBroadcaster.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
|
||||
@@ -45,10 +46,11 @@ import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
|
||||
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
|
||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
|
||||
import { RepositoryIdentityResolverLive } from "../src/project/Layers/RepositoryIdentityResolver.ts";
|
||||
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
|
||||
import { RuntimeReceiptBusLive } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
|
||||
import { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
|
||||
import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
|
||||
import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
|
||||
import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
|
||||
@@ -289,14 +291,15 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
);
|
||||
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
|
||||
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
orchestrationLayer,
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
projectionSnapshotQueryLayer,
|
||||
orchestrationLayer.pipe(Layer.provide(projectionSnapshotQueryLayer)),
|
||||
ProjectionCheckpointRepositoryLive,
|
||||
ProjectionPendingApprovalRepositoryLive,
|
||||
checkpointStoreLayer,
|
||||
providerLayer,
|
||||
RuntimeReceiptBusLive,
|
||||
RuntimeReceiptBusTest,
|
||||
);
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest();
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
@@ -319,6 +322,22 @@ 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),
|
||||
@@ -333,8 +352,11 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Layer.provideMerge(providerCommandReactorLayer),
|
||||
Layer.provideMerge(checkpointReactorLayer),
|
||||
);
|
||||
const layer = orchestrationReactorLayer.pipe(
|
||||
const layer = Layer.empty.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(orchestrationReactorLayer),
|
||||
Layer.provide(persistenceLayer),
|
||||
Layer.provideMerge(RepositoryIdentityResolverLive),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
@@ -373,7 +395,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.stream, (receipt) =>
|
||||
yield* Stream.runForEach(runtimeReceiptBus.streamEventsForTest, (receipt) =>
|
||||
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
|
||||
).pipe(Effect.forkIn(scope));
|
||||
yield* Effect.sleep(10);
|
||||
@@ -416,7 +438,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
) =>
|
||||
waitFor(
|
||||
pendingApprovalRepository
|
||||
.getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })
|
||||
.getByRequestId({ requestId: ApprovalRequestId.make(requestId) })
|
||||
.pipe(
|
||||
Effect.map((row) =>
|
||||
Option.match(row, {
|
||||
|
||||
@@ -289,7 +289,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
|
||||
state.turnCount += 1;
|
||||
const turnCount = state.turnCount;
|
||||
const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
|
||||
const turnId = TurnId.make(`turn-${turnCount}`);
|
||||
|
||||
const response = state.queuedResponses.shift();
|
||||
if (!response) {
|
||||
@@ -307,7 +307,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
...(fixtureEvent as Record<string, unknown>),
|
||||
eventId: randomUUID(),
|
||||
provider,
|
||||
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
|
||||
sessionId: RuntimeSessionId.make(String(input.threadId)),
|
||||
createdAt: nowIso(),
|
||||
};
|
||||
rawEvent.threadId = state.snapshot.threadId;
|
||||
@@ -363,7 +363,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
if (deferredTurnCompletedEvents.length === 0) {
|
||||
yield* emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe(randomUUID()),
|
||||
eventId: EventId.make(randomUUID()),
|
||||
provider,
|
||||
createdAt: nowIso(),
|
||||
threadId: state.snapshot.threadId,
|
||||
@@ -488,7 +488,9 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
readThread,
|
||||
rollbackThread,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromQueue(runtimeEvents),
|
||||
get streamEvents() {
|
||||
return Stream.fromQueue(runtimeEvents);
|
||||
},
|
||||
};
|
||||
|
||||
const queueTurnResponse = (
|
||||
|
||||
@@ -5,14 +5,14 @@ const PROVIDER = "codex" as const;
|
||||
const SESSION_ID = "fixture-session";
|
||||
const THREAD_ID = "fixture-thread";
|
||||
const TURN_ID = "fixture-turn";
|
||||
const REQUEST_ID = RuntimeRequestId.makeUnsafe("req-1");
|
||||
const REQUEST_ID = RuntimeRequestId.make("req-1");
|
||||
|
||||
function baseEvent(
|
||||
eventId: string,
|
||||
createdAt: string,
|
||||
): Pick<LegacyProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
|
||||
return {
|
||||
eventId: EventId.makeUnsafe(eventId),
|
||||
eventId: EventId.make(eventId),
|
||||
provider: PROVIDER,
|
||||
sessionId: SESSION_ID,
|
||||
createdAt,
|
||||
|
||||
@@ -30,14 +30,13 @@ import type {
|
||||
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asApprovalRequestId = (value: string): ApprovalRequestId =>
|
||||
ApprovalRequestId.makeUnsafe(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.make(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asEventId = (value: string): EventId => EventId.make(value);
|
||||
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
|
||||
|
||||
const PROJECT_ID = asProjectId("project-1");
|
||||
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
|
||||
const THREAD_ID = ThreadId.make("thread-1");
|
||||
const FIXTURE_TURN_ID = "fixture-turn";
|
||||
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
|
||||
type IntegrationProvider = ProviderKind;
|
||||
@@ -112,7 +111,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
commandId: CommandId.make("cmd-project-create"),
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
@@ -125,7 +124,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
commandId: CommandId.make("cmd-thread-create"),
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
@@ -150,7 +149,7 @@ const startTurn = (input: {
|
||||
}) =>
|
||||
input.harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe(input.commandId),
|
||||
commandId: CommandId.make(input.commandId),
|
||||
threadId: THREAD_ID,
|
||||
message: {
|
||||
messageId: asMessageId(input.messageId),
|
||||
@@ -261,7 +260,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create-real-codex"),
|
||||
commandId: CommandId.make("cmd-project-create-real-codex"),
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
@@ -274,7 +273,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-real-codex"),
|
||||
commandId: CommandId.make("cmd-thread-create-real-codex"),
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
@@ -291,7 +290,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-real-codex-1"),
|
||||
threadId: THREAD_ID,
|
||||
message: {
|
||||
messageId: asMessageId("msg-real-codex-1"),
|
||||
@@ -318,7 +317,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-2"),
|
||||
commandId: CommandId.make("cmd-turn-start-real-codex-2"),
|
||||
threadId: THREAD_ID,
|
||||
message: {
|
||||
messageId: asMessageId("msg-real-codex-2"),
|
||||
@@ -583,7 +582,7 @@ it.live("tracks approval requests and resolves pending approvals on user respons
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.makeUnsafe("cmd-approval-respond"),
|
||||
commandId: CommandId.make("cmd-approval-respond"),
|
||||
threadId: THREAD_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
decision: "accept",
|
||||
@@ -815,7 +814,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert"),
|
||||
commandId: CommandId.make("cmd-checkpoint-revert"),
|
||||
threadId: THREAD_ID,
|
||||
turnCount: 1,
|
||||
createdAt: nowIso(),
|
||||
@@ -875,7 +874,7 @@ it.live(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-no-session"),
|
||||
commandId: CommandId.make("cmd-checkpoint-revert-no-session"),
|
||||
threadId: THREAD_ID,
|
||||
turnCount: 0,
|
||||
createdAt: nowIso(),
|
||||
@@ -1119,7 +1118,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
|
||||
commandId: CommandId.make("cmd-claude-approval-respond"),
|
||||
threadId: THREAD_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
decision: "accept",
|
||||
@@ -1192,7 +1191,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.interrupt",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
|
||||
commandId: CommandId.make("cmd-turn-interrupt-claude"),
|
||||
threadId: THREAD_ID,
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
@@ -1309,7 +1308,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
|
||||
commandId: CommandId.make("cmd-checkpoint-revert-claude"),
|
||||
threadId: THREAD_ID,
|
||||
turnCount: 1,
|
||||
createdAt: nowIso(),
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { readFile, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { PERF_CATALOG_IDS, getPerfSeedScenario } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { seedPerfState } from "./seedPerfState.ts";
|
||||
|
||||
describe("seedPerfState", () => {
|
||||
const runParentDirsToCleanup: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
runParentDirsToCleanup
|
||||
.splice(0)
|
||||
.map((runParentDir) => rm(runParentDir, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
it("seeds large thread fixtures through the real event store and projection pipeline", async () => {
|
||||
const seeded = await seedPerfState("large_threads");
|
||||
runParentDirsToCleanup.push(seeded.runParentDir);
|
||||
const scenario = getPerfSeedScenario("large_threads");
|
||||
|
||||
expect(seeded.snapshot.projects).toHaveLength(5);
|
||||
expect(seeded.snapshot.threads).toHaveLength(30);
|
||||
expect(seeded.baseDir).toBe(join(seeded.runParentDir, "base"));
|
||||
expect(new Set(seeded.snapshot.threads.map((thread) => thread.projectId)).size).toBe(5);
|
||||
|
||||
const heavyThread = seeded.snapshot.threads.find(
|
||||
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
);
|
||||
const heavyThreadScenario = scenario.threads.find(
|
||||
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
);
|
||||
expect(heavyThread?.messages).toHaveLength(2_000);
|
||||
expect(heavyThreadScenario?.turnCount ?? Number.POSITIVE_INFINITY).toBeLessThan(100);
|
||||
expect((heavyThread?.activities.length ?? 0) > 0).toBe(true);
|
||||
expect((heavyThread?.proposedPlans.length ?? 0) > 0).toBe(true);
|
||||
expect((heavyThread?.checkpoints.length ?? 0) >= 20).toBe(true);
|
||||
expect((heavyThread?.checkpoints[0]?.files.length ?? 0) >= 12).toBe(true);
|
||||
});
|
||||
|
||||
it("enables assistant streaming in the burst base seed for websocket perf runs", async () => {
|
||||
const seeded = await seedPerfState("burst_base");
|
||||
runParentDirsToCleanup.push(seeded.runParentDir);
|
||||
|
||||
const rawSettings = await readFile(join(seeded.baseDir, "userdata/settings.json"), "utf8");
|
||||
expect(JSON.parse(rawSettings)).toMatchObject({
|
||||
enableAssistantStreaming: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,589 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { cp, mkdir, mkdtemp, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
CheckpointRef,
|
||||
CommandId,
|
||||
EventId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationReadModel,
|
||||
type ProjectId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, ManagedRuntime } from "effect";
|
||||
|
||||
import {
|
||||
buildPerfAssistantMessageCountPlan,
|
||||
getPerfSeedScenario,
|
||||
perfEventId,
|
||||
perfMessageIdForThread,
|
||||
perfTurnIdForThread,
|
||||
type PerfProjectScenario,
|
||||
type PerfSeedScenario,
|
||||
type PerfSeedScenarioId,
|
||||
type PerfSeedThreadScenario,
|
||||
} from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { ServerConfig } from "../../src/config.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "../../src/orchestration/Layers/ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "../../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationProjectionPipeline } from "../../src/orchestration/Services/ProjectionPipeline.ts";
|
||||
import { ProjectionSnapshotQuery } from "../../src/orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationEventStoreLive } from "../../src/persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "../../src/persistence/Layers/Sqlite.ts";
|
||||
import { OrchestrationEventStore } from "../../src/persistence/Services/OrchestrationEventStore.ts";
|
||||
import { ServerSettingsService, ServerSettingsLive } from "../../src/serverSettings.ts";
|
||||
|
||||
export interface PerfSeededState {
|
||||
readonly scenarioId: PerfSeedScenarioId;
|
||||
readonly runParentDir: string;
|
||||
readonly baseDir: string;
|
||||
readonly workspaceRoot: string;
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
}
|
||||
|
||||
const templateDirPromises = new Map<PerfSeedScenarioId, Promise<string>>();
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
execFileSync("git", args, {
|
||||
cwd,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
encoding: "utf8",
|
||||
});
|
||||
}
|
||||
|
||||
async function initializeGitWorkspace(workspaceRoot: string): Promise<void> {
|
||||
await mkdir(workspaceRoot, { recursive: true });
|
||||
runGit(workspaceRoot, ["init", "--initial-branch=main"]);
|
||||
runGit(workspaceRoot, ["config", "user.email", "[email protected]"]);
|
||||
runGit(workspaceRoot, ["config", "user.name", "Perf Fixture"]);
|
||||
await writeFile(
|
||||
join(workspaceRoot, "README.md"),
|
||||
"# Performance Workspace\n\nSeeded fixture state for local perf regression tests.\n",
|
||||
"utf8",
|
||||
);
|
||||
runGit(workspaceRoot, ["add", "."]);
|
||||
runGit(workspaceRoot, ["commit", "-m", "Initial perf workspace"]);
|
||||
}
|
||||
|
||||
function plusMs(baseTimeMs: number, offsetMs: number): string {
|
||||
return new Date(baseTimeMs + offsetMs).toISOString();
|
||||
}
|
||||
|
||||
function makeCommandId(prefix: string, threadId: string, turnIndex: number): CommandId {
|
||||
return CommandId.makeUnsafe(`${prefix}:${threadId}:${turnIndex.toString().padStart(4, "0")}`);
|
||||
}
|
||||
|
||||
function buildProjectEvent(
|
||||
project: PerfProjectScenario,
|
||||
workspaceRoot: string,
|
||||
createdAt: string,
|
||||
): Omit<OrchestrationEvent, "sequence"> {
|
||||
return {
|
||||
type: "project.created",
|
||||
eventId: EventId.makeUnsafe(`perf-project-created:${String(project.id)}`),
|
||||
aggregateKind: "project",
|
||||
aggregateId: project.id,
|
||||
occurredAt: createdAt,
|
||||
commandId: CommandId.makeUnsafe(`perf-project-create:${String(project.id)}`),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe(`perf-project-create:${String(project.id)}`),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: project.id,
|
||||
title: project.title,
|
||||
workspaceRoot,
|
||||
defaultModelSelection: project.defaultModelSelection,
|
||||
scripts: [],
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildThreadCreatedEvent(
|
||||
thread: PerfSeedThreadScenario,
|
||||
project: PerfProjectScenario,
|
||||
createdAt: string,
|
||||
): Omit<OrchestrationEvent, "sequence"> {
|
||||
return {
|
||||
type: "thread.created",
|
||||
eventId: EventId.makeUnsafe(`perf-thread-created:${String(thread.id)}`),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: createdAt,
|
||||
commandId: CommandId.makeUnsafe(`perf-thread-create:${String(thread.id)}`),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe(`perf-thread-create:${String(thread.id)}`),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
modelSelection: project.defaultModelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildUserMessageText(thread: PerfSeedThreadScenario, turnIndex: number): string {
|
||||
const base = `${thread.title} request ${turnIndex}: review the current workspace state and explain the next change.`;
|
||||
if (turnIndex % 11 === 0) {
|
||||
return `${base}\n\nFocus on virtualization, batching, and cross-thread navigation latency.`;
|
||||
}
|
||||
if (turnIndex % 7 === 0) {
|
||||
return `${base}\n\nSummarize CPU-sensitive paths and any websocket burst handling concerns.`;
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
function buildAssistantMessageText(
|
||||
thread: PerfSeedThreadScenario,
|
||||
turnIndex: number,
|
||||
assistantMessageIndex: number,
|
||||
assistantMessageCount: number,
|
||||
): string {
|
||||
const phaseLabel =
|
||||
assistantMessageIndex === 1
|
||||
? "Opening"
|
||||
: assistantMessageIndex === assistantMessageCount
|
||||
? "Settled"
|
||||
: assistantMessageIndex % 5 === 0
|
||||
? "Checkpoint"
|
||||
: "Loop";
|
||||
const focusTopics = [
|
||||
"checked the visible timeline window and sidebar ordering",
|
||||
"trimmed redundant projection work before the next render pass",
|
||||
"reviewed websocket fan-out and message grouping pressure",
|
||||
"verified checkpoint rows stay bounded while hidden threads move",
|
||||
"kept the active route stable while background threads kept streaming",
|
||||
];
|
||||
const topic = focusTopics[(turnIndex + assistantMessageIndex) % focusTopics.length]!;
|
||||
const threadBias =
|
||||
thread.category === "heavy"
|
||||
? "The thread is still dense enough to stress virtualization."
|
||||
: thread.category === "burst"
|
||||
? "This pass is still carrying live burst pressure."
|
||||
: "Background churn is staying active without stealing focus.";
|
||||
|
||||
return `${thread.title} ${phaseLabel.toLowerCase()} ${assistantMessageIndex}/${assistantMessageCount} for turn ${turnIndex}: ${topic}. ${threadBias}`;
|
||||
}
|
||||
|
||||
function buildProposedPlanMarkdown(thread: PerfSeedThreadScenario, turnIndex: number): string {
|
||||
return [
|
||||
`## ${thread.title} plan ${turnIndex}`,
|
||||
"",
|
||||
"1. Measure the current thread switch path against a stable local budget.",
|
||||
"2. Reduce avoidable render churn in the visible timeline window.",
|
||||
"3. Validate websocket burst handling with real runtime events before tightening thresholds.",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function buildCheckpointFiles(
|
||||
thread: PerfSeedThreadScenario,
|
||||
threadOrdinal: number,
|
||||
turnIndex: number,
|
||||
): ReadonlyArray<{
|
||||
readonly path: string;
|
||||
readonly kind: string;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
}> {
|
||||
const nestedPathTemplates = [
|
||||
["apps", "web", "src", "components", `thread-${threadOrdinal + 1}`, "TimelineVirtualizer.tsx"],
|
||||
["apps", "web", "src", "components", `thread-${threadOrdinal + 1}`, "ThreadSummaryPane.tsx"],
|
||||
["apps", "web", "src", "hooks", `thread-${threadOrdinal + 1}`, "useThreadViewport.ts"],
|
||||
["apps", "web", "src", "stores", `thread-${threadOrdinal + 1}`, "timelineStore.ts"],
|
||||
[
|
||||
"apps",
|
||||
"server",
|
||||
"src",
|
||||
"orchestration",
|
||||
`thread-${threadOrdinal + 1}`,
|
||||
"projectionPipeline.ts",
|
||||
],
|
||||
["apps", "server", "src", "provider", `thread-${threadOrdinal + 1}`, "runtimeBuffer.ts"],
|
||||
["packages", "shared", "src", "perf", `thread-${threadOrdinal + 1}`, "fixtureBuilders.ts"],
|
||||
["packages", "shared", "src", "perf", `thread-${threadOrdinal + 1}`, "scenarioCatalog.ts"],
|
||||
["packages", "contracts", "src", "orchestration", `thread-${threadOrdinal + 1}`, "schemas.ts"],
|
||||
["docs", "perf", `thread-${threadOrdinal + 1}`, "notes", "regression-findings.md"],
|
||||
["scripts", "perf", `thread-${threadOrdinal + 1}`, "capture-profile.ts"],
|
||||
["test", "perf", "fixtures", `thread-${threadOrdinal + 1}`, "workspace-state.json"],
|
||||
] as const;
|
||||
const fileCount = thread.category === "heavy" ? 12 + (turnIndex % 7) : 7 + (turnIndex % 4);
|
||||
|
||||
return Array.from({ length: fileCount }, (_, fileIndex) => {
|
||||
const template = nestedPathTemplates[fileIndex % nestedPathTemplates.length]!;
|
||||
const variant = Math.floor(fileIndex / nestedPathTemplates.length);
|
||||
const baseSegments = [...template];
|
||||
const fileName = baseSegments.pop()!;
|
||||
const variantFileName =
|
||||
variant === 0
|
||||
? fileName
|
||||
: fileName.replace(/(\.[^.]*)$/, `-${(variant + 1).toString().padStart(2, "0")}$1`);
|
||||
const path = [...baseSegments, variantFileName].join("/");
|
||||
const kind =
|
||||
fileIndex % 9 === 0
|
||||
? "deleted"
|
||||
: fileIndex % 5 === 0
|
||||
? "added"
|
||||
: fileIndex % 4 === 0
|
||||
? "renamed"
|
||||
: "modified";
|
||||
|
||||
return {
|
||||
path,
|
||||
kind,
|
||||
additions: kind === "deleted" ? 0 : 4 + ((turnIndex + fileIndex) % 11),
|
||||
deletions: kind === "added" ? 0 : 1 + ((threadOrdinal + fileIndex + turnIndex) % 6),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function buildThreadTurnEvents(
|
||||
thread: PerfSeedThreadScenario,
|
||||
threadOrdinal: number,
|
||||
projectStartMs: number,
|
||||
): ReadonlyArray<Omit<OrchestrationEvent, "sequence">> {
|
||||
const events: Array<Omit<OrchestrationEvent, "sequence">> = [];
|
||||
const threadStartMs = projectStartMs + threadOrdinal * 60_000;
|
||||
const assistantMessageCountPlan = buildPerfAssistantMessageCountPlan(thread);
|
||||
|
||||
for (let turnIndex = 1; turnIndex <= thread.turnCount; turnIndex += 1) {
|
||||
const turnId = perfTurnIdForThread(thread, turnIndex);
|
||||
const userMessageId = perfMessageIdForThread(thread, "user", turnIndex, 1);
|
||||
const assistantMessageCount = assistantMessageCountPlan[turnIndex - 1] ?? 1;
|
||||
const turnBaseMs = threadStartMs + turnIndex * 1_000;
|
||||
const userOccurredAt = plusMs(turnBaseMs, 0);
|
||||
const activityAssistantIndex =
|
||||
thread.activityStride !== null && turnIndex % thread.activityStride === 0
|
||||
? Math.max(2, Math.floor(assistantMessageCount * 0.35))
|
||||
: null;
|
||||
const planAssistantIndex =
|
||||
thread.planStride !== null && turnIndex % thread.planStride === 0
|
||||
? Math.max(2, Math.floor(assistantMessageCount * 0.7))
|
||||
: null;
|
||||
let lastAssistantMessageId = perfMessageIdForThread(
|
||||
thread,
|
||||
"assistant",
|
||||
turnIndex,
|
||||
assistantMessageCount,
|
||||
);
|
||||
let turnEventOffset = 0;
|
||||
const nextEventId = (prefix: string) =>
|
||||
perfEventId(prefix, thread.id, turnIndex * 100 + turnEventOffset++);
|
||||
|
||||
events.push({
|
||||
type: "thread.message-sent",
|
||||
eventId: nextEventId("perf-user-message"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: userOccurredAt,
|
||||
commandId: makeCommandId("perf-user-message", String(thread.id), turnIndex),
|
||||
causationEventId: null,
|
||||
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
messageId: userMessageId,
|
||||
role: "user",
|
||||
text: buildUserMessageText(thread, turnIndex),
|
||||
attachments: [],
|
||||
turnId,
|
||||
streaming: false,
|
||||
createdAt: userOccurredAt,
|
||||
updatedAt: userOccurredAt,
|
||||
},
|
||||
});
|
||||
|
||||
for (
|
||||
let assistantMessageIndex = 1;
|
||||
assistantMessageIndex <= assistantMessageCount;
|
||||
assistantMessageIndex += 1
|
||||
) {
|
||||
const assistantOccurredAt = plusMs(turnBaseMs, 120 + assistantMessageIndex * 40);
|
||||
const assistantMessageId = perfMessageIdForThread(
|
||||
thread,
|
||||
"assistant",
|
||||
turnIndex,
|
||||
assistantMessageIndex,
|
||||
);
|
||||
lastAssistantMessageId = assistantMessageId;
|
||||
|
||||
events.push({
|
||||
type: "thread.message-sent",
|
||||
eventId: nextEventId("perf-assistant-message"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: assistantOccurredAt,
|
||||
commandId: makeCommandId("perf-assistant-message", String(thread.id), turnIndex),
|
||||
causationEventId: null,
|
||||
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
role: "assistant",
|
||||
text: buildAssistantMessageText(
|
||||
thread,
|
||||
turnIndex,
|
||||
assistantMessageIndex,
|
||||
assistantMessageCount,
|
||||
),
|
||||
attachments: [],
|
||||
turnId,
|
||||
streaming: false,
|
||||
createdAt: assistantOccurredAt,
|
||||
updatedAt: assistantOccurredAt,
|
||||
},
|
||||
});
|
||||
|
||||
if (activityAssistantIndex === assistantMessageIndex) {
|
||||
const activityOccurredAt = plusMs(turnBaseMs, 132 + assistantMessageIndex * 40);
|
||||
events.push({
|
||||
type: "thread.activity-appended",
|
||||
eventId: nextEventId("perf-activity"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: activityOccurredAt,
|
||||
commandId: makeCommandId("perf-activity", String(thread.id), turnIndex),
|
||||
causationEventId: null,
|
||||
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
activity: {
|
||||
id: perfEventId("perf-activity-row", thread.id, turnIndex),
|
||||
tone: "tool",
|
||||
kind: "tool.completed",
|
||||
summary: `Synthetic command batch ${turnIndex}.${assistantMessageIndex}`,
|
||||
payload: {
|
||||
command: "perf-simulated",
|
||||
batch: turnIndex,
|
||||
loop: assistantMessageIndex,
|
||||
threadCategory: thread.category,
|
||||
},
|
||||
turnId,
|
||||
createdAt: activityOccurredAt,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (planAssistantIndex === assistantMessageIndex) {
|
||||
const planOccurredAt = plusMs(turnBaseMs, 140 + assistantMessageIndex * 40);
|
||||
events.push({
|
||||
type: "thread.proposed-plan-upserted",
|
||||
eventId: nextEventId("perf-plan"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: planOccurredAt,
|
||||
commandId: makeCommandId("perf-plan", String(thread.id), turnIndex),
|
||||
causationEventId: null,
|
||||
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
proposedPlan: {
|
||||
id: `perf-plan:${String(thread.id)}:${turnIndex.toString().padStart(4, "0")}`,
|
||||
turnId,
|
||||
planMarkdown: buildProposedPlanMarkdown(thread, turnIndex),
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
createdAt: planOccurredAt,
|
||||
updatedAt: planOccurredAt,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (thread.diffStride !== null && turnIndex % thread.diffStride === 0) {
|
||||
const diffOccurredAt = plusMs(turnBaseMs, 180 + assistantMessageCount * 40);
|
||||
events.push({
|
||||
type: "thread.turn-diff-completed",
|
||||
eventId: nextEventId("perf-diff"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: diffOccurredAt,
|
||||
commandId: makeCommandId("perf-diff", String(thread.id), turnIndex),
|
||||
causationEventId: null,
|
||||
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
checkpointTurnCount: turnIndex,
|
||||
checkpointRef: CheckpointRef.makeUnsafe(
|
||||
`refs/perf/${String(thread.id)}/${turnIndex.toString().padStart(4, "0")}`,
|
||||
),
|
||||
status: "ready",
|
||||
files: buildCheckpointFiles(thread, threadOrdinal, turnIndex),
|
||||
assistantMessageId: lastAssistantMessageId,
|
||||
completedAt: diffOccurredAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
|
||||
function buildScenarioEvents(
|
||||
scenario: PerfSeedScenario,
|
||||
workspaceRootsByProjectId: ReadonlyMap<ProjectId, string>,
|
||||
): ReadonlyArray<Omit<OrchestrationEvent, "sequence">> {
|
||||
const projectStartMs = Date.parse("2026-03-01T12:00:00.000Z");
|
||||
const threadsByProjectId = new Map<ProjectId, PerfSeedThreadScenario[]>();
|
||||
for (const thread of scenario.threads) {
|
||||
const existing = threadsByProjectId.get(thread.projectId) ?? [];
|
||||
existing.push(thread);
|
||||
threadsByProjectId.set(thread.projectId, existing);
|
||||
}
|
||||
|
||||
let globalThreadOrdinal = 0;
|
||||
const events: Array<Omit<OrchestrationEvent, "sequence">> = [];
|
||||
|
||||
for (const [projectOrdinal, project] of scenario.projects.entries()) {
|
||||
const projectWorkspaceRoot = workspaceRootsByProjectId.get(project.id);
|
||||
if (!projectWorkspaceRoot) {
|
||||
throw new Error(`Missing workspace root for perf project '${String(project.id)}'.`);
|
||||
}
|
||||
const projectBaseMs = projectStartMs + projectOrdinal * 6 * 60_000;
|
||||
const projectCreatedAt = plusMs(projectBaseMs, 0);
|
||||
const projectThreads = threadsByProjectId.get(project.id) ?? [];
|
||||
events.push(buildProjectEvent(project, projectWorkspaceRoot, projectCreatedAt));
|
||||
|
||||
for (const [threadOrdinalWithinProject, thread] of projectThreads.entries()) {
|
||||
const threadCreatedAt = plusMs(projectBaseMs, threadOrdinalWithinProject * 45_000 + 50);
|
||||
const threadEvents = buildThreadTurnEvents(thread, globalThreadOrdinal, projectBaseMs);
|
||||
globalThreadOrdinal += 1;
|
||||
events.push(buildThreadCreatedEvent(thread, project, threadCreatedAt), ...threadEvents);
|
||||
}
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
|
||||
async function createTemplateDir(scenarioId: PerfSeedScenarioId): Promise<string> {
|
||||
const scenario = getPerfSeedScenario(scenarioId);
|
||||
const baseDir = await mkdtemp(join(tmpdir(), `t3-perf-template-${scenarioId}-`));
|
||||
const primaryProject = scenario.projects[0];
|
||||
if (!primaryProject) {
|
||||
throw new Error(`Perf scenario '${scenarioId}' has no projects.`);
|
||||
}
|
||||
const workspaceRoot = join(baseDir, primaryProject.workspaceDirectoryName);
|
||||
const workspaceRootsByProjectId = new Map<ProjectId, string>(
|
||||
scenario.projects.map((project) => [project.id, join(baseDir, project.workspaceDirectoryName)]),
|
||||
);
|
||||
|
||||
await Promise.all(
|
||||
scenario.projects.map((project) =>
|
||||
initializeGitWorkspace(join(baseDir, project.workspaceDirectoryName)),
|
||||
),
|
||||
);
|
||||
|
||||
const seedLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
|
||||
Layer.provideMerge(OrchestrationProjectionPipelineLive),
|
||||
Layer.provideMerge(OrchestrationEventStoreLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceRoot, baseDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtime = ManagedRuntime.make(seedLayer);
|
||||
|
||||
const snapshot = await runtime.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
|
||||
yield* serverSettings.updateSettings({
|
||||
enableAssistantStreaming: scenario.id === "burst_base",
|
||||
});
|
||||
|
||||
for (const event of buildScenarioEvents(scenario, workspaceRootsByProjectId)) {
|
||||
const storedEvent = yield* eventStore.append(event);
|
||||
yield* projectionPipeline.projectEvent(storedEvent);
|
||||
}
|
||||
|
||||
return yield* snapshotQuery.getSnapshot();
|
||||
}),
|
||||
);
|
||||
|
||||
const manifestPath = join(baseDir, "perf-seed-manifest.json");
|
||||
await writeFile(
|
||||
manifestPath,
|
||||
`${JSON.stringify(
|
||||
{
|
||||
scenarioId,
|
||||
workspaceRoot,
|
||||
snapshotSequence: snapshot.snapshotSequence,
|
||||
projectCount: snapshot.projects.length,
|
||||
threadCount: snapshot.threads.length,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
"utf8",
|
||||
);
|
||||
|
||||
await runtime.dispose();
|
||||
return baseDir;
|
||||
}
|
||||
|
||||
async function getTemplateDir(scenarioId: PerfSeedScenarioId): Promise<string> {
|
||||
const existing = templateDirPromises.get(scenarioId);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
const created = createTemplateDir(scenarioId);
|
||||
templateDirPromises.set(scenarioId, created);
|
||||
return created;
|
||||
}
|
||||
|
||||
export async function seedPerfState(scenarioId: PerfSeedScenarioId): Promise<PerfSeededState> {
|
||||
const scenario = getPerfSeedScenario(scenarioId);
|
||||
const templateDir = await getTemplateDir(scenarioId);
|
||||
const runParentDir = await mkdtemp(join(tmpdir(), `t3-perf-run-${scenarioId}-`));
|
||||
const baseDir = join(runParentDir, "base");
|
||||
await cp(templateDir, baseDir, { recursive: true, force: true });
|
||||
const primaryProject = scenario.projects[0];
|
||||
if (!primaryProject) {
|
||||
throw new Error(`Perf scenario '${scenarioId}' has no projects.`);
|
||||
}
|
||||
const workspaceRoot = join(baseDir, primaryProject.workspaceDirectoryName);
|
||||
|
||||
const snapshotLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceRoot, baseDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtime = ManagedRuntime.make(snapshotLayer);
|
||||
const snapshot = await runtime.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
return yield* snapshotQuery.getSnapshot();
|
||||
}),
|
||||
);
|
||||
await runtime.dispose();
|
||||
|
||||
return {
|
||||
scenarioId,
|
||||
runParentDir,
|
||||
baseDir,
|
||||
workspaceRoot,
|
||||
snapshot,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,920 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { performance } from "node:perf_hooks";
|
||||
|
||||
import {
|
||||
type ClientOrchestrationCommand,
|
||||
CommandId,
|
||||
MessageId,
|
||||
type ModelSelection,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type OrchestrationEvent,
|
||||
type ProjectId,
|
||||
type TerminalEvent,
|
||||
ThreadId,
|
||||
type ThreadId as ThreadIdType,
|
||||
WS_METHODS,
|
||||
} from "@t3tools/contracts";
|
||||
import { PERF_CATALOG_IDS } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
type ServerCommandLatencyMeasurement,
|
||||
startServerPerfHarness,
|
||||
summarizeCommandLatencyMeasurements,
|
||||
summarizeRpcLatencySeries,
|
||||
type ServerPerfHarness,
|
||||
type ServerRpcLatencySeries,
|
||||
} from "./serverPerfHarness.ts";
|
||||
import type { PerfLatencySample } from "@t3tools/shared/perf/artifact";
|
||||
|
||||
const CONTROL_PLANE_SAMPLE_COUNT = 4;
|
||||
const GIT_RPC_SAMPLE_COUNT = 6;
|
||||
const STREAM_THREAD_COUNT = 5;
|
||||
const SPAM_THREAD_COUNT = 8;
|
||||
const TERMINAL_SESSION_COUNT = 3;
|
||||
const TERMINAL_OUTPUT_LINE_COUNT = 260;
|
||||
const TERMINAL_OUTPUT_SLEEP_SECONDS = 0.04;
|
||||
const GIT_BRANCH_COUNT = 240;
|
||||
const GIT_UNTRACKED_FILE_COUNT = 160;
|
||||
const DEFAULT_WAIT_TIMEOUT_MS = 45_000;
|
||||
|
||||
interface SubscriptionCleanup {
|
||||
readonly dispose: () => void;
|
||||
}
|
||||
|
||||
interface EventWaiter<TValue, TResult> {
|
||||
readonly description: string;
|
||||
readonly select: (values: ReadonlyArray<TValue>) => TResult | null;
|
||||
readonly resolve: (value: TResult) => void;
|
||||
readonly reject: (error: Error) => void;
|
||||
readonly timer: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
class BufferedEventFeed<TValue> implements SubscriptionCleanup {
|
||||
private readonly values: TValue[] = [];
|
||||
private readonly waiters = new Set<EventWaiter<TValue, unknown>>();
|
||||
|
||||
push(value: TValue) {
|
||||
this.values.push(value);
|
||||
for (const waiter of this.waiters) {
|
||||
const match = waiter.select(this.values);
|
||||
if (match === null) {
|
||||
continue;
|
||||
}
|
||||
clearTimeout(waiter.timer);
|
||||
this.waiters.delete(waiter);
|
||||
waiter.resolve(match);
|
||||
}
|
||||
}
|
||||
|
||||
waitFor<TResult>(
|
||||
description: string,
|
||||
select: (values: ReadonlyArray<TValue>) => TResult | null,
|
||||
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
|
||||
): Promise<TResult> {
|
||||
const immediateMatch = select(this.values);
|
||||
if (immediateMatch !== null) {
|
||||
return Promise.resolve(immediateMatch);
|
||||
}
|
||||
|
||||
return new Promise<TResult>((resolve, reject) => {
|
||||
const waiter: EventWaiter<TValue, TResult> = {
|
||||
description,
|
||||
select,
|
||||
resolve,
|
||||
reject,
|
||||
timer: setTimeout(() => {
|
||||
this.waiters.delete(waiter as EventWaiter<TValue, unknown>);
|
||||
reject(new Error(`Timed out waiting for ${description} after ${timeoutMs}ms.`));
|
||||
}, timeoutMs),
|
||||
};
|
||||
this.waiters.add(waiter as EventWaiter<TValue, unknown>);
|
||||
});
|
||||
}
|
||||
|
||||
waitForEvent(
|
||||
description: string,
|
||||
predicate: (value: TValue) => boolean,
|
||||
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
|
||||
): Promise<TValue> {
|
||||
return this.waitFor(description, (values) => values.find(predicate) ?? null, timeoutMs);
|
||||
}
|
||||
|
||||
waitForCount(
|
||||
description: string,
|
||||
predicate: (value: TValue) => boolean,
|
||||
count: number,
|
||||
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
|
||||
): Promise<ReadonlyArray<TValue>> {
|
||||
return this.waitFor(
|
||||
description,
|
||||
(values) => {
|
||||
const matches = values.filter(predicate);
|
||||
return matches.length >= count ? matches.slice(0, count) : null;
|
||||
},
|
||||
timeoutMs,
|
||||
);
|
||||
}
|
||||
|
||||
waitForDistinct<TKey extends string | number>(
|
||||
description: string,
|
||||
predicate: (value: TValue) => boolean,
|
||||
selectKey: (value: TValue) => TKey,
|
||||
count: number,
|
||||
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
|
||||
): Promise<ReadonlyArray<TValue>> {
|
||||
return this.waitFor(
|
||||
description,
|
||||
(values) => {
|
||||
const distinctMatches = new Map<TKey, TValue>();
|
||||
for (const value of values) {
|
||||
if (!predicate(value)) {
|
||||
continue;
|
||||
}
|
||||
const key = selectKey(value);
|
||||
if (!distinctMatches.has(key)) {
|
||||
distinctMatches.set(key, value);
|
||||
}
|
||||
}
|
||||
const matches = [...distinctMatches.values()];
|
||||
return matches.length >= count ? matches : null;
|
||||
},
|
||||
timeoutMs,
|
||||
);
|
||||
}
|
||||
|
||||
dispose() {
|
||||
for (const waiter of this.waiters) {
|
||||
clearTimeout(waiter.timer);
|
||||
waiter.reject(new Error(`Buffered feed disposed while waiting for ${waiter.description}.`));
|
||||
}
|
||||
this.waiters.clear();
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(delayMs: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
execFileSync("git", args, {
|
||||
cwd,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
encoding: "utf8",
|
||||
});
|
||||
}
|
||||
|
||||
function makeControlThreadId(label: string): ThreadIdType {
|
||||
return ThreadId.makeUnsafe(`perf-control-${label}-${crypto.randomUUID()}`);
|
||||
}
|
||||
|
||||
function makeCommandId(label: string) {
|
||||
return CommandId.makeUnsafe(`perf-command:${label}:${crypto.randomUUID()}`);
|
||||
}
|
||||
|
||||
function makeMessageId(label: string) {
|
||||
return MessageId.makeUnsafe(`perf-message:${label}:${crypto.randomUUID()}`);
|
||||
}
|
||||
|
||||
async function dispatchCommand(harness: ServerPerfHarness, command: ClientOrchestrationCommand) {
|
||||
return await harness.rpc.request((client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand](command),
|
||||
);
|
||||
}
|
||||
|
||||
async function measureCommandLatency(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly command: ClientOrchestrationCommand;
|
||||
readonly expectedEventType: OrchestrationEvent["type"];
|
||||
readonly loadProfile: string;
|
||||
readonly timeoutMs?: number;
|
||||
readonly metadata?: Record<string, unknown>;
|
||||
}): Promise<ServerCommandLatencyMeasurement> {
|
||||
const startedAt = nowIso();
|
||||
const startedAtMs = performance.now();
|
||||
const result = await dispatchCommand(input.harness, input.command);
|
||||
const ackAtMs = performance.now();
|
||||
const event = await input.orchestrationEvents.waitForEvent(
|
||||
`${input.expectedEventType} for ${input.command.type}`,
|
||||
(candidate) =>
|
||||
candidate.type === input.expectedEventType &&
|
||||
String(candidate.commandId) === String(input.command.commandId),
|
||||
input.timeoutMs,
|
||||
);
|
||||
const eventAtMs = performance.now();
|
||||
|
||||
return {
|
||||
commandType: input.command.type,
|
||||
loadProfile: input.loadProfile,
|
||||
startedAt,
|
||||
dispatchToAckMs: ackAtMs - startedAtMs,
|
||||
dispatchToEventMs: eventAtMs - startedAtMs,
|
||||
ackToEventMs: eventAtMs - ackAtMs,
|
||||
resultSequence: result.sequence,
|
||||
eventSequence: event.sequence,
|
||||
...(input.metadata ? { metadata: input.metadata } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function createSupportThread(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly projectId: ProjectId;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly label: string;
|
||||
}): Promise<ThreadIdType> {
|
||||
const threadId = makeControlThreadId(`load-${input.label}`);
|
||||
const command = {
|
||||
type: "thread.create",
|
||||
commandId: makeCommandId(`load-thread-create-${input.label}`),
|
||||
threadId,
|
||||
projectId: input.projectId,
|
||||
title: `Perf Load ${input.label}`,
|
||||
modelSelection: input.modelSelection,
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: nowIso(),
|
||||
} as const satisfies ClientOrchestrationCommand;
|
||||
|
||||
await dispatchCommand(input.harness, command);
|
||||
await input.orchestrationEvents.waitForEvent(
|
||||
`thread.created for load support thread ${input.label}`,
|
||||
(event) => event.type === "thread.created" && event.payload.threadId === threadId,
|
||||
);
|
||||
return threadId;
|
||||
}
|
||||
|
||||
async function captureCreateArchiveSamples(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly loadProfile: string;
|
||||
readonly sampleCount: number;
|
||||
readonly projectId: ProjectId;
|
||||
readonly modelSelection: ModelSelection;
|
||||
}): Promise<ReadonlyArray<ServerCommandLatencyMeasurement>> {
|
||||
const samples: ServerCommandLatencyMeasurement[] = [];
|
||||
|
||||
for (let sampleIndex = 0; sampleIndex < input.sampleCount; sampleIndex += 1) {
|
||||
const threadId = makeControlThreadId(`${input.loadProfile}-${sampleIndex + 1}`);
|
||||
const createCommand = {
|
||||
type: "thread.create",
|
||||
commandId: makeCommandId(`thread-create-${input.loadProfile}-${sampleIndex + 1}`),
|
||||
threadId,
|
||||
projectId: input.projectId,
|
||||
title: `Perf ${input.loadProfile} ${sampleIndex + 1}`,
|
||||
modelSelection: input.modelSelection,
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: nowIso(),
|
||||
} as const satisfies ClientOrchestrationCommand;
|
||||
|
||||
samples.push(
|
||||
await measureCommandLatency({
|
||||
harness: input.harness,
|
||||
orchestrationEvents: input.orchestrationEvents,
|
||||
command: createCommand,
|
||||
expectedEventType: "thread.created",
|
||||
loadProfile: input.loadProfile,
|
||||
metadata: {
|
||||
sampleIndex: sampleIndex + 1,
|
||||
threadId,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const archiveCommand = {
|
||||
type: "thread.archive",
|
||||
commandId: makeCommandId(`thread-archive-${input.loadProfile}-${sampleIndex + 1}`),
|
||||
threadId,
|
||||
} as const satisfies ClientOrchestrationCommand;
|
||||
|
||||
samples.push(
|
||||
await measureCommandLatency({
|
||||
harness: input.harness,
|
||||
orchestrationEvents: input.orchestrationEvents,
|
||||
command: archiveCommand,
|
||||
expectedEventType: "thread.archived",
|
||||
loadProfile: input.loadProfile,
|
||||
metadata: {
|
||||
sampleIndex: sampleIndex + 1,
|
||||
threadId,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return samples;
|
||||
}
|
||||
|
||||
async function ensureStreamingThreads(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly projectId: ProjectId;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly count: number;
|
||||
}): Promise<ReadonlyArray<ThreadIdType>> {
|
||||
const threadIds: ThreadIdType[] = [
|
||||
PERF_CATALOG_IDS.burstBase.burstThreadId,
|
||||
PERF_CATALOG_IDS.burstBase.navigationThreadId,
|
||||
PERF_CATALOG_IDS.burstBase.fillerThreadId,
|
||||
];
|
||||
|
||||
while (threadIds.length < input.count) {
|
||||
threadIds.push(
|
||||
await createSupportThread({
|
||||
harness: input.harness,
|
||||
orchestrationEvents: input.orchestrationEvents,
|
||||
projectId: input.projectId,
|
||||
modelSelection: input.modelSelection,
|
||||
label: `stream-${threadIds.length + 1}`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return threadIds;
|
||||
}
|
||||
|
||||
async function startAssistantStreamingLoad(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly threadIds: ReadonlyArray<ThreadIdType>;
|
||||
readonly label: string;
|
||||
}): Promise<void> {
|
||||
await Promise.all(
|
||||
input.threadIds.map((threadId, index) =>
|
||||
dispatchCommand(input.harness, {
|
||||
type: "thread.turn.start",
|
||||
commandId: makeCommandId(`${input.label}-turn-start-${index + 1}`),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: makeMessageId(`${input.label}-turn-${index + 1}`),
|
||||
role: "user",
|
||||
text: `Perf load ${input.label} ${index + 1}`,
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
createdAt: nowIso(),
|
||||
} as const satisfies ClientOrchestrationCommand),
|
||||
),
|
||||
);
|
||||
|
||||
const threadIds = new Set(input.threadIds.map(String));
|
||||
await input.orchestrationEvents.waitForDistinct(
|
||||
`assistant streaming output for ${input.label}`,
|
||||
(event) =>
|
||||
event.type === "thread.message-sent" &&
|
||||
event.payload.role === "assistant" &&
|
||||
event.payload.streaming &&
|
||||
threadIds.has(String(event.payload.threadId)),
|
||||
(event) => (event.type === "thread.message-sent" ? String(event.payload.threadId) : ""),
|
||||
input.threadIds.length,
|
||||
);
|
||||
}
|
||||
|
||||
async function startCreateTurnSpamLoad(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly projectId: ProjectId;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly count: number;
|
||||
readonly label: string;
|
||||
}): Promise<{
|
||||
readonly threadIds: ReadonlyArray<ThreadIdType>;
|
||||
readonly done: Promise<ReadonlyArray<ThreadIdType>>;
|
||||
}> {
|
||||
const threadIds = Array.from({ length: input.count }, (_, index) =>
|
||||
makeControlThreadId(`${input.label}-${index + 1}`),
|
||||
);
|
||||
const threadIdStrings = new Set(threadIds.map(String));
|
||||
|
||||
const done = Promise.all(
|
||||
threadIds.map(async (threadId, index) => {
|
||||
const createCommand = {
|
||||
type: "thread.create",
|
||||
commandId: makeCommandId(`${input.label}-create-${index + 1}`),
|
||||
threadId,
|
||||
projectId: input.projectId,
|
||||
title: `Perf Spam ${index + 1}`,
|
||||
modelSelection: input.modelSelection,
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: nowIso(),
|
||||
} as const satisfies ClientOrchestrationCommand;
|
||||
await dispatchCommand(input.harness, createCommand);
|
||||
await input.orchestrationEvents.waitForEvent(
|
||||
`thread.created for ${input.label}-${index + 1}`,
|
||||
(event) => event.type === "thread.created" && event.payload.threadId === threadId,
|
||||
);
|
||||
await dispatchCommand(input.harness, {
|
||||
type: "thread.turn.start",
|
||||
commandId: makeCommandId(`${input.label}-turn-start-${index + 1}`),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: makeMessageId(`${input.label}-turn-${index + 1}`),
|
||||
role: "user",
|
||||
text: `Perf spam ${input.label} ${index + 1}`,
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
createdAt: nowIso(),
|
||||
} as const satisfies ClientOrchestrationCommand);
|
||||
return threadId;
|
||||
}),
|
||||
);
|
||||
|
||||
await input.orchestrationEvents.waitForCount(
|
||||
`thread.create spam ${input.label}`,
|
||||
(event) =>
|
||||
event.type === "thread.created" && threadIdStrings.has(String(event.payload.threadId)),
|
||||
Math.min(4, input.count),
|
||||
);
|
||||
await input.orchestrationEvents.waitForDistinct(
|
||||
`assistant spam output ${input.label}`,
|
||||
(event) =>
|
||||
event.type === "thread.message-sent" &&
|
||||
event.payload.role === "assistant" &&
|
||||
event.payload.streaming &&
|
||||
threadIdStrings.has(String(event.payload.threadId)),
|
||||
(event) => (event.type === "thread.message-sent" ? String(event.payload.threadId) : ""),
|
||||
Math.min(4, input.count),
|
||||
);
|
||||
|
||||
return {
|
||||
threadIds,
|
||||
done,
|
||||
};
|
||||
}
|
||||
|
||||
async function startTerminalLoad(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly terminalEvents: BufferedEventFeed<TerminalEvent>;
|
||||
readonly workspaceRoot: string;
|
||||
readonly threadIds: ReadonlyArray<ThreadIdType>;
|
||||
}): Promise<ReadonlyArray<{ readonly threadId: ThreadIdType; readonly terminalId: string }>> {
|
||||
const sessions = await Promise.all(
|
||||
input.threadIds.slice(0, TERMINAL_SESSION_COUNT).map(async (threadId, index) => {
|
||||
const terminalId = `perf-${index + 1}`;
|
||||
await input.harness.rpc.request((client) =>
|
||||
client[WS_METHODS.terminalOpen]({
|
||||
threadId,
|
||||
terminalId,
|
||||
cwd: input.workspaceRoot,
|
||||
cols: 120,
|
||||
rows: 32,
|
||||
}),
|
||||
);
|
||||
|
||||
const command = [
|
||||
"i=1",
|
||||
`while [ $i -le ${TERMINAL_OUTPUT_LINE_COUNT} ]`,
|
||||
"do",
|
||||
` printf 'perf-terminal-${index + 1}-%03d\\n' "$i"`,
|
||||
" i=$((i + 1))",
|
||||
` sleep ${TERMINAL_OUTPUT_SLEEP_SECONDS.toFixed(2)}`,
|
||||
"done",
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
await input.harness.rpc.request((client) =>
|
||||
client[WS_METHODS.terminalWrite]({
|
||||
threadId,
|
||||
terminalId,
|
||||
data: command,
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
threadId,
|
||||
terminalId,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
const terminalIds = new Set(sessions.map((session) => session.terminalId));
|
||||
await input.terminalEvents.waitForDistinct(
|
||||
"terminal output load",
|
||||
(event) => event.type === "output" && terminalIds.has(event.terminalId),
|
||||
(event) => event.terminalId,
|
||||
sessions.length,
|
||||
30_000,
|
||||
);
|
||||
|
||||
return sessions;
|
||||
}
|
||||
|
||||
async function closeTerminalLoad(
|
||||
harness: ServerPerfHarness,
|
||||
sessions: ReadonlyArray<{ readonly threadId: ThreadIdType; readonly terminalId: string }>,
|
||||
): Promise<void> {
|
||||
await Promise.all(
|
||||
sessions.map((session) =>
|
||||
harness.rpc.request((client) =>
|
||||
client[WS_METHODS.terminalClose]({
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
deleteHistory: true,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async function seedGitPressure(workspaceRoot: string): Promise<void> {
|
||||
const untrackedDir = join(workspaceRoot, "perf-git-pressure");
|
||||
await mkdir(untrackedDir, { recursive: true });
|
||||
await Promise.all(
|
||||
Array.from({ length: GIT_UNTRACKED_FILE_COUNT }, (_, index) =>
|
||||
writeFile(
|
||||
join(untrackedDir, `untracked-${(index + 1).toString().padStart(3, "0")}.ts`),
|
||||
`export const perfFile${index + 1} = ${index + 1};\n`,
|
||||
"utf8",
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
for (let index = 0; index < GIT_BRANCH_COUNT; index += 1) {
|
||||
runGit(workspaceRoot, ["branch", `perf/latency-${(index + 1).toString().padStart(4, "0")}`]);
|
||||
}
|
||||
}
|
||||
|
||||
async function measureRpcLatencySeries<TResult>(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly name: string;
|
||||
readonly loadProfile: string;
|
||||
readonly iterations: number;
|
||||
readonly execute: () => Promise<TResult>;
|
||||
}): Promise<ServerRpcLatencySeries> {
|
||||
const samples: PerfLatencySample[] = [];
|
||||
|
||||
for (let iteration = 0; iteration < input.iterations; iteration += 1) {
|
||||
const startedAt = nowIso();
|
||||
const startedAtMs = performance.now();
|
||||
await input.execute();
|
||||
const endedAtMs = performance.now();
|
||||
samples.push({
|
||||
name: `${input.name}-${iteration + 1}`,
|
||||
durationMs: endedAtMs - startedAtMs,
|
||||
startedAt,
|
||||
endedAt: nowIso(),
|
||||
metadata: {
|
||||
iteration: iteration + 1,
|
||||
loadProfile: input.loadProfile,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
name: input.name,
|
||||
loadProfile: input.loadProfile,
|
||||
summary: summarizeRpcLatencySeries(samples),
|
||||
samples,
|
||||
};
|
||||
}
|
||||
|
||||
function groupCommandSeries(
|
||||
samples: ReadonlyArray<ServerCommandLatencyMeasurement>,
|
||||
loadProfile: string,
|
||||
) {
|
||||
const createSamples = samples.filter((sample) => sample.commandType === "thread.create");
|
||||
const archiveSamples = samples.filter((sample) => sample.commandType === "thread.archive");
|
||||
|
||||
return [
|
||||
{
|
||||
name: "thread.create",
|
||||
loadProfile,
|
||||
summary: summarizeCommandLatencyMeasurements(createSamples),
|
||||
samples: createSamples,
|
||||
},
|
||||
{
|
||||
name: "thread.archive",
|
||||
loadProfile,
|
||||
summary: summarizeCommandLatencyMeasurements(archiveSamples),
|
||||
samples: archiveSamples,
|
||||
},
|
||||
] as const;
|
||||
}
|
||||
|
||||
describe("server perf latency", () => {
|
||||
const disposables: Array<SubscriptionCleanup> = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const disposable of disposables.splice(0)) {
|
||||
disposable.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("records idle and assistant-stream command latency at the websocket boundary", async () => {
|
||||
let harness: ServerPerfHarness | null = null;
|
||||
|
||||
try {
|
||||
harness = await startServerPerfHarness({
|
||||
suite: "server-latency-critical-commands",
|
||||
seedScenarioId: "burst_base",
|
||||
providerScenarioId: "parallel_assistant_stream",
|
||||
});
|
||||
const runStartedAt = nowIso();
|
||||
|
||||
const burstProject = harness.seededState.snapshot.projects.find(
|
||||
(project) => project.id === PERF_CATALOG_IDS.burstBase.burstProjectId,
|
||||
);
|
||||
expect(burstProject).toBeTruthy();
|
||||
const modelSelection = burstProject!.defaultModelSelection;
|
||||
expect(modelSelection).toBeTruthy();
|
||||
|
||||
const orchestrationEvents = new BufferedEventFeed<OrchestrationEvent>();
|
||||
disposables.push(orchestrationEvents);
|
||||
disposables.push({
|
||||
dispose: harness.rpc.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeOrchestrationDomainEvents]({}),
|
||||
(event) => orchestrationEvents.push(event),
|
||||
),
|
||||
});
|
||||
|
||||
await sleep(250);
|
||||
|
||||
const idleSamples = await captureCreateArchiveSamples({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
loadProfile: "idle",
|
||||
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
});
|
||||
|
||||
const streamingThreadIds = await ensureStreamingThreads({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
count: STREAM_THREAD_COUNT,
|
||||
});
|
||||
await startAssistantStreamingLoad({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
threadIds: streamingThreadIds,
|
||||
label: "stream-control-plane",
|
||||
});
|
||||
|
||||
const streamingSamples = await captureCreateArchiveSamples({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
loadProfile: "assistant-stream-5x",
|
||||
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
});
|
||||
const spamLoad = await startCreateTurnSpamLoad({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
count: SPAM_THREAD_COUNT,
|
||||
label: "create-turn-spam-8x",
|
||||
});
|
||||
const spamSamples = await captureCreateArchiveSamples({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
loadProfile: "create-turn-spam-8x",
|
||||
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
});
|
||||
await spamLoad.done;
|
||||
|
||||
const commandLatency = [
|
||||
...groupCommandSeries(idleSamples, "idle"),
|
||||
...groupCommandSeries(streamingSamples, "assistant-stream-5x"),
|
||||
...groupCommandSeries(spamSamples, "create-turn-spam-8x"),
|
||||
];
|
||||
const result = await harness.finishRun({
|
||||
artifactBasename: "control-plane-stream-baseline",
|
||||
artifact: {
|
||||
suite: "server-latency-critical-commands",
|
||||
scenarioId: "burst_base_control_plane_stream_baseline",
|
||||
startedAt: runStartedAt,
|
||||
completedAt: nowIso(),
|
||||
commandLatency,
|
||||
rpcLatency: [],
|
||||
metadata: {
|
||||
sampleCountPerProfile: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
streamingThreadCount: STREAM_THREAD_COUNT,
|
||||
spamThreadCount: SPAM_THREAD_COUNT,
|
||||
},
|
||||
},
|
||||
});
|
||||
harness = null;
|
||||
|
||||
expect(result.artifact.commandLatency).toHaveLength(6);
|
||||
for (const series of result.artifact.commandLatency) {
|
||||
expect(series.samples).toHaveLength(CONTROL_PLANE_SAMPLE_COUNT);
|
||||
expect(series.summary.dispatchToEventMs.p50Ms).not.toBeNull();
|
||||
expect(series.summary.dispatchToEventMs.maxMs).toBeLessThan(30_000);
|
||||
}
|
||||
} finally {
|
||||
await harness?.dispose();
|
||||
}
|
||||
}, 180_000);
|
||||
|
||||
it("records command and git rpc latency under terminal and mixed server load", async () => {
|
||||
let harness: ServerPerfHarness | null = null;
|
||||
let terminalSessions: ReadonlyArray<{
|
||||
readonly threadId: ThreadIdType;
|
||||
readonly terminalId: string;
|
||||
}> = [];
|
||||
|
||||
try {
|
||||
harness = await startServerPerfHarness({
|
||||
suite: "server-latency-critical-commands",
|
||||
seedScenarioId: "burst_base",
|
||||
providerScenarioId: "parallel_assistant_stream",
|
||||
});
|
||||
const runStartedAt = nowIso();
|
||||
|
||||
const burstProject = harness.seededState.snapshot.projects.find(
|
||||
(project) => project.id === PERF_CATALOG_IDS.burstBase.burstProjectId,
|
||||
);
|
||||
expect(burstProject).toBeTruthy();
|
||||
const modelSelection = burstProject!.defaultModelSelection;
|
||||
expect(modelSelection).toBeTruthy();
|
||||
|
||||
const orchestrationEvents = new BufferedEventFeed<OrchestrationEvent>();
|
||||
const terminalEvents = new BufferedEventFeed<TerminalEvent>();
|
||||
disposables.push(orchestrationEvents, terminalEvents);
|
||||
disposables.push({
|
||||
dispose: harness.rpc.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeOrchestrationDomainEvents]({}),
|
||||
(event) => orchestrationEvents.push(event),
|
||||
),
|
||||
});
|
||||
disposables.push({
|
||||
dispose: harness.rpc.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeTerminalEvents]({}),
|
||||
(event) => terminalEvents.push(event),
|
||||
),
|
||||
});
|
||||
|
||||
await sleep(250);
|
||||
await seedGitPressure(harness.seededState.workspaceRoot);
|
||||
|
||||
const gitLatencyIdle = await Promise.all([
|
||||
measureRpcLatencySeries({
|
||||
harness,
|
||||
name: "git.status",
|
||||
loadProfile: "idle-repo-pressure",
|
||||
iterations: GIT_RPC_SAMPLE_COUNT,
|
||||
execute: () =>
|
||||
harness!.rpc.request((client) =>
|
||||
client[WS_METHODS.gitStatus]({
|
||||
cwd: harness!.seededState.workspaceRoot,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
measureRpcLatencySeries({
|
||||
harness,
|
||||
name: "git.listBranches",
|
||||
loadProfile: "idle-repo-pressure",
|
||||
iterations: GIT_RPC_SAMPLE_COUNT,
|
||||
execute: () =>
|
||||
harness!.rpc.request((client) =>
|
||||
client[WS_METHODS.gitListBranches]({
|
||||
cwd: harness!.seededState.workspaceRoot,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
]);
|
||||
|
||||
const streamingThreadIds = await ensureStreamingThreads({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
count: STREAM_THREAD_COUNT,
|
||||
});
|
||||
|
||||
terminalSessions = await startTerminalLoad({
|
||||
harness,
|
||||
terminalEvents,
|
||||
workspaceRoot: harness.seededState.workspaceRoot,
|
||||
threadIds: streamingThreadIds,
|
||||
});
|
||||
|
||||
const terminalSamples = await captureCreateArchiveSamples({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
loadProfile: "terminal-output-3x",
|
||||
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
});
|
||||
|
||||
await sleep(6_500);
|
||||
await startAssistantStreamingLoad({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
threadIds: streamingThreadIds,
|
||||
label: "mixed-load",
|
||||
});
|
||||
await terminalEvents.waitForCount(
|
||||
"continued terminal output during mixed load",
|
||||
(event) =>
|
||||
event.type === "output" &&
|
||||
terminalSessions.some((session) => session.terminalId === event.terminalId),
|
||||
TERMINAL_SESSION_COUNT,
|
||||
30_000,
|
||||
);
|
||||
|
||||
const mixedSamples = await captureCreateArchiveSamples({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
loadProfile: "mixed-stream-terminal-git",
|
||||
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
});
|
||||
|
||||
const gitLatencyMixed = await Promise.all([
|
||||
measureRpcLatencySeries({
|
||||
harness,
|
||||
name: "git.status",
|
||||
loadProfile: "mixed-stream-terminal-git",
|
||||
iterations: GIT_RPC_SAMPLE_COUNT,
|
||||
execute: () =>
|
||||
harness!.rpc.request((client) =>
|
||||
client[WS_METHODS.gitStatus]({
|
||||
cwd: harness!.seededState.workspaceRoot,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
measureRpcLatencySeries({
|
||||
harness,
|
||||
name: "git.listBranches",
|
||||
loadProfile: "mixed-stream-terminal-git",
|
||||
iterations: GIT_RPC_SAMPLE_COUNT,
|
||||
execute: () =>
|
||||
harness!.rpc.request((client) =>
|
||||
client[WS_METHODS.gitListBranches]({
|
||||
cwd: harness!.seededState.workspaceRoot,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
]);
|
||||
|
||||
await closeTerminalLoad(harness, terminalSessions);
|
||||
terminalSessions = [];
|
||||
|
||||
const result = await harness.finishRun({
|
||||
artifactBasename: "terminal-mixed-git-baseline",
|
||||
artifact: {
|
||||
suite: "server-latency-critical-commands",
|
||||
scenarioId: "burst_base_terminal_mixed_git_baseline",
|
||||
startedAt: runStartedAt,
|
||||
completedAt: nowIso(),
|
||||
commandLatency: [
|
||||
...groupCommandSeries(terminalSamples, "terminal-output-3x"),
|
||||
...groupCommandSeries(mixedSamples, "mixed-stream-terminal-git"),
|
||||
],
|
||||
rpcLatency: [...gitLatencyIdle, ...gitLatencyMixed],
|
||||
metadata: {
|
||||
sampleCountPerProfile: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
gitRpcSampleCount: GIT_RPC_SAMPLE_COUNT,
|
||||
branchCount: GIT_BRANCH_COUNT,
|
||||
untrackedFileCount: GIT_UNTRACKED_FILE_COUNT,
|
||||
terminalSessionCount: TERMINAL_SESSION_COUNT,
|
||||
},
|
||||
},
|
||||
});
|
||||
harness = null;
|
||||
|
||||
expect(result.artifact.commandLatency).toHaveLength(4);
|
||||
expect(result.artifact.rpcLatency).toHaveLength(4);
|
||||
for (const series of result.artifact.commandLatency) {
|
||||
expect(series.samples).toHaveLength(CONTROL_PLANE_SAMPLE_COUNT);
|
||||
expect(series.summary.dispatchToEventMs.maxMs).toBeLessThan(30_000);
|
||||
}
|
||||
for (const series of result.artifact.rpcLatency) {
|
||||
expect(series.samples).toHaveLength(GIT_RPC_SAMPLE_COUNT);
|
||||
expect(series.summary.maxMs).toBeLessThan(30_000);
|
||||
}
|
||||
} finally {
|
||||
if (harness && terminalSessions.length > 0) {
|
||||
await closeTerminalLoad(harness, terminalSessions).catch(() => undefined);
|
||||
}
|
||||
await harness?.dispose();
|
||||
}
|
||||
}, 180_000);
|
||||
});
|
||||
@@ -0,0 +1,393 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { createServer } from "node:net";
|
||||
import { join, resolve } from "node:path";
|
||||
import { performance } from "node:perf_hooks";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import * as NodeSocket from "@effect/platform-node/NodeSocket";
|
||||
import {
|
||||
type OrchestrationEvent,
|
||||
type TerminalEvent,
|
||||
WS_METHODS,
|
||||
WsRpcGroup,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
Effect,
|
||||
Exit,
|
||||
Layer,
|
||||
ManagedRuntime,
|
||||
Scope,
|
||||
Stream,
|
||||
type Scope as ScopeService,
|
||||
} from "effect";
|
||||
import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
|
||||
import {
|
||||
summarizeLatencySamples,
|
||||
summarizeLatencyValues,
|
||||
type PerfLatencySample,
|
||||
type PerfLatencySummary,
|
||||
writeJsonArtifact,
|
||||
} from "@t3tools/shared/perf/artifact";
|
||||
import type {
|
||||
PerfProviderScenarioId,
|
||||
PerfSeedScenarioId,
|
||||
} from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { seedPerfState, type PerfSeededState } from "./seedPerfState.ts";
|
||||
|
||||
const repoRoot = fileURLToPath(new URL("../../../../", import.meta.url));
|
||||
const PERF_ARTIFACT_DIR_ENV = "T3CODE_PERF_ARTIFACT_DIR";
|
||||
const PERF_PROVIDER_ENV = "T3CODE_PERF_PROVIDER";
|
||||
const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO";
|
||||
const AUTO_BOOTSTRAP_PROJECT_ENV = "T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD";
|
||||
|
||||
const makeWsRpcClient = RpcClient.make(WsRpcGroup);
|
||||
type WsRpcClient =
|
||||
typeof makeWsRpcClient extends Effect.Effect<infer Client, any, any> ? Client : never;
|
||||
|
||||
export interface ServerCommandLatencyMeasurement {
|
||||
readonly commandType: string;
|
||||
readonly loadProfile: string;
|
||||
readonly startedAt: string;
|
||||
readonly dispatchToAckMs: number;
|
||||
readonly dispatchToEventMs: number;
|
||||
readonly ackToEventMs: number;
|
||||
readonly resultSequence: number;
|
||||
readonly eventSequence: number;
|
||||
readonly metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface ServerCommandLatencySummary {
|
||||
readonly count: number;
|
||||
readonly dispatchToAckMs: PerfLatencySummary;
|
||||
readonly dispatchToEventMs: PerfLatencySummary;
|
||||
readonly ackToEventMs: PerfLatencySummary;
|
||||
}
|
||||
|
||||
export interface ServerCommandLatencySeries {
|
||||
readonly name: string;
|
||||
readonly loadProfile: string;
|
||||
readonly summary: ServerCommandLatencySummary;
|
||||
readonly samples: ReadonlyArray<ServerCommandLatencyMeasurement>;
|
||||
}
|
||||
|
||||
export interface ServerRpcLatencySeries {
|
||||
readonly name: string;
|
||||
readonly loadProfile: string;
|
||||
readonly summary: PerfLatencySummary;
|
||||
readonly samples: ReadonlyArray<PerfLatencySample>;
|
||||
}
|
||||
|
||||
export interface ServerPerfRunArtifact {
|
||||
readonly suite: string;
|
||||
readonly scenarioId: string;
|
||||
readonly startedAt: string;
|
||||
readonly completedAt: string;
|
||||
readonly commandLatency: ReadonlyArray<ServerCommandLatencySeries>;
|
||||
readonly rpcLatency: ReadonlyArray<ServerRpcLatencySeries>;
|
||||
readonly metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
interface StartServerPerfHarnessOptions {
|
||||
readonly suite: string;
|
||||
readonly seedScenarioId: PerfSeedScenarioId;
|
||||
readonly providerScenarioId?: PerfProviderScenarioId;
|
||||
}
|
||||
|
||||
interface FinishServerPerfRunOptions {
|
||||
readonly artifactBasename?: string;
|
||||
readonly artifact: ServerPerfRunArtifact;
|
||||
}
|
||||
|
||||
export interface ServerPerfHarness {
|
||||
readonly seededState: PerfSeededState;
|
||||
readonly wsUrl: string;
|
||||
readonly artifactDir: string;
|
||||
readonly rpc: PerfWsRpcClient;
|
||||
readonly finishRun: (options: FinishServerPerfRunOptions) => Promise<{
|
||||
readonly artifactPath: string;
|
||||
readonly artifact: ServerPerfRunArtifact;
|
||||
}>;
|
||||
readonly dispose: () => Promise<void>;
|
||||
}
|
||||
|
||||
const wsRpcProtocolLayer = (wsUrl: string) =>
|
||||
RpcClient.layerProtocolSocket().pipe(
|
||||
Layer.provide(NodeSocket.layerWebSocket(wsUrl)),
|
||||
Layer.provide(RpcSerialization.layerJson),
|
||||
);
|
||||
|
||||
async function pickFreePort(): Promise<number> {
|
||||
return await new Promise<number>((resolvePort, reject) => {
|
||||
const server = createServer();
|
||||
server.on("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") {
|
||||
reject(new Error("Unable to resolve a free localhost port."));
|
||||
return;
|
||||
}
|
||||
const { port } = address;
|
||||
server.close((closeError) => {
|
||||
if (closeError) {
|
||||
reject(closeError);
|
||||
return;
|
||||
}
|
||||
resolvePort(port);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function stopChildProcess(process: ChildProcess): Promise<void> {
|
||||
if (process.exitCode !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
process.kill("SIGTERM");
|
||||
const exited = await new Promise<boolean>((resolveExited) => {
|
||||
const timer = setTimeout(() => resolveExited(false), 5_000);
|
||||
process.once("exit", () => {
|
||||
clearTimeout(timer);
|
||||
resolveExited(true);
|
||||
});
|
||||
});
|
||||
|
||||
if (!exited && process.exitCode === null) {
|
||||
process.kill("SIGKILL");
|
||||
await new Promise<void>((resolveExited) => {
|
||||
process.once("exit", () => resolveExited());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureArtifactDir(suite: string, scenarioId: string): Promise<string> {
|
||||
const baseArtifactDir = resolve(
|
||||
process.env[PERF_ARTIFACT_DIR_ENV] ?? join(repoRoot, "artifacts/perf/server"),
|
||||
);
|
||||
const runId = `${suite}-${scenarioId}-${Date.now().toString()}`;
|
||||
const artifactDir = join(baseArtifactDir, runId);
|
||||
await mkdir(artifactDir, { recursive: true });
|
||||
return artifactDir;
|
||||
}
|
||||
|
||||
async function writeServerLogs(
|
||||
artifactDir: string,
|
||||
stdout: string,
|
||||
stderr: string,
|
||||
basename: string,
|
||||
): Promise<void> {
|
||||
await mkdir(artifactDir, { recursive: true });
|
||||
await Promise.all([
|
||||
writeFile(join(artifactDir, `${basename}.server.stdout.log`), stdout, "utf8"),
|
||||
writeFile(join(artifactDir, `${basename}.server.stderr.log`), stderr, "utf8"),
|
||||
]);
|
||||
}
|
||||
|
||||
function buildPerfServerEnv(
|
||||
baseEnv: NodeJS.ProcessEnv,
|
||||
providerScenarioId?: PerfProviderScenarioId,
|
||||
): NodeJS.ProcessEnv {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
...baseEnv,
|
||||
[AUTO_BOOTSTRAP_PROJECT_ENV]: "false",
|
||||
};
|
||||
|
||||
if (!providerScenarioId) {
|
||||
delete env[PERF_PROVIDER_ENV];
|
||||
delete env[PERF_SCENARIO_ENV];
|
||||
return env;
|
||||
}
|
||||
|
||||
return {
|
||||
...env,
|
||||
[PERF_PROVIDER_ENV]: "1",
|
||||
[PERF_SCENARIO_ENV]: providerScenarioId,
|
||||
};
|
||||
}
|
||||
|
||||
export class PerfWsRpcClient {
|
||||
private readonly runtime: ManagedRuntime.ManagedRuntime<RpcClient.Protocol, never>;
|
||||
private readonly clientScope: Scope.Closeable;
|
||||
private readonly clientPromise: Promise<WsRpcClient>;
|
||||
private disposed = false;
|
||||
|
||||
constructor(private readonly wsUrl: string) {
|
||||
this.runtime = ManagedRuntime.make(wsRpcProtocolLayer(wsUrl));
|
||||
this.clientScope = this.runtime.runSync(Scope.make());
|
||||
this.clientPromise = this.runtime.runPromise(Scope.provide(this.clientScope)(makeWsRpcClient));
|
||||
}
|
||||
|
||||
async request<TSuccess, TError>(
|
||||
execute: (client: WsRpcClient) => Effect.Effect<TSuccess, TError, never>,
|
||||
): Promise<TSuccess> {
|
||||
if (this.disposed) {
|
||||
throw new Error(`WebSocket RPC client disposed for ${this.wsUrl}`);
|
||||
}
|
||||
|
||||
const client = await this.clientPromise;
|
||||
return await this.runtime.runPromise(Effect.suspend(() => execute(client)));
|
||||
}
|
||||
|
||||
subscribe<TValue>(
|
||||
connect: (client: WsRpcClient) => Stream.Stream<TValue, Error, never>,
|
||||
listener: (value: TValue) => void,
|
||||
): () => void {
|
||||
if (this.disposed) {
|
||||
return () => undefined;
|
||||
}
|
||||
|
||||
let active = true;
|
||||
const cancel = this.runtime.runCallback(
|
||||
Effect.promise(() => this.clientPromise).pipe(
|
||||
Effect.flatMap((client) =>
|
||||
Stream.runForEach(connect(client), (value) =>
|
||||
Effect.sync(() => {
|
||||
if (!active) {
|
||||
return;
|
||||
}
|
||||
listener(value);
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
cancel();
|
||||
};
|
||||
}
|
||||
|
||||
async dispose(): Promise<void> {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
this.disposed = true;
|
||||
await this.runtime.runPromise(Scope.close(this.clientScope, Exit.void));
|
||||
await this.runtime.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForRpcReady(wsUrl: string, process: ChildProcess): Promise<void> {
|
||||
const startedAtMs = performance.now();
|
||||
const timeoutMs = 45_000;
|
||||
|
||||
while (performance.now() - startedAtMs < timeoutMs) {
|
||||
if (process.exitCode !== null) {
|
||||
throw new Error(`Perf server exited early with code ${process.exitCode}.`);
|
||||
}
|
||||
|
||||
const client = new PerfWsRpcClient(wsUrl);
|
||||
try {
|
||||
await client.request((rpcClient) => rpcClient[WS_METHODS.serverGetSettings]({}));
|
||||
await client.dispose();
|
||||
return;
|
||||
} catch {
|
||||
await client.dispose().catch(() => undefined);
|
||||
await new Promise((resolveDelay) => setTimeout(resolveDelay, 200));
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Timed out waiting for websocket readiness at ${wsUrl}.`);
|
||||
}
|
||||
|
||||
export function summarizeCommandLatencyMeasurements(
|
||||
samples: ReadonlyArray<ServerCommandLatencyMeasurement>,
|
||||
): ServerCommandLatencySummary {
|
||||
return {
|
||||
count: samples.length,
|
||||
dispatchToAckMs: summarizeLatencyValues(samples.map((sample) => sample.dispatchToAckMs)),
|
||||
dispatchToEventMs: summarizeLatencyValues(samples.map((sample) => sample.dispatchToEventMs)),
|
||||
ackToEventMs: summarizeLatencyValues(samples.map((sample) => sample.ackToEventMs)),
|
||||
};
|
||||
}
|
||||
|
||||
export function summarizeRpcLatencySeries(
|
||||
samples: ReadonlyArray<PerfLatencySample>,
|
||||
): PerfLatencySummary {
|
||||
return summarizeLatencySamples(samples);
|
||||
}
|
||||
|
||||
export async function startServerPerfHarness(
|
||||
options: StartServerPerfHarnessOptions,
|
||||
): Promise<ServerPerfHarness> {
|
||||
const seededState = await seedPerfState(options.seedScenarioId);
|
||||
const artifactDir = await ensureArtifactDir(options.suite, options.seedScenarioId);
|
||||
const port = await pickFreePort();
|
||||
const wsUrl = `ws://127.0.0.1:${port}/ws`;
|
||||
const env = buildPerfServerEnv(process.env, options.providerScenarioId);
|
||||
|
||||
let stdoutBuffer = "";
|
||||
let stderrBuffer = "";
|
||||
let finished = false;
|
||||
const serverProcess = spawn(
|
||||
"bun",
|
||||
[
|
||||
"run",
|
||||
"apps/server/src/bin.ts",
|
||||
"--mode",
|
||||
"web",
|
||||
"--host",
|
||||
"127.0.0.1",
|
||||
"--port",
|
||||
`${port}`,
|
||||
"--base-dir",
|
||||
seededState.baseDir,
|
||||
"--no-browser",
|
||||
],
|
||||
{
|
||||
cwd: repoRoot,
|
||||
env,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
},
|
||||
);
|
||||
serverProcess.stdout?.on("data", (chunk) => {
|
||||
stdoutBuffer += chunk.toString();
|
||||
});
|
||||
serverProcess.stderr?.on("data", (chunk) => {
|
||||
stderrBuffer += chunk.toString();
|
||||
});
|
||||
|
||||
const cleanup = async () => {
|
||||
if (finished) {
|
||||
return;
|
||||
}
|
||||
finished = true;
|
||||
await stopChildProcess(serverProcess);
|
||||
await rm(seededState.runParentDir, { recursive: true, force: true });
|
||||
};
|
||||
|
||||
try {
|
||||
await waitForRpcReady(wsUrl, serverProcess);
|
||||
const rpc = new PerfWsRpcClient(wsUrl);
|
||||
|
||||
return {
|
||||
seededState,
|
||||
wsUrl,
|
||||
artifactDir,
|
||||
rpc,
|
||||
finishRun: async ({ artifactBasename, artifact }) => {
|
||||
const basename = artifactBasename ?? `${artifact.suite}-${artifact.scenarioId}`;
|
||||
await rpc.dispose();
|
||||
await cleanup();
|
||||
await writeServerLogs(artifactDir, stdoutBuffer, stderrBuffer, basename);
|
||||
const artifactPath = join(artifactDir, `${basename}.json`);
|
||||
await writeJsonArtifact(artifactPath, artifact);
|
||||
return {
|
||||
artifactPath,
|
||||
artifact,
|
||||
};
|
||||
},
|
||||
dispose: async () => {
|
||||
await rpc.dispose().catch(() => undefined);
|
||||
await cleanup();
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
await cleanup();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export type { OrchestrationEvent, ScopeService, TerminalEvent, WsRpcClient };
|
||||
@@ -86,6 +86,7 @@ const collectEventsDuring = <A, E, R>(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
yield* Effect.sleep("50 millis");
|
||||
yield* action;
|
||||
|
||||
return yield* Effect.forEach(
|
||||
@@ -104,7 +105,6 @@ const runTurn = (input: {
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
yield* input.harness.queueTurnResponse(input.threadId, input.response);
|
||||
|
||||
return yield* collectEventsDuring(
|
||||
input.provider.streamEvents,
|
||||
input.response.events.length,
|
||||
@@ -116,21 +116,18 @@ const runTurn = (input: {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("replays typed runtime fixture events", () =>
|
||||
it.live("replays typed runtime fixture events", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-typed"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-typed"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
|
||||
threadId: ThreadId.make("thread-integration-typed"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
const observedEvents = yield* runTurn({
|
||||
@@ -149,7 +146,7 @@ it.effect("replays typed runtime fixture events", () =>
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("replays file-changing fixture turn events", () =>
|
||||
it.live("replays file-changing fixture turn events", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const { join } = yield* Path.Path;
|
||||
@@ -157,15 +154,12 @@ it.effect("replays file-changing fixture turn events", () =>
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-tools"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-tools"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
|
||||
threadId: ThreadId.make("thread-integration-tools"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
const observedEvents = yield* runTurn({
|
||||
@@ -188,7 +182,7 @@ it.effect("replays file-changing fixture turn events", () =>
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("runs multi-turn tool/approval flow", () =>
|
||||
it.live("runs multi-turn tool/approval flow", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const { join } = yield* Path.Path;
|
||||
@@ -196,15 +190,12 @@ it.effect("runs multi-turn tool/approval flow", () =>
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-multi"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-multi"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
|
||||
threadId: ThreadId.make("thread-integration-multi"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
const firstTurnEvents = yield* runTurn({
|
||||
@@ -242,7 +233,7 @@ it.effect("runs multi-turn tool/approval flow", () =>
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("rolls back provider conversation state only", () =>
|
||||
it.live("rolls back provider conversation state only", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const { join } = yield* Path.Path;
|
||||
@@ -250,15 +241,12 @@ it.effect("rolls back provider conversation state only", () =>
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-rollback"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-rollback"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
|
||||
threadId: ThreadId.make("thread-integration-rollback"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
yield* runTurn({
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.15",
|
||||
"version": "0.0.17",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -20,7 +20,8 @@
|
||||
"start": "node dist/bin.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
"test": "vitest run",
|
||||
"test:perf": "vitest run integration/perf"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
|
||||
|
||||
+124
-101
@@ -14,6 +14,22 @@ import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog
|
||||
import rootPackageJson from "../../../package.json" with { type: "json" };
|
||||
import serverPackageJson from "../package.json" with { type: "json" };
|
||||
|
||||
interface PackageJson {
|
||||
name: string;
|
||||
repository: {
|
||||
type: string;
|
||||
url: string;
|
||||
directory: string;
|
||||
};
|
||||
bin: Record<string, string>;
|
||||
type: string;
|
||||
version: string;
|
||||
engines: Record<string, string>;
|
||||
files: string[];
|
||||
dependencies: Record<string, string>;
|
||||
overrides: Record<string, string>;
|
||||
}
|
||||
|
||||
class CliError extends Data.TaggedError("CliError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
@@ -122,34 +138,35 @@ const buildCmd = Command.make(
|
||||
{
|
||||
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
|
||||
},
|
||||
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");
|
||||
(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");
|
||||
|
||||
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)."));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -166,87 +183,93 @@ const publishCmd = Command.make(
|
||||
dryRun: Flag.boolean("dry-run").pipe(Flag.withDefault(false)),
|
||||
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
|
||||
},
|
||||
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`;
|
||||
(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`;
|
||||
|
||||
// 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/bin.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.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>,
|
||||
};
|
||||
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: PackageJson = {
|
||||
name: serverPackageJson.name,
|
||||
repository: serverPackageJson.repository,
|
||||
bin: serverPackageJson.bin,
|
||||
type: serverPackageJson.type,
|
||||
version,
|
||||
engines: serverPackageJson.engines,
|
||||
files: serverPackageJson.files,
|
||||
dependencies: serverPackageJson.dependencies,
|
||||
overrides: rootPackageJson.overrides,
|
||||
};
|
||||
|
||||
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",
|
||||
}),
|
||||
pkg.dependencies = resolveCatalogDependencies(
|
||||
pkg.dependencies,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"apps/server dependencies",
|
||||
);
|
||||
})(),
|
||||
// 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");
|
||||
}),
|
||||
);
|
||||
}),
|
||||
pkg.overrides = resolveCatalogDependencies(
|
||||
pkg.overrides,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"root overrides",
|
||||
);
|
||||
|
||||
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");
|
||||
}),
|
||||
);
|
||||
}),
|
||||
).pipe(Command.withDescription("Publish the server package to npm."));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { join } from "node:path";
|
||||
|
||||
import { seedPerfState } from "../integration/perf/seedPerfState.ts";
|
||||
import { getPerfSeedScenario } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
|
||||
const PERF_SEED_JSON_START = "__T3_PERF_SEED_JSON_START__";
|
||||
const PERF_SEED_JSON_END = "__T3_PERF_SEED_JSON_END__";
|
||||
const scenarioId = process.argv[2];
|
||||
|
||||
if (scenarioId !== "large_threads" && scenarioId !== "burst_base") {
|
||||
console.error(`Expected a perf seed scenario id, received '${scenarioId ?? "<missing>"}'.`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const seeded = await seedPerfState(scenarioId);
|
||||
const scenario = getPerfSeedScenario(scenarioId);
|
||||
const scenarioProjectById = new Map(scenario.projects.map((project) => [project.id, project]));
|
||||
const scenarioThreadById = new Map(scenario.threads.map((thread) => [thread.id, thread]));
|
||||
const projectById = new Map(seeded.snapshot.projects.map((project) => [project.id, project]));
|
||||
const payload = JSON.stringify(
|
||||
{
|
||||
scenarioId: seeded.scenarioId,
|
||||
runParentDir: seeded.runParentDir,
|
||||
baseDir: seeded.baseDir,
|
||||
workspaceRoot: seeded.workspaceRoot,
|
||||
projectTitle: seeded.snapshot.projects[0]?.title ?? null,
|
||||
projectSummaries: seeded.snapshot.projects.map((project) => ({
|
||||
id: project.id,
|
||||
title: project.title,
|
||||
workspaceRoot:
|
||||
scenarioProjectById.get(project.id)?.workspaceDirectoryName !== undefined
|
||||
? join(seeded.baseDir, scenarioProjectById.get(project.id)?.workspaceDirectoryName ?? "")
|
||||
: project.workspaceRoot,
|
||||
threadCount: seeded.snapshot.threads.filter((thread) => thread.projectId === project.id)
|
||||
.length,
|
||||
})),
|
||||
threadSummaries: seeded.snapshot.threads.map((thread) => ({
|
||||
id: thread.id,
|
||||
projectId: thread.projectId,
|
||||
projectTitle: projectById.get(thread.projectId)?.title ?? null,
|
||||
title: thread.title,
|
||||
turnCount: scenarioThreadById.get(thread.id)?.turnCount ?? null,
|
||||
messageCount: thread.messages.length,
|
||||
activityCount: thread.activities.length,
|
||||
proposedPlanCount: thread.proposedPlans.length,
|
||||
checkpointCount: thread.checkpoints.length,
|
||||
})),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
process.stdout.write(`${PERF_SEED_JSON_START}\n${payload}\n${PERF_SEED_JSON_END}\n`);
|
||||
@@ -0,0 +1,111 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import { ServerConfigShape } from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
|
||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
||||
import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { AuthControlPlane } from "../Services/AuthControlPlane.ts";
|
||||
import { makeAuthControlPlane } from "./AuthControlPlane.ts";
|
||||
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
|
||||
|
||||
const makeServerConfigLayer = (
|
||||
overrides?: Partial<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())),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,176 @@
|
||||
import type { AuthClientSession, AuthPairingLink } from "@t3tools/contracts";
|
||||
import { DateTime, Effect, Layer } from "effect";
|
||||
|
||||
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
|
||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
||||
import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
|
||||
import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
|
||||
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "../../persistence/Layers/Sqlite.ts";
|
||||
import {
|
||||
AuthControlPlane,
|
||||
AuthControlPlaneError,
|
||||
AuthControlPlaneShape,
|
||||
DEFAULT_SESSION_SUBJECT,
|
||||
IssuedBearerSession,
|
||||
IssuedPairingLink,
|
||||
} from "../Services/AuthControlPlane.ts";
|
||||
|
||||
const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {
|
||||
if (left.role !== right.role) {
|
||||
return left.role === "owner" ? -1 : 1;
|
||||
}
|
||||
if (left.connected !== right.connected) {
|
||||
return left.connected ? -1 : 1;
|
||||
}
|
||||
return right.issuedAt.epochMilliseconds - left.issuedAt.epochMilliseconds;
|
||||
};
|
||||
|
||||
const toAuthControlPlaneError =
|
||||
(message: string) =>
|
||||
(cause: unknown): AuthControlPlaneError =>
|
||||
new AuthControlPlaneError({
|
||||
message,
|
||||
cause,
|
||||
});
|
||||
|
||||
export const makeAuthControlPlane = Effect.gen(function* () {
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
const sessions = yield* SessionCredentialService;
|
||||
|
||||
const createPairingLink: AuthControlPlaneShape["createPairingLink"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const createdAt = yield* DateTime.now;
|
||||
const issued = yield* bootstrapCredentials.issueOneTimeToken({
|
||||
role: input?.role ?? "client",
|
||||
subject: input?.subject ?? "one-time-token",
|
||||
...(input?.ttl ? { ttl: input.ttl } : {}),
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
});
|
||||
return {
|
||||
id: issued.id,
|
||||
credential: issued.credential,
|
||||
role: input?.role ?? "client",
|
||||
subject: input?.subject ?? "one-time-token",
|
||||
...(issued.label ? { label: issued.label } : {}),
|
||||
createdAt: DateTime.toUtc(createdAt),
|
||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
||||
} satisfies IssuedPairingLink;
|
||||
}).pipe(Effect.mapError(toAuthControlPlaneError("Failed to create pairing link.")));
|
||||
|
||||
const listPairingLinks: AuthControlPlaneShape["listPairingLinks"] = (input) =>
|
||||
bootstrapCredentials.listActive().pipe(
|
||||
Effect.map((pairingLinks) =>
|
||||
pairingLinks
|
||||
.filter((pairingLink) => (input?.role ? pairingLink.role === input.role : true))
|
||||
.filter((pairingLink) => !input?.excludeSubjects?.includes(pairingLink.subject))
|
||||
.map((pairingLink) =>
|
||||
pairingLink.label
|
||||
? ({
|
||||
id: pairingLink.id,
|
||||
credential: pairingLink.credential,
|
||||
role: pairingLink.role,
|
||||
subject: pairingLink.subject,
|
||||
label: pairingLink.label,
|
||||
createdAt: pairingLink.createdAt,
|
||||
expiresAt: pairingLink.expiresAt,
|
||||
} satisfies AuthPairingLink)
|
||||
: ({
|
||||
id: pairingLink.id,
|
||||
credential: pairingLink.credential,
|
||||
role: pairingLink.role,
|
||||
subject: pairingLink.subject,
|
||||
createdAt: pairingLink.createdAt,
|
||||
expiresAt: pairingLink.expiresAt,
|
||||
} satisfies AuthPairingLink),
|
||||
)
|
||||
.toSorted(
|
||||
(left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
|
||||
),
|
||||
),
|
||||
Effect.mapError(toAuthControlPlaneError("Failed to list pairing links.")),
|
||||
);
|
||||
|
||||
const revokePairingLink: AuthControlPlaneShape["revokePairingLink"] = (id) =>
|
||||
bootstrapCredentials
|
||||
.revoke(id)
|
||||
.pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke pairing link.")));
|
||||
|
||||
const issueSession: AuthControlPlaneShape["issueSession"] = (input) =>
|
||||
sessions
|
||||
.issue({
|
||||
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
|
||||
method: "bearer-session-token",
|
||||
role: input?.role ?? "owner",
|
||||
client: {
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
deviceType: "bot",
|
||||
},
|
||||
...(input?.ttl ? { ttl: input.ttl } : {}),
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap((issued) => {
|
||||
if (issued.method !== "bearer-session-token") {
|
||||
return Effect.fail(
|
||||
new AuthControlPlaneError({
|
||||
message: "CLI session issuance produced an unexpected session method.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed({
|
||||
sessionId: issued.sessionId,
|
||||
token: issued.token,
|
||||
method: "bearer-session-token" as const,
|
||||
role: issued.role,
|
||||
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
|
||||
client: issued.client,
|
||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
||||
} satisfies IssuedBearerSession);
|
||||
}),
|
||||
Effect.mapError(toAuthControlPlaneError("Failed to issue session token.")),
|
||||
);
|
||||
|
||||
const listSessions: AuthControlPlaneShape["listSessions"] = () =>
|
||||
sessions.listActive().pipe(
|
||||
Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)),
|
||||
Effect.mapError(toAuthControlPlaneError("Failed to list sessions.")),
|
||||
);
|
||||
|
||||
const revokeSession: AuthControlPlaneShape["revokeSession"] = (sessionId) =>
|
||||
sessions
|
||||
.revoke(sessionId)
|
||||
.pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke session.")));
|
||||
|
||||
const revokeOtherSessionsExcept: AuthControlPlaneShape["revokeOtherSessionsExcept"] = (
|
||||
sessionId,
|
||||
) =>
|
||||
sessions
|
||||
.revokeAllExcept(sessionId)
|
||||
.pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke other sessions.")));
|
||||
|
||||
return {
|
||||
createPairingLink,
|
||||
listPairingLinks,
|
||||
revokePairingLink,
|
||||
issueSession,
|
||||
listSessions,
|
||||
revokeSession,
|
||||
revokeOtherSessionsExcept,
|
||||
} satisfies AuthControlPlaneShape;
|
||||
});
|
||||
|
||||
export const AuthCoreLive = Layer.mergeAll(
|
||||
BootstrapCredentialServiceLive,
|
||||
SessionCredentialServiceLive,
|
||||
);
|
||||
|
||||
export const AuthStorageLive = Layer.mergeAll(ServerSecretStoreLive, SqlitePersistenceLayerLive);
|
||||
|
||||
export const AuthRuntimeLive = AuthCoreLive.pipe(Layer.provideMerge(AuthStorageLive));
|
||||
|
||||
export const AuthControlPlaneLive = Layer.effect(AuthControlPlane, makeAuthControlPlane);
|
||||
|
||||
export const AuthControlPlaneRuntimeLive = AuthControlPlaneLive.pipe(
|
||||
Layer.provideMerge(AuthRuntimeLive),
|
||||
);
|
||||
@@ -0,0 +1,151 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Duration, Effect, Layer } from "effect";
|
||||
import { TestClock } from "effect/testing";
|
||||
|
||||
import type { ServerConfigShape } from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
|
||||
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
|
||||
|
||||
const makeServerConfigLayer = (
|
||||
overrides?: Partial<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())),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,296 @@
|
||||
import type { AuthPairingLink } from "@t3tools/contracts";
|
||||
import { DateTime, Duration, Effect, Layer, PubSub, Ref, Stream } from "effect";
|
||||
import { Option } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { AuthPairingLinkRepositoryLive } from "../../persistence/Layers/AuthPairingLinks.ts";
|
||||
import { AuthPairingLinkRepository } from "../../persistence/Services/AuthPairingLinks.ts";
|
||||
import {
|
||||
BootstrapCredentialError,
|
||||
BootstrapCredentialService,
|
||||
type BootstrapCredentialChange,
|
||||
type BootstrapCredentialServiceShape,
|
||||
type BootstrapGrant,
|
||||
type IssuedBootstrapCredential,
|
||||
} from "../Services/BootstrapCredentialService.ts";
|
||||
|
||||
interface StoredBootstrapGrant extends BootstrapGrant {
|
||||
readonly remainingUses: number | "unbounded";
|
||||
}
|
||||
|
||||
type ConsumeResult =
|
||||
| {
|
||||
readonly _tag: "error";
|
||||
readonly reason: "not-found" | "expired";
|
||||
readonly error: BootstrapCredentialError;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "success";
|
||||
readonly grant: BootstrapGrant;
|
||||
};
|
||||
|
||||
const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
|
||||
const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
|
||||
const PAIRING_TOKEN_LENGTH = 12;
|
||||
|
||||
const generatePairingToken = (): string => {
|
||||
const randomBytes = crypto.getRandomValues(new Uint8Array(PAIRING_TOKEN_LENGTH));
|
||||
|
||||
return Array.from(randomBytes, (value) => PAIRING_TOKEN_ALPHABET[value & 31]).join("");
|
||||
};
|
||||
|
||||
export const makeBootstrapCredentialService = Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
const pairingLinks = yield* AuthPairingLinkRepository;
|
||||
const seededGrantsRef = yield* Ref.make(new Map<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));
|
||||
@@ -0,0 +1,182 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import type { ServerConfigShape } from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts";
|
||||
import { ServerAuth, type ServerAuthShape } from "../Services/ServerAuth.ts";
|
||||
import { ServerAuthLive, toBootstrapExchangeAuthError } from "./ServerAuth.ts";
|
||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
||||
|
||||
const makeServerConfigLayer = (overrides?: Partial<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",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,395 @@
|
||||
import {
|
||||
type AuthBearerBootstrapResult,
|
||||
type AuthClientSession,
|
||||
type AuthBootstrapResult,
|
||||
type AuthPairingCredentialResult,
|
||||
type AuthSessionState,
|
||||
type AuthWebSocketTokenResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { DateTime, Effect, Layer, Option } from "effect";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
|
||||
import { AuthControlPlane } from "../Services/AuthControlPlane.ts";
|
||||
import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts";
|
||||
import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
|
||||
import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts";
|
||||
import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts";
|
||||
import {
|
||||
ServerAuth,
|
||||
type AuthenticatedSession,
|
||||
AuthError,
|
||||
type ServerAuthShape,
|
||||
} from "../Services/ServerAuth.ts";
|
||||
import {
|
||||
SessionCredentialError,
|
||||
SessionCredentialService,
|
||||
} from "../Services/SessionCredentialService.ts";
|
||||
import { AuthControlPlaneLive, AuthCoreLive } from "./AuthControlPlane.ts";
|
||||
|
||||
type BootstrapExchangeResult = {
|
||||
readonly response: AuthBootstrapResult;
|
||||
readonly sessionToken: string;
|
||||
};
|
||||
|
||||
const AUTHORIZATION_PREFIX = "Bearer ";
|
||||
const WEBSOCKET_TOKEN_QUERY_PARAM = "wsToken";
|
||||
|
||||
export function toBootstrapExchangeAuthError(cause: BootstrapCredentialError): AuthError {
|
||||
if (cause.status === 500) {
|
||||
return new AuthError({
|
||||
message: "Failed to validate bootstrap credential.",
|
||||
status: 500,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
return new AuthError({
|
||||
message: "Invalid bootstrap credential.",
|
||||
status: 401,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {
|
||||
const header = request.headers["authorization"];
|
||||
if (typeof header !== "string" || !header.startsWith(AUTHORIZATION_PREFIX)) {
|
||||
return null;
|
||||
}
|
||||
const token = header.slice(AUTHORIZATION_PREFIX.length).trim();
|
||||
return token.length > 0 ? token : null;
|
||||
}
|
||||
|
||||
export const makeServerAuth = Effect.gen(function* () {
|
||||
const policy = yield* ServerAuthPolicy;
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
const authControlPlane = yield* AuthControlPlane;
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
const authenticateToken = (token: string): Effect.Effect<AuthenticatedSession, AuthError> =>
|
||||
sessions.verify(token).pipe(
|
||||
Effect.tapError((cause: SessionCredentialError) =>
|
||||
Effect.logWarning("Rejected authenticated session credential.").pipe(
|
||||
Effect.annotateLogs({
|
||||
reason: cause.message,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.map((session) => ({
|
||||
sessionId: session.sessionId,
|
||||
subject: session.subject,
|
||||
method: session.method,
|
||||
role: session.role,
|
||||
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
|
||||
})),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Unauthorized request.",
|
||||
status: 401,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const authenticateRequest = (request: HttpServerRequest.HttpServerRequest) => {
|
||||
const cookieToken = request.cookies[sessions.cookieName];
|
||||
const bearerToken = parseBearerToken(request);
|
||||
const credential = cookieToken ?? bearerToken;
|
||||
if (!credential) {
|
||||
return Effect.fail(
|
||||
new AuthError({
|
||||
message: "Authentication required.",
|
||||
status: 401,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return authenticateToken(credential);
|
||||
};
|
||||
|
||||
const getSessionState: ServerAuthShape["getSessionState"] = (request) =>
|
||||
authenticateRequest(request).pipe(
|
||||
Effect.map(
|
||||
(session) =>
|
||||
({
|
||||
authenticated: true,
|
||||
auth: descriptor,
|
||||
role: session.role,
|
||||
sessionMethod: session.method,
|
||||
...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
|
||||
}) satisfies AuthSessionState,
|
||||
),
|
||||
Effect.catchTag("AuthError", () =>
|
||||
Effect.succeed({
|
||||
authenticated: false,
|
||||
auth: descriptor,
|
||||
} satisfies AuthSessionState),
|
||||
),
|
||||
);
|
||||
|
||||
const exchangeBootstrapCredential: ServerAuthShape["exchangeBootstrapCredential"] = (
|
||||
credential,
|
||||
requestMetadata,
|
||||
) =>
|
||||
bootstrapCredentials.consume(credential).pipe(
|
||||
Effect.mapError(toBootstrapExchangeAuthError),
|
||||
Effect.flatMap((grant) =>
|
||||
sessions
|
||||
.issue({
|
||||
method: "browser-session-cookie",
|
||||
subject: grant.subject,
|
||||
role: grant.role,
|
||||
client: {
|
||||
...requestMetadata,
|
||||
...(grant.label ? { label: grant.label } : {}),
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to issue authenticated session.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map(
|
||||
(session) =>
|
||||
({
|
||||
response: {
|
||||
authenticated: true,
|
||||
role: session.role,
|
||||
sessionMethod: session.method,
|
||||
expiresAt: DateTime.toUtc(session.expiresAt),
|
||||
} satisfies AuthBootstrapResult,
|
||||
sessionToken: session.token,
|
||||
}) satisfies BootstrapExchangeResult,
|
||||
),
|
||||
);
|
||||
|
||||
const exchangeBootstrapCredentialForBearerSession: ServerAuthShape["exchangeBootstrapCredentialForBearerSession"] =
|
||||
(credential, requestMetadata) =>
|
||||
bootstrapCredentials.consume(credential).pipe(
|
||||
Effect.mapError(toBootstrapExchangeAuthError),
|
||||
Effect.flatMap((grant) =>
|
||||
sessions
|
||||
.issue({
|
||||
method: "bearer-session-token",
|
||||
subject: grant.subject,
|
||||
role: grant.role,
|
||||
client: {
|
||||
...requestMetadata,
|
||||
...(grant.label ? { label: grant.label } : {}),
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to issue authenticated session.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map(
|
||||
(session) =>
|
||||
({
|
||||
authenticated: true,
|
||||
role: session.role,
|
||||
sessionMethod: "bearer-session-token",
|
||||
expiresAt: DateTime.toUtc(session.expiresAt),
|
||||
sessionToken: session.token,
|
||||
}) satisfies AuthBearerBootstrapResult,
|
||||
),
|
||||
);
|
||||
|
||||
const issuePairingCredential: ServerAuthShape["issuePairingCredential"] = (input) =>
|
||||
authControlPlane
|
||||
.createPairingLink({
|
||||
role: input?.role ?? "client",
|
||||
subject: input?.role === "owner" ? "owner-bootstrap" : "one-time-token",
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to issue pairing credential.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.map(
|
||||
(issued) =>
|
||||
({
|
||||
id: issued.id,
|
||||
credential: issued.credential,
|
||||
...(issued.label ? { label: issued.label } : {}),
|
||||
expiresAt: issued.expiresAt,
|
||||
}) satisfies AuthPairingCredentialResult,
|
||||
),
|
||||
);
|
||||
|
||||
const listPairingLinks: ServerAuthShape["listPairingLinks"] = () =>
|
||||
authControlPlane
|
||||
.listPairingLinks({
|
||||
role: "client",
|
||||
excludeSubjects: ["owner-bootstrap"],
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to load pairing links.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const revokePairingLink: ServerAuthShape["revokePairingLink"] = (id) =>
|
||||
authControlPlane.revokePairingLink(id).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to revoke pairing link.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const listClientSessions: ServerAuthShape["listClientSessions"] = (currentSessionId) =>
|
||||
authControlPlane.listSessions().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to load paired clients.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.map((clientSessions) =>
|
||||
clientSessions.map(
|
||||
(clientSession): AuthClientSession => ({
|
||||
...clientSession,
|
||||
current: clientSession.sessionId === currentSessionId,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const revokeClientSession: ServerAuthShape["revokeClientSession"] = (
|
||||
currentSessionId,
|
||||
targetSessionId,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
if (currentSessionId === targetSessionId) {
|
||||
return yield* new AuthError({
|
||||
message: "Use revoke other clients to keep the current owner session active.",
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
return yield* authControlPlane.revokeSession(targetSessionId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to revoke client session.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const revokeOtherClientSessions: ServerAuthShape["revokeOtherClientSessions"] = (
|
||||
currentSessionId,
|
||||
) =>
|
||||
authControlPlane.revokeOtherSessionsExcept(currentSessionId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to revoke other client sessions.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const issueStartupPairingUrl: ServerAuthShape["issueStartupPairingUrl"] = (baseUrl) =>
|
||||
issuePairingCredential({ role: "owner" }).pipe(
|
||||
Effect.map((issued) => {
|
||||
const url = new URL(baseUrl);
|
||||
url.pathname = "/pair";
|
||||
url.searchParams.delete("token");
|
||||
url.hash = new URLSearchParams([["token", issued.credential]]).toString();
|
||||
return url.toString();
|
||||
}),
|
||||
);
|
||||
|
||||
const issueWebSocketToken: ServerAuthShape["issueWebSocketToken"] = (session) =>
|
||||
sessions.issueWebSocketToken(session.sessionId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to issue websocket token.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.map(
|
||||
(issued) =>
|
||||
({
|
||||
token: issued.token,
|
||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
||||
}) satisfies AuthWebSocketTokenResult,
|
||||
),
|
||||
);
|
||||
|
||||
const authenticateWebSocketUpgrade: ServerAuthShape["authenticateWebSocketUpgrade"] = (request) =>
|
||||
Effect.gen(function* () {
|
||||
const requestUrl = HttpServerRequest.toURL(request);
|
||||
if (Option.isSome(requestUrl)) {
|
||||
const websocketToken = requestUrl.value.searchParams.get(WEBSOCKET_TOKEN_QUERY_PARAM);
|
||||
if (websocketToken && websocketToken.trim().length > 0) {
|
||||
return yield* sessions.verifyWebSocketToken(websocketToken).pipe(
|
||||
Effect.map((session) => ({
|
||||
sessionId: session.sessionId,
|
||||
subject: session.subject,
|
||||
method: session.method,
|
||||
role: session.role,
|
||||
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
|
||||
})),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Unauthorized request.",
|
||||
status: 401,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return yield* authenticateRequest(request);
|
||||
});
|
||||
|
||||
return {
|
||||
getDescriptor: () => Effect.succeed(descriptor),
|
||||
getSessionState,
|
||||
exchangeBootstrapCredential,
|
||||
exchangeBootstrapCredentialForBearerSession,
|
||||
issuePairingCredential,
|
||||
listPairingLinks,
|
||||
revokePairingLink,
|
||||
listClientSessions,
|
||||
revokeClientSession,
|
||||
revokeOtherClientSessions,
|
||||
authenticateHttpRequest: authenticateRequest,
|
||||
authenticateWebSocketUpgrade,
|
||||
issueWebSocketToken,
|
||||
issueStartupPairingUrl,
|
||||
} satisfies ServerAuthShape;
|
||||
});
|
||||
|
||||
export const ServerAuthLive = Layer.effect(ServerAuth, makeServerAuth).pipe(
|
||||
Layer.provideMerge(AuthControlPlaneLive),
|
||||
Layer.provideMerge(AuthCoreLive),
|
||||
Layer.provideMerge(ServerAuthPolicyLive),
|
||||
);
|
||||
@@ -0,0 +1,114 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import type { ServerConfigShape } from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts";
|
||||
import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts";
|
||||
|
||||
const makeServerAuthPolicyLayer = (overrides?: Partial<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"]);
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session_3773");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
mode: "desktop",
|
||||
port: 3773,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses remote-reachable policy for desktop mode when bound beyond loopback", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* ServerAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.policy).toBe("remote-reachable");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap", "one-time-token"]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
mode: "desktop",
|
||||
host: "0.0.0.0",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses loopback-browser policy for loopback web hosts", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* ServerAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.policy).toBe("loopback-browser");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
mode: "web",
|
||||
host: "127.0.0.1",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses remote-reachable policy for wildcard web hosts", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* ServerAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.policy).toBe("remote-reachable");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
mode: "web",
|
||||
host: "0.0.0.0",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses remote-reachable policy for non-loopback web hosts", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* ServerAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.policy).toBe("remote-reachable");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
mode: "web",
|
||||
host: "192.168.1.50",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { ServerAuthDescriptor } from "@t3tools/contracts";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerAuthPolicy, type ServerAuthPolicyShape } from "../Services/ServerAuthPolicy.ts";
|
||||
import { resolveSessionCookieName } from "../utils.ts";
|
||||
import { isLoopbackHost, isWildcardHost } from "../../startupAccess.ts";
|
||||
|
||||
export const makeServerAuthPolicy = Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
const isRemoteReachable = isWildcardHost(config.host) || !isLoopbackHost(config.host);
|
||||
|
||||
const policy =
|
||||
config.mode === "desktop"
|
||||
? isRemoteReachable
|
||||
? "remote-reachable"
|
||||
: "desktop-managed-local"
|
||||
: isRemoteReachable
|
||||
? "remote-reachable"
|
||||
: "loopback-browser";
|
||||
|
||||
const bootstrapMethods: ServerAuthDescriptor["bootstrapMethods"] =
|
||||
policy === "desktop-managed-local"
|
||||
? ["desktop-bootstrap"]
|
||||
: config.mode === "desktop" && policy === "remote-reachable"
|
||||
? ["desktop-bootstrap", "one-time-token"]
|
||||
: ["one-time-token"];
|
||||
|
||||
const descriptor: ServerAuthDescriptor = {
|
||||
policy,
|
||||
bootstrapMethods,
|
||||
sessionMethods: ["browser-session-cookie", "bearer-session-token"],
|
||||
sessionCookieName: resolveSessionCookieName({
|
||||
mode: config.mode,
|
||||
port: config.port,
|
||||
}),
|
||||
};
|
||||
|
||||
return {
|
||||
getDescriptor: () => Effect.succeed(descriptor),
|
||||
} satisfies ServerAuthPolicyShape;
|
||||
});
|
||||
|
||||
export const ServerAuthPolicyLive = Layer.effect(ServerAuthPolicy, makeServerAuthPolicy);
|
||||
@@ -0,0 +1,263 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Cause, Deferred, Effect, FileSystem, Layer, Ref } from "effect";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { SecretStoreError, ServerSecretStore } from "../Services/ServerSecretStore.ts";
|
||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
||||
|
||||
const makeServerConfigLayer = () =>
|
||||
ServerConfig.layerTest(process.cwd(), { prefix: "t3-secret-store-test-" });
|
||||
|
||||
const makeServerSecretStoreLayer = () =>
|
||||
Layer.provide(ServerSecretStoreLive, makeServerConfigLayer());
|
||||
|
||||
const PermissionDeniedFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
return {
|
||||
...fileSystem,
|
||||
readFile: (path) =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFile",
|
||||
pathOrDescriptor: path,
|
||||
description: "Permission denied while reading secret file.",
|
||||
}),
|
||||
),
|
||||
} satisfies FileSystem.FileSystem;
|
||||
}),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const makePermissionDeniedSecretStoreLayer = () =>
|
||||
ServerSecretStoreLive.pipe(
|
||||
Layer.provide(makeServerConfigLayer()),
|
||||
Layer.provideMerge(PermissionDeniedFileSystemLayer),
|
||||
);
|
||||
|
||||
const RenameFailureFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
return {
|
||||
...fileSystem,
|
||||
rename: (from, to) =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "rename",
|
||||
pathOrDescriptor: `${String(from)} -> ${String(to)}`,
|
||||
description: "Permission denied while persisting secret file.",
|
||||
}),
|
||||
),
|
||||
} satisfies FileSystem.FileSystem;
|
||||
}),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const makeRenameFailureSecretStoreLayer = () =>
|
||||
ServerSecretStoreLive.pipe(
|
||||
Layer.provide(makeServerConfigLayer()),
|
||||
Layer.provideMerge(RenameFailureFileSystemLayer),
|
||||
);
|
||||
|
||||
const RemoveFailureFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
return {
|
||||
...fileSystem,
|
||||
remove: (path, options) =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "remove",
|
||||
pathOrDescriptor: String(path),
|
||||
description: `Permission denied while removing secret file.${options ? " options-set" : ""}`,
|
||||
}),
|
||||
),
|
||||
} satisfies FileSystem.FileSystem;
|
||||
}),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const makeRemoveFailureSecretStoreLayer = () =>
|
||||
ServerSecretStoreLive.pipe(
|
||||
Layer.provide(makeServerConfigLayer()),
|
||||
Layer.provideMerge(RemoveFailureFileSystemLayer),
|
||||
);
|
||||
|
||||
const ConcurrentReadMissFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const readCountRef = yield* Ref.make(0);
|
||||
const readBarrier = yield* Deferred.make<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())),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
import * as Crypto from "node:crypto";
|
||||
|
||||
import { Effect, FileSystem, Layer, Path, Predicate } from "effect";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import {
|
||||
SecretStoreError,
|
||||
ServerSecretStore,
|
||||
type ServerSecretStoreShape,
|
||||
} from "../Services/ServerSecretStore.ts";
|
||||
|
||||
export const makeServerSecretStore = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
|
||||
yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });
|
||||
yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreError({
|
||||
message: `Failed to secure secrets directory ${serverConfig.secretsDir}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
|
||||
|
||||
const isPlatformError = (u: unknown): u is PlatformError.PlatformError =>
|
||||
Predicate.isTagged(u, "PlatformError");
|
||||
|
||||
const get: ServerSecretStoreShape["get"] = (name) =>
|
||||
fileSystem.readFile(resolveSecretPath(name)).pipe(
|
||||
Effect.map((bytes) => Uint8Array.from(bytes)),
|
||||
Effect.catch((cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.succeed(null)
|
||||
: Effect.fail(
|
||||
new SecretStoreError({
|
||||
message: `Failed to read secret ${name}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const set: ServerSecretStoreShape["set"] = (name, value) => {
|
||||
const secretPath = resolveSecretPath(name);
|
||||
const tempPath = `${secretPath}.${Crypto.randomUUID()}.tmp`;
|
||||
return Effect.gen(function* () {
|
||||
yield* fileSystem.writeFile(tempPath, value);
|
||||
yield* fileSystem.chmod(tempPath, 0o600);
|
||||
yield* fileSystem.rename(tempPath, secretPath);
|
||||
yield* fileSystem.chmod(secretPath, 0o600);
|
||||
}).pipe(
|
||||
Effect.catch((cause) =>
|
||||
fileSystem.remove(tempPath).pipe(
|
||||
Effect.ignore,
|
||||
Effect.flatMap(() =>
|
||||
Effect.fail(
|
||||
new SecretStoreError({
|
||||
message: `Failed to persist secret ${name}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const create: ServerSecretStoreShape["set"] = (name, value) => {
|
||||
const secretPath = resolveSecretPath(name);
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const file = yield* fileSystem.open(secretPath, {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
yield* file.writeAll(value);
|
||||
yield* file.sync;
|
||||
yield* fileSystem.chmod(secretPath, 0o600);
|
||||
}),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreError({
|
||||
message: `Failed to persist secret ${name}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const getOrCreateRandom: ServerSecretStoreShape["getOrCreateRandom"] = (name, bytes) =>
|
||||
get(name).pipe(
|
||||
Effect.flatMap((existing) => {
|
||||
if (existing) {
|
||||
return Effect.succeed(existing);
|
||||
}
|
||||
|
||||
const generated = Crypto.randomBytes(bytes);
|
||||
return create(name, generated).pipe(
|
||||
Effect.as(Uint8Array.from(generated)),
|
||||
Effect.catchTag("SecretStoreError", (error) =>
|
||||
isPlatformError(error.cause) && error.cause.reason._tag === "AlreadyExists"
|
||||
? get(name).pipe(
|
||||
Effect.flatMap((created) =>
|
||||
created !== null
|
||||
? Effect.succeed(created)
|
||||
: Effect.fail(
|
||||
new SecretStoreError({
|
||||
message: `Failed to read secret ${name} after concurrent creation.`,
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
: Effect.fail(error),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const remove: ServerSecretStoreShape["remove"] = (name) =>
|
||||
fileSystem.remove(resolveSecretPath(name)).pipe(
|
||||
Effect.catch((cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new SecretStoreError({
|
||||
message: `Failed to remove secret ${name}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
get,
|
||||
set,
|
||||
getOrCreateRandom,
|
||||
remove,
|
||||
} satisfies ServerSecretStoreShape;
|
||||
});
|
||||
|
||||
export const ServerSecretStoreLive = Layer.effect(ServerSecretStore, makeServerSecretStore);
|
||||
@@ -0,0 +1,191 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Duration, Effect, Layer } from "effect";
|
||||
import { TestClock } from "effect/testing";
|
||||
|
||||
import type { ServerConfigShape } from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
|
||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
||||
import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
|
||||
|
||||
const makeServerConfigLayer = (
|
||||
overrides?: Partial<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()))),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,500 @@
|
||||
import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "@t3tools/contracts";
|
||||
import { Clock, DateTime, Duration, Effect, Layer, PubSub, Ref, Schema, Stream } from "effect";
|
||||
import { Option } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts";
|
||||
import { AuthSessionRepository } from "../../persistence/Services/AuthSessions.ts";
|
||||
import { ServerSecretStore } from "../Services/ServerSecretStore.ts";
|
||||
import {
|
||||
SessionCredentialError,
|
||||
SessionCredentialService,
|
||||
type IssuedSession,
|
||||
type SessionCredentialChange,
|
||||
type SessionCredentialServiceShape,
|
||||
type VerifiedSession,
|
||||
} from "../Services/SessionCredentialService.ts";
|
||||
import {
|
||||
base64UrlDecodeUtf8,
|
||||
base64UrlEncode,
|
||||
resolveSessionCookieName,
|
||||
signPayload,
|
||||
timingSafeEqualBase64Url,
|
||||
} from "../utils.ts";
|
||||
|
||||
const SIGNING_SECRET_NAME = "server-signing-key";
|
||||
const DEFAULT_SESSION_TTL = Duration.days(30);
|
||||
const DEFAULT_WEBSOCKET_TOKEN_TTL = Duration.minutes(5);
|
||||
|
||||
const SessionClaims = Schema.Struct({
|
||||
v: Schema.Literal(1),
|
||||
kind: Schema.Literal("session"),
|
||||
sid: AuthSessionId,
|
||||
sub: Schema.String,
|
||||
role: Schema.Literals(["owner", "client"]),
|
||||
method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]),
|
||||
iat: Schema.Number,
|
||||
exp: Schema.Number,
|
||||
});
|
||||
type SessionClaims = typeof SessionClaims.Type;
|
||||
|
||||
const WebSocketClaims = Schema.Struct({
|
||||
v: Schema.Literal(1),
|
||||
kind: Schema.Literal("websocket"),
|
||||
sid: AuthSessionId,
|
||||
iat: Schema.Number,
|
||||
exp: Schema.Number,
|
||||
});
|
||||
type WebSocketClaims = typeof WebSocketClaims.Type;
|
||||
|
||||
const decodeSessionClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(SessionClaims));
|
||||
const decodeWebSocketClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(WebSocketClaims));
|
||||
|
||||
function createDefaultClientMetadata(): AuthClientMetadata {
|
||||
return {
|
||||
deviceType: "unknown",
|
||||
};
|
||||
}
|
||||
|
||||
function toClientMetadata(record: {
|
||||
readonly label: string | null;
|
||||
readonly ipAddress: string | null;
|
||||
readonly userAgent: string | null;
|
||||
readonly deviceType: AuthClientMetadata["deviceType"];
|
||||
readonly os: string | null;
|
||||
readonly browser: string | null;
|
||||
}): AuthClientMetadata {
|
||||
return {
|
||||
...(record.label ? { label: record.label } : {}),
|
||||
...(record.ipAddress ? { ipAddress: record.ipAddress } : {}),
|
||||
...(record.userAgent ? { userAgent: record.userAgent } : {}),
|
||||
deviceType: record.deviceType,
|
||||
...(record.os ? { os: record.os } : {}),
|
||||
...(record.browser ? { browser: record.browser } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthClientSession {
|
||||
return {
|
||||
...input,
|
||||
current: false,
|
||||
};
|
||||
}
|
||||
|
||||
export const makeSessionCredentialService = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
const authSessions = yield* AuthSessionRepository;
|
||||
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
|
||||
const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
|
||||
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
|
||||
const cookieName = resolveSessionCookieName({
|
||||
mode: serverConfig.mode,
|
||||
port: serverConfig.port,
|
||||
});
|
||||
|
||||
const toSessionCredentialError = (message: string) => (cause: unknown) =>
|
||||
new SessionCredentialError({
|
||||
message,
|
||||
cause,
|
||||
});
|
||||
|
||||
const emitUpsert = (clientSession: AuthClientSession) =>
|
||||
PubSub.publish(changesPubSub, {
|
||||
type: "clientUpserted",
|
||||
clientSession,
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const emitRemoved = (sessionId: AuthSessionId) =>
|
||||
PubSub.publish(changesPubSub, {
|
||||
type: "clientRemoved",
|
||||
sessionId,
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const loadActiveSession = (sessionId: AuthSessionId) =>
|
||||
Effect.gen(function* () {
|
||||
const row = yield* authSessions.getById({ sessionId });
|
||||
if (Option.isNone(row) || row.value.revokedAt !== null) {
|
||||
return Option.none<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.make(crypto.randomUUID());
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
|
||||
});
|
||||
const claims: SessionClaims = {
|
||||
v: 1,
|
||||
kind: "session",
|
||||
sid: sessionId,
|
||||
sub: input?.subject ?? "browser",
|
||||
role: input?.role ?? "client",
|
||||
method: input?.method ?? "browser-session-cookie",
|
||||
iat: issuedAt.epochMilliseconds,
|
||||
exp: expiresAt.epochMilliseconds,
|
||||
};
|
||||
const encodedPayload = base64UrlEncode(JSON.stringify(claims));
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
const client = input?.client ?? createDefaultClientMetadata();
|
||||
yield* authSessions.create({
|
||||
sessionId,
|
||||
subject: claims.sub,
|
||||
role: claims.role,
|
||||
method: claims.method,
|
||||
client: {
|
||||
label: client.label ?? null,
|
||||
ipAddress: client.ipAddress ?? null,
|
||||
userAgent: client.userAgent ?? null,
|
||||
deviceType: client.deviceType,
|
||||
os: client.os ?? null,
|
||||
browser: client.browser ?? null,
|
||||
},
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
});
|
||||
yield* emitUpsert(
|
||||
toAuthClientSession({
|
||||
sessionId,
|
||||
subject: claims.sub,
|
||||
role: claims.role,
|
||||
method: claims.method,
|
||||
client,
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
lastConnectedAt: null,
|
||||
connected: false,
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
sessionId,
|
||||
token: `${encodedPayload}.${signature}`,
|
||||
method: claims.method,
|
||||
client,
|
||||
expiresAt: expiresAt,
|
||||
role: claims.role,
|
||||
} satisfies IssuedSession;
|
||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to issue session credential.")));
|
||||
|
||||
const verify: SessionCredentialServiceShape["verify"] = (token) =>
|
||||
Effect.gen(function* () {
|
||||
const [encodedPayload, signature] = token.split(".");
|
||||
if (!encodedPayload || !signature) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Malformed session token.",
|
||||
});
|
||||
}
|
||||
|
||||
const expectedSignature = signPayload(encodedPayload, signingSecret);
|
||||
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Invalid session token signature.",
|
||||
});
|
||||
}
|
||||
|
||||
const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SessionCredentialError({
|
||||
message: "Invalid session token payload.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
if (claims.exp <= now) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Session token expired.",
|
||||
});
|
||||
}
|
||||
|
||||
const row = yield* authSessions.getById({ sessionId: claims.sid });
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Unknown session token.",
|
||||
});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Session token revoked.",
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
sessionId: claims.sid,
|
||||
token,
|
||||
method: claims.method,
|
||||
client: toClientMetadata(row.value.client),
|
||||
expiresAt: DateTime.makeUnsafe(claims.exp),
|
||||
subject: claims.sub,
|
||||
role: claims.role,
|
||||
} satisfies VerifiedSession;
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause instanceof SessionCredentialError
|
||||
? cause
|
||||
: new SessionCredentialError({
|
||||
message: "Failed to verify session credential.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const issueWebSocketToken: SessionCredentialServiceShape["issueWebSocketToken"] = (
|
||||
sessionId,
|
||||
input,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
|
||||
});
|
||||
const claims: WebSocketClaims = {
|
||||
v: 1,
|
||||
kind: "websocket",
|
||||
sid: sessionId,
|
||||
iat: issuedAt.epochMilliseconds,
|
||||
exp: expiresAt.epochMilliseconds,
|
||||
};
|
||||
const encodedPayload = base64UrlEncode(JSON.stringify(claims));
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
return {
|
||||
token: `${encodedPayload}.${signature}`,
|
||||
expiresAt,
|
||||
};
|
||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to issue websocket token.")));
|
||||
|
||||
const verifyWebSocketToken: SessionCredentialServiceShape["verifyWebSocketToken"] = (token) =>
|
||||
Effect.gen(function* () {
|
||||
const [encodedPayload, signature] = token.split(".");
|
||||
if (!encodedPayload || !signature) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Malformed websocket token.",
|
||||
});
|
||||
}
|
||||
|
||||
const expectedSignature = signPayload(encodedPayload, signingSecret);
|
||||
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Invalid websocket token signature.",
|
||||
});
|
||||
}
|
||||
|
||||
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SessionCredentialError({
|
||||
message: "Invalid websocket token payload.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
if (claims.exp <= now) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Websocket token expired.",
|
||||
});
|
||||
}
|
||||
|
||||
const row = yield* authSessions.getById({ sessionId: claims.sid });
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Unknown websocket session.",
|
||||
});
|
||||
}
|
||||
if (row.value.expiresAt.epochMilliseconds <= now) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Websocket session expired.",
|
||||
});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Websocket session revoked.",
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
sessionId: row.value.sessionId,
|
||||
token,
|
||||
method: row.value.method,
|
||||
client: toClientMetadata(row.value.client),
|
||||
expiresAt: row.value.expiresAt,
|
||||
subject: row.value.subject,
|
||||
role: row.value.role,
|
||||
} satisfies VerifiedSession;
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause instanceof SessionCredentialError
|
||||
? cause
|
||||
: new SessionCredentialError({
|
||||
message: "Failed to verify websocket token.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const listActive: SessionCredentialServiceShape["listActive"] = () =>
|
||||
Effect.gen(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
const connectedSessions = yield* Ref.get(connectedSessionsRef);
|
||||
const rows = yield* authSessions.listActive({ now });
|
||||
|
||||
return rows.map((row) =>
|
||||
toAuthClientSession({
|
||||
sessionId: row.sessionId,
|
||||
subject: row.subject,
|
||||
role: row.role,
|
||||
method: row.method,
|
||||
client: toClientMetadata(row.client),
|
||||
issuedAt: row.issuedAt,
|
||||
expiresAt: row.expiresAt,
|
||||
lastConnectedAt: row.lastConnectedAt,
|
||||
connected: connectedSessions.has(row.sessionId),
|
||||
}),
|
||||
);
|
||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to list active sessions.")));
|
||||
|
||||
const revoke: SessionCredentialServiceShape["revoke"] = (sessionId) =>
|
||||
Effect.gen(function* () {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revoked = yield* authSessions.revoke({
|
||||
sessionId,
|
||||
revokedAt,
|
||||
});
|
||||
if (revoked) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
next.delete(sessionId);
|
||||
return next;
|
||||
});
|
||||
yield* emitRemoved(sessionId);
|
||||
}
|
||||
return revoked;
|
||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke session.")));
|
||||
|
||||
const revokeAllExcept: SessionCredentialServiceShape["revokeAllExcept"] = (sessionId) =>
|
||||
Effect.gen(function* () {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revokedSessionIds = yield* authSessions.revokeAllExcept({
|
||||
currentSessionId: sessionId,
|
||||
revokedAt,
|
||||
});
|
||||
if (revokedSessionIds.length > 0) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
for (const revokedSessionId of revokedSessionIds) {
|
||||
next.delete(revokedSessionId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
revokedSessionIds,
|
||||
(revokedSessionId) => emitRemoved(revokedSessionId),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
return revokedSessionIds.length;
|
||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke other sessions.")));
|
||||
|
||||
return {
|
||||
cookieName,
|
||||
issue,
|
||||
verify,
|
||||
issueWebSocketToken,
|
||||
verifyWebSocketToken,
|
||||
listActive,
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
revoke,
|
||||
revokeAllExcept,
|
||||
markConnected,
|
||||
markDisconnected,
|
||||
} satisfies SessionCredentialServiceShape;
|
||||
});
|
||||
|
||||
export const SessionCredentialServiceLive = Layer.effect(
|
||||
SessionCredentialService,
|
||||
makeSessionCredentialService,
|
||||
).pipe(Layer.provideMerge(AuthSessionRepositoryLive));
|
||||
@@ -0,0 +1,69 @@
|
||||
import type {
|
||||
AuthClientMetadata,
|
||||
AuthClientSession,
|
||||
AuthPairingLink,
|
||||
AuthSessionId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, DateTime, Duration, Effect, Context } from "effect";
|
||||
import { SessionRole } from "./SessionCredentialService";
|
||||
|
||||
export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
|
||||
|
||||
export interface IssuedPairingLink {
|
||||
readonly id: string;
|
||||
readonly credential: string;
|
||||
readonly role: SessionRole;
|
||||
readonly subject: string;
|
||||
readonly label?: string;
|
||||
readonly createdAt: DateTime.Utc;
|
||||
readonly expiresAt: DateTime.Utc;
|
||||
}
|
||||
|
||||
export interface IssuedBearerSession {
|
||||
readonly sessionId: AuthSessionId;
|
||||
readonly token: string;
|
||||
readonly method: "bearer-session-token";
|
||||
readonly role: SessionRole;
|
||||
readonly subject: string;
|
||||
readonly client: AuthClientMetadata;
|
||||
readonly expiresAt: DateTime.Utc;
|
||||
}
|
||||
|
||||
export class AuthControlPlaneError extends Data.TaggedError("AuthControlPlaneError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export interface AuthControlPlaneShape {
|
||||
readonly createPairingLink: (input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
readonly label?: string;
|
||||
readonly role?: SessionRole;
|
||||
readonly subject?: string;
|
||||
}) => Effect.Effect<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 Context.Service<AuthControlPlane, AuthControlPlaneShape>()(
|
||||
"t3/AuthControlPlane",
|
||||
) {}
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { AuthPairingLink, ServerAuthBootstrapMethod } from "@t3tools/contracts";
|
||||
import { Data, DateTime, Duration, Context } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
|
||||
export type BootstrapCredentialRole = "owner" | "client";
|
||||
|
||||
export interface BootstrapGrant {
|
||||
readonly method: ServerAuthBootstrapMethod;
|
||||
readonly role: BootstrapCredentialRole;
|
||||
readonly subject: string;
|
||||
readonly label?: string;
|
||||
readonly expiresAt: DateTime.DateTime;
|
||||
}
|
||||
|
||||
export class BootstrapCredentialError extends Data.TaggedError("BootstrapCredentialError")<{
|
||||
readonly message: string;
|
||||
readonly status?: 401 | 500;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export interface IssuedBootstrapCredential {
|
||||
readonly id: string;
|
||||
readonly credential: string;
|
||||
readonly label?: string;
|
||||
readonly expiresAt: DateTime.Utc;
|
||||
}
|
||||
|
||||
export type BootstrapCredentialChange =
|
||||
| {
|
||||
readonly type: "pairingLinkUpserted";
|
||||
readonly pairingLink: AuthPairingLink;
|
||||
}
|
||||
| {
|
||||
readonly type: "pairingLinkRemoved";
|
||||
readonly id: string;
|
||||
};
|
||||
|
||||
export interface BootstrapCredentialServiceShape {
|
||||
readonly issueOneTimeToken: (input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
readonly role?: BootstrapCredentialRole;
|
||||
readonly subject?: string;
|
||||
readonly label?: string;
|
||||
}) => Effect.Effect<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 Context.Service<
|
||||
BootstrapCredentialService,
|
||||
BootstrapCredentialServiceShape
|
||||
>()("t3/auth/Services/BootstrapCredentialService") {}
|
||||
@@ -0,0 +1,84 @@
|
||||
import type {
|
||||
AuthBearerBootstrapResult,
|
||||
AuthBootstrapResult,
|
||||
AuthClientMetadata,
|
||||
AuthClientSession,
|
||||
AuthCreatePairingCredentialInput,
|
||||
AuthPairingLink,
|
||||
AuthPairingCredentialResult,
|
||||
AuthSessionId,
|
||||
AuthSessionState,
|
||||
ServerAuthDescriptor,
|
||||
ServerAuthSessionMethod,
|
||||
AuthWebSocketTokenResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, DateTime, Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import type { SessionRole } from "./SessionCredentialService.ts";
|
||||
|
||||
export interface AuthenticatedSession {
|
||||
readonly sessionId: AuthSessionId;
|
||||
readonly subject: string;
|
||||
readonly method: ServerAuthSessionMethod;
|
||||
readonly role: SessionRole;
|
||||
readonly expiresAt?: DateTime.DateTime;
|
||||
}
|
||||
|
||||
export class AuthError extends Data.TaggedError("AuthError")<{
|
||||
readonly message: string;
|
||||
readonly status?: 400 | 401 | 403 | 500;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export interface ServerAuthShape {
|
||||
readonly getDescriptor: () => Effect.Effect<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 Context.Service<ServerAuth, ServerAuthShape>()(
|
||||
"t3/auth/Services/ServerAuth",
|
||||
) {}
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { ServerAuthDescriptor } from "@t3tools/contracts";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export interface ServerAuthPolicyShape {
|
||||
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
|
||||
}
|
||||
|
||||
export class ServerAuthPolicy extends Context.Service<ServerAuthPolicy, ServerAuthPolicyShape>()(
|
||||
"t3/auth/Services/ServerAuthPolicy",
|
||||
) {}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Data, Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export interface ServerSecretStoreShape {
|
||||
readonly get: (name: string) => Effect.Effect<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 Context.Service<ServerSecretStore, ServerSecretStoreShape>()(
|
||||
"t3/auth/Services/ServerSecretStore",
|
||||
) {}
|
||||
@@ -0,0 +1,87 @@
|
||||
import type {
|
||||
AuthClientMetadata,
|
||||
AuthClientSession,
|
||||
AuthSessionId,
|
||||
ServerAuthSessionMethod,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, DateTime, Duration, Context } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
|
||||
export type SessionRole = "owner" | "client";
|
||||
|
||||
export interface IssuedSession {
|
||||
readonly sessionId: AuthSessionId;
|
||||
readonly token: string;
|
||||
readonly method: ServerAuthSessionMethod;
|
||||
readonly client: AuthClientMetadata;
|
||||
readonly expiresAt: DateTime.DateTime;
|
||||
readonly role: SessionRole;
|
||||
}
|
||||
|
||||
export interface VerifiedSession {
|
||||
readonly sessionId: AuthSessionId;
|
||||
readonly token: string;
|
||||
readonly method: ServerAuthSessionMethod;
|
||||
readonly client: AuthClientMetadata;
|
||||
readonly expiresAt?: DateTime.DateTime;
|
||||
readonly subject: string;
|
||||
readonly role: SessionRole;
|
||||
}
|
||||
|
||||
export type SessionCredentialChange =
|
||||
| {
|
||||
readonly type: "clientUpserted";
|
||||
readonly clientSession: AuthClientSession;
|
||||
}
|
||||
| {
|
||||
readonly type: "clientRemoved";
|
||||
readonly sessionId: AuthSessionId;
|
||||
};
|
||||
|
||||
export class SessionCredentialError extends Data.TaggedError("SessionCredentialError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export interface SessionCredentialServiceShape {
|
||||
readonly cookieName: string;
|
||||
readonly issue: (input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
readonly subject?: string;
|
||||
readonly method?: ServerAuthSessionMethod;
|
||||
readonly role?: SessionRole;
|
||||
readonly client?: AuthClientMetadata;
|
||||
}) => Effect.Effect<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 Context.Service<
|
||||
SessionCredentialService,
|
||||
SessionCredentialServiceShape
|
||||
>()("t3/auth/Services/SessionCredentialService") {}
|
||||
@@ -0,0 +1,254 @@
|
||||
import {
|
||||
type AuthBearerBootstrapResult,
|
||||
AuthBootstrapInput,
|
||||
AuthCreatePairingCredentialInput,
|
||||
AuthRevokeClientSessionInput,
|
||||
AuthRevokePairingLinkInput,
|
||||
type AuthWebSocketTokenResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { DateTime, Effect, Schema } from "effect";
|
||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
|
||||
import { AuthError, ServerAuth } from "./Services/ServerAuth.ts";
|
||||
import { SessionCredentialService } from "./Services/SessionCredentialService.ts";
|
||||
import { deriveAuthClientMetadata } from "./utils.ts";
|
||||
|
||||
export const respondToAuthError = (error: AuthError) =>
|
||||
Effect.gen(function* () {
|
||||
if ((error.status ?? 500) >= 500) {
|
||||
yield* Effect.logError("auth route failed", {
|
||||
message: error.message,
|
||||
cause: error.cause,
|
||||
});
|
||||
}
|
||||
return HttpServerResponse.jsonUnsafe(
|
||||
{
|
||||
error: error.message,
|
||||
},
|
||||
{ status: error.status ?? 500 },
|
||||
);
|
||||
});
|
||||
|
||||
export const authSessionRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
"/api/auth/session",
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const session = yield* serverAuth.getSessionState(request);
|
||||
return HttpServerResponse.jsonUnsafe(session, { status: 200 });
|
||||
}),
|
||||
);
|
||||
|
||||
const PairingCredentialRequestHeaders = Schema.Struct({
|
||||
"content-length": Schema.optionalKey(Schema.String),
|
||||
"content-type": Schema.optionalKey(Schema.String),
|
||||
"transfer-encoding": Schema.optionalKey(Schema.String),
|
||||
});
|
||||
|
||||
function hasRequestBody(headers: typeof PairingCredentialRequestHeaders.Type) {
|
||||
const contentLengthHeader = headers["content-length"];
|
||||
if (typeof contentLengthHeader === "string") {
|
||||
const contentLength = Number.parseInt(contentLengthHeader, 10);
|
||||
if (Number.isFinite(contentLength)) {
|
||||
return contentLength > 0;
|
||||
}
|
||||
}
|
||||
return typeof headers["transfer-encoding"] === "string";
|
||||
}
|
||||
|
||||
export const authBootstrapRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/api/auth/bootstrap",
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const payload = yield* HttpServerRequest.schemaBodyJson(AuthBootstrapInput).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Invalid bootstrap payload.",
|
||||
status: 400,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const result = yield* serverAuth.exchangeBootstrapCredential(
|
||||
payload.credential,
|
||||
deriveAuthClientMetadata({ request }),
|
||||
);
|
||||
|
||||
return yield* HttpServerResponse.jsonUnsafe(result.response, { status: 200 }).pipe(
|
||||
HttpServerResponse.setCookie(sessions.cookieName, result.sessionToken, {
|
||||
expires: DateTime.toDate(result.response.expiresAt),
|
||||
httpOnly: true,
|
||||
path: "/",
|
||||
sameSite: "lax",
|
||||
}),
|
||||
);
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
export const authBearerBootstrapRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/api/auth/bootstrap/bearer",
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const payload = yield* HttpServerRequest.schemaBodyJson(AuthBootstrapInput).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Invalid bootstrap payload.",
|
||||
status: 400,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const result = yield* serverAuth.exchangeBootstrapCredentialForBearerSession(
|
||||
payload.credential,
|
||||
deriveAuthClientMetadata({ request }),
|
||||
);
|
||||
return HttpServerResponse.jsonUnsafe(result satisfies AuthBearerBootstrapResult, {
|
||||
status: 200,
|
||||
});
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
export const authWebSocketTokenRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/api/auth/ws-token",
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const session = yield* serverAuth.authenticateHttpRequest(request);
|
||||
const result = yield* serverAuth.issueWebSocketToken(session);
|
||||
return HttpServerResponse.jsonUnsafe(result satisfies AuthWebSocketTokenResult, {
|
||||
status: 200,
|
||||
});
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
export const authPairingCredentialRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/api/auth/pairing-token",
|
||||
Effect.gen(function* () {
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const session = yield* serverAuth.authenticateHttpRequest(request);
|
||||
if (session.role !== "owner") {
|
||||
return yield* new AuthError({
|
||||
message: "Only owner sessions can create pairing credentials.",
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
const headers = yield* HttpServerRequest.schemaHeaders(PairingCredentialRequestHeaders).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Invalid pairing credential request headers.",
|
||||
status: 400,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const payload = hasRequestBody(headers)
|
||||
? yield* HttpServerRequest.schemaBodyJson(AuthCreatePairingCredentialInput).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Invalid pairing credential payload.",
|
||||
status: 400,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
)
|
||||
: {};
|
||||
const result = yield* serverAuth.issuePairingCredential(payload);
|
||||
return HttpServerResponse.jsonUnsafe(result, { status: 200 });
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
const authenticateOwnerSession = Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const session = yield* serverAuth.authenticateHttpRequest(request);
|
||||
if (session.role !== "owner") {
|
||||
return yield* new AuthError({
|
||||
message: "Only owner sessions can manage network access.",
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
return { serverAuth, session } as const;
|
||||
});
|
||||
|
||||
export const authPairingLinksRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
"/api/auth/pairing-links",
|
||||
Effect.gen(function* () {
|
||||
const { serverAuth } = yield* authenticateOwnerSession;
|
||||
const pairingLinks = yield* serverAuth.listPairingLinks();
|
||||
return HttpServerResponse.jsonUnsafe(pairingLinks, { status: 200 });
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
export const authPairingLinksRevokeRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/api/auth/pairing-links/revoke",
|
||||
Effect.gen(function* () {
|
||||
const { serverAuth } = yield* authenticateOwnerSession;
|
||||
const payload = yield* HttpServerRequest.schemaBodyJson(AuthRevokePairingLinkInput).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Invalid revoke pairing link payload.",
|
||||
status: 400,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const revoked = yield* serverAuth.revokePairingLink(payload.id);
|
||||
return HttpServerResponse.jsonUnsafe({ revoked }, { status: 200 });
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
export const authClientsRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
"/api/auth/clients",
|
||||
Effect.gen(function* () {
|
||||
const { serverAuth, session } = yield* authenticateOwnerSession;
|
||||
const clients = yield* serverAuth.listClientSessions(session.sessionId);
|
||||
return HttpServerResponse.jsonUnsafe(clients, { status: 200 });
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
export const authClientsRevokeRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/api/auth/clients/revoke",
|
||||
Effect.gen(function* () {
|
||||
const { serverAuth, session } = yield* authenticateOwnerSession;
|
||||
const payload = yield* HttpServerRequest.schemaBodyJson(AuthRevokeClientSessionInput).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Invalid revoke client payload.",
|
||||
status: 400,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const revoked = yield* serverAuth.revokeClientSession(session.sessionId, payload.sessionId);
|
||||
return HttpServerResponse.jsonUnsafe({ revoked }, { status: 200 });
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
export const authClientsRevokeOthersRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/api/auth/clients/revoke-others",
|
||||
Effect.gen(function* () {
|
||||
const { serverAuth, session } = yield* authenticateOwnerSession;
|
||||
const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);
|
||||
return HttpServerResponse.jsonUnsafe({ revokedCount }, { status: 200 });
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { deriveAuthClientMetadata } from "./utils";
|
||||
|
||||
describe("deriveAuthClientMetadata", () => {
|
||||
it("labels Electron user agents as Electron instead of Chrome", () => {
|
||||
const metadata = deriveAuthClientMetadata({
|
||||
request: {
|
||||
headers: {
|
||||
"user-agent":
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) t3code/0.0.15 Chrome/136.0.7103.93 Electron/36.3.2 Safari/537.36",
|
||||
},
|
||||
source: {
|
||||
remoteAddress: "::ffff:127.0.0.1",
|
||||
},
|
||||
} as never,
|
||||
});
|
||||
|
||||
expect(metadata).toMatchObject({
|
||||
browser: "Electron",
|
||||
deviceType: "desktop",
|
||||
ipAddress: "127.0.0.1",
|
||||
os: "macOS",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
import type { AuthClientMetadata, AuthClientMetadataDeviceType } from "@t3tools/contracts";
|
||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as Crypto from "node:crypto";
|
||||
|
||||
const SESSION_COOKIE_NAME = "t3_session";
|
||||
|
||||
export function resolveSessionCookieName(input: {
|
||||
readonly mode: "web" | "desktop";
|
||||
readonly port: number;
|
||||
}): string {
|
||||
if (input.mode !== "desktop") {
|
||||
return SESSION_COOKIE_NAME;
|
||||
}
|
||||
|
||||
return `${SESSION_COOKIE_NAME}_${input.port}`;
|
||||
}
|
||||
|
||||
export function base64UrlEncode(input: string | Uint8Array): string {
|
||||
const buffer = typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.from(input);
|
||||
return buffer.toString("base64url");
|
||||
}
|
||||
|
||||
export function base64UrlDecodeUtf8(input: string): string {
|
||||
return Buffer.from(input, "base64url").toString("utf8");
|
||||
}
|
||||
|
||||
export function signPayload(payload: string, secret: Uint8Array): string {
|
||||
return Crypto.createHmac("sha256", Buffer.from(secret)).update(payload).digest("base64url");
|
||||
}
|
||||
|
||||
export function timingSafeEqualBase64Url(left: string, right: string): boolean {
|
||||
const leftBuffer = Buffer.from(left, "base64url");
|
||||
const rightBuffer = Buffer.from(right, "base64url");
|
||||
if (leftBuffer.length !== rightBuffer.length) {
|
||||
return false;
|
||||
}
|
||||
return Crypto.timingSafeEqual(leftBuffer, rightBuffer);
|
||||
}
|
||||
|
||||
function normalizeNonEmptyString(value: string | null | undefined): string | undefined {
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function normalizeIpAddress(value: string | null | undefined): string | undefined {
|
||||
const normalized = normalizeNonEmptyString(value);
|
||||
if (!normalized) {
|
||||
return undefined;
|
||||
}
|
||||
return normalized.startsWith("::ffff:") ? normalized.slice("::ffff:".length) : normalized;
|
||||
}
|
||||
|
||||
function inferDeviceType(userAgent: string | undefined): AuthClientMetadataDeviceType {
|
||||
if (!userAgent) {
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
const normalized = userAgent.toLowerCase();
|
||||
if (/bot|crawler|spider|slurp|curl|wget/.test(normalized)) {
|
||||
return "bot";
|
||||
}
|
||||
if (/ipad|tablet/.test(normalized)) {
|
||||
return "tablet";
|
||||
}
|
||||
if (/iphone|android.+mobile|mobile/.test(normalized)) {
|
||||
return "mobile";
|
||||
}
|
||||
return "desktop";
|
||||
}
|
||||
|
||||
function inferBrowser(userAgent: string | undefined): string | undefined {
|
||||
if (!userAgent) {
|
||||
return undefined;
|
||||
}
|
||||
const normalized = userAgent.toLowerCase();
|
||||
if (/edg\//.test(normalized)) return "Edge";
|
||||
if (/opr\//.test(normalized)) return "Opera";
|
||||
if (/firefox\//.test(normalized)) return "Firefox";
|
||||
if (/electron\//.test(normalized)) return "Electron";
|
||||
if (/chrome\//.test(normalized) || /crios\//.test(normalized)) return "Chrome";
|
||||
if (/safari\//.test(normalized) && !/chrome\//.test(normalized)) return "Safari";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function inferOs(userAgent: string | undefined): string | undefined {
|
||||
if (!userAgent) {
|
||||
return undefined;
|
||||
}
|
||||
const normalized = userAgent.toLowerCase();
|
||||
if (/iphone|ipad|ipod/.test(normalized)) return "iOS";
|
||||
if (/android/.test(normalized)) return "Android";
|
||||
if (/mac os x|macintosh/.test(normalized)) return "macOS";
|
||||
if (/windows nt/.test(normalized)) return "Windows";
|
||||
if (/linux/.test(normalized)) return "Linux";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function readRemoteAddressFromSource(source: unknown): string | undefined {
|
||||
if (!source || typeof source !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const candidate = source as {
|
||||
readonly remoteAddress?: string | null;
|
||||
readonly socket?: {
|
||||
readonly remoteAddress?: string | null;
|
||||
};
|
||||
};
|
||||
|
||||
return normalizeIpAddress(candidate.socket?.remoteAddress ?? candidate.remoteAddress);
|
||||
}
|
||||
|
||||
export function deriveAuthClientMetadata(input: {
|
||||
readonly request: HttpServerRequest.HttpServerRequest;
|
||||
readonly label?: string;
|
||||
}): AuthClientMetadata {
|
||||
const userAgent = normalizeNonEmptyString(input.request.headers["user-agent"]);
|
||||
const ipAddress = readRemoteAddressFromSource(input.request.source);
|
||||
const os = inferOs(userAgent);
|
||||
const browser = inferBrowser(userAgent);
|
||||
return {
|
||||
...(input.label ? { label: input.label } : {}),
|
||||
...(ipAddress ? { ipAddress } : {}),
|
||||
...(userAgent ? { userAgent } : {}),
|
||||
deviceType: inferDeviceType(userAgent),
|
||||
...(os ? { os } : {}),
|
||||
...(browser ? { browser } : {}),
|
||||
};
|
||||
}
|
||||
@@ -1,83 +1,38 @@
|
||||
import {
|
||||
CheckpointRef,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { CheckpointRef, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
ProjectionSnapshotQuery,
|
||||
type ProjectionThreadCheckpointContext,
|
||||
} from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||
import { CheckpointDiffQueryLive } from "./CheckpointDiffQuery.ts";
|
||||
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
||||
import { CheckpointDiffQuery } from "../Services/CheckpointDiffQuery.ts";
|
||||
|
||||
function makeSnapshot(input: {
|
||||
function makeThreadCheckpointContext(input: {
|
||||
readonly projectId: ProjectId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly workspaceRoot: string;
|
||||
readonly worktreePath: string | null;
|
||||
readonly checkpointTurnCount: number;
|
||||
readonly checkpointRef: CheckpointRef;
|
||||
}): OrchestrationReadModel {
|
||||
}): ProjectionThreadCheckpointContext {
|
||||
return {
|
||||
snapshotSequence: 0,
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
projects: [
|
||||
threadId: input.threadId,
|
||||
projectId: input.projectId,
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
worktreePath: input.worktreePath,
|
||||
checkpoints: [
|
||||
{
|
||||
id: input.projectId,
|
||||
title: "Project",
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: input.threadId,
|
||||
projectId: input.projectId,
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: input.worktreePath,
|
||||
latestTurn: {
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-01-01T00:00:00.000Z",
|
||||
startedAt: "2026-01-01T00:00:00.000Z",
|
||||
completedAt: "2026-01-01T00:00:00.000Z",
|
||||
assistantMessageId: null,
|
||||
},
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
checkpoints: [
|
||||
{
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
checkpointTurnCount: input.checkpointTurnCount,
|
||||
checkpointRef: input.checkpointRef,
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: null,
|
||||
completedAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
session: null,
|
||||
turnId: TurnId.make("turn-1"),
|
||||
checkpointTurnCount: input.checkpointTurnCount,
|
||||
checkpointRef: input.checkpointRef,
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: null,
|
||||
completedAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -85,8 +40,8 @@ function makeSnapshot(input: {
|
||||
|
||||
describe("CheckpointDiffQueryLive", () => {
|
||||
it("computes diffs using canonical turn-0 checkpoint refs", async () => {
|
||||
const projectId = ProjectId.makeUnsafe("project-1");
|
||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
||||
const projectId = ProjectId.make("project-1");
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
const hasCheckpointRefCalls: Array<CheckpointRef> = [];
|
||||
const diffCheckpointsCalls: Array<{
|
||||
@@ -95,7 +50,7 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
readonly cwd: string;
|
||||
}> = [];
|
||||
|
||||
const snapshot = makeSnapshot({
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
projectId,
|
||||
threadId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
@@ -125,7 +80,17 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () => Effect.succeed(snapshot),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -159,7 +124,7 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
});
|
||||
|
||||
it("fails when the thread is missing from the snapshot", async () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-missing");
|
||||
const threadId = ThreadId.make("thread-missing");
|
||||
|
||||
const checkpointStore: CheckpointStoreShape = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
@@ -175,12 +140,16 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () =>
|
||||
Effect.succeed({
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [],
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
} satisfies OrchestrationReadModel),
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -4,11 +4,11 @@ import {
|
||||
type OrchestrationGetFullThreadDiffResult,
|
||||
type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
import { Effect, Layer, Option, Schema } from "effect";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { CheckpointInvariantError, CheckpointUnavailableError } from "../Errors.ts";
|
||||
import { checkpointRefForThreadTurn, resolveThreadWorkspaceCwd } from "../Utils.ts";
|
||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||
import { CheckpointStore } from "../Services/CheckpointStore.ts";
|
||||
import {
|
||||
CheckpointDiffQuery,
|
||||
@@ -41,16 +41,17 @@ const make = Effect.gen(function* () {
|
||||
return emptyDiff;
|
||||
}
|
||||
|
||||
const snapshot = yield* projectionSnapshotQuery.getSnapshot();
|
||||
const thread = snapshot.threads.find((entry) => entry.id === input.threadId);
|
||||
if (!thread) {
|
||||
const threadContext = yield* projectionSnapshotQuery.getThreadCheckpointContext(
|
||||
input.threadId,
|
||||
);
|
||||
if (Option.isNone(threadContext)) {
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
detail: `Thread '${input.threadId}' not found.`,
|
||||
});
|
||||
}
|
||||
|
||||
const maxTurnCount = thread.checkpoints.reduce(
|
||||
const maxTurnCount = threadContext.value.checkpoints.reduce(
|
||||
(max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),
|
||||
0,
|
||||
);
|
||||
@@ -62,10 +63,7 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const workspaceCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: snapshot.projects,
|
||||
});
|
||||
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
|
||||
if (!workspaceCwd) {
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
@@ -76,7 +74,7 @@ const make = Effect.gen(function* () {
|
||||
const fromCheckpointRef =
|
||||
input.fromTurnCount === 0
|
||||
? checkpointRefForThreadTurn(input.threadId, 0)
|
||||
: thread.checkpoints.find(
|
||||
: threadContext.value.checkpoints.find(
|
||||
(checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,
|
||||
)?.checkpointRef;
|
||||
if (!fromCheckpointRef) {
|
||||
@@ -87,7 +85,7 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const toCheckpointRef = thread.checkpoints.find(
|
||||
const toCheckpointRef = threadContext.value.checkpoints.find(
|
||||
(checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,
|
||||
)?.checkpointRef;
|
||||
if (!toCheckpointRef) {
|
||||
|
||||
@@ -80,7 +80,7 @@ function initRepoWithCommit(
|
||||
});
|
||||
}
|
||||
|
||||
function buildLargeText(lineCount = 20_000): string {
|
||||
function buildLargeText(lineCount = 5_000): string {
|
||||
return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`)
|
||||
.join("\n")
|
||||
.concat("\n");
|
||||
@@ -93,7 +93,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
const threadId = ThreadId.makeUnsafe("thread-checkpoint-store");
|
||||
const threadId = ThreadId.make("thread-checkpoint-store");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
@@ -115,7 +115,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
|
||||
|
||||
expect(diff).toContain("diff --git");
|
||||
expect(diff).not.toContain("[truncated]");
|
||||
expect(diff).toContain("+line 19999");
|
||||
expect(diff).toContain("+line 04999");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -12,7 +12,7 @@ import type {
|
||||
OrchestrationGetTurnDiffInput,
|
||||
OrchestrationGetTurnDiffResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { CheckpointServiceError } from "../Errors.ts";
|
||||
@@ -43,7 +43,7 @@ export interface CheckpointDiffQueryShape {
|
||||
/**
|
||||
* CheckpointDiffQuery - Service tag for checkpoint diff queries.
|
||||
*/
|
||||
export class CheckpointDiffQuery extends ServiceMap.Service<
|
||||
export class CheckpointDiffQuery extends Context.Service<
|
||||
CheckpointDiffQuery,
|
||||
CheckpointDiffQueryShape
|
||||
>()("t3/checkpointing/Services/CheckpointDiffQuery") {}
|
||||
@@ -5,12 +5,12 @@
|
||||
* workspace thread timeline. It does not store user-facing checkpoint metadata
|
||||
* and does not coordinate provider conversation rollback.
|
||||
*
|
||||
* Uses Effect `ServiceMap.Service` for dependency injection and exposes typed
|
||||
* Uses Effect `Context.Service` for dependency injection and exposes typed
|
||||
* domain errors for checkpoint storage operations.
|
||||
*
|
||||
* @module CheckpointStore
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { CheckpointStoreError } from "../Errors.ts";
|
||||
@@ -95,6 +95,6 @@ export interface CheckpointStoreShape {
|
||||
/**
|
||||
* CheckpointStore - Service tag for checkpoint persistence and restore operations.
|
||||
*/
|
||||
export class CheckpointStore extends ServiceMap.Service<CheckpointStore, CheckpointStoreShape>()(
|
||||
export class CheckpointStore extends Context.Service<CheckpointStore, CheckpointStoreShape>()(
|
||||
"t3/checkpointing/Services/CheckpointStore",
|
||||
) {}
|
||||
@@ -4,7 +4,7 @@ import { CheckpointRef, ProjectId, type ThreadId } from "@t3tools/contracts";
|
||||
export const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
|
||||
|
||||
export function checkpointRefForThreadTurn(threadId: ThreadId, turnCount: number): CheckpointRef {
|
||||
return CheckpointRef.makeUnsafe(
|
||||
return CheckpointRef.make(
|
||||
`${CHECKPOINT_REFS_PREFIX}/${Encoding.encodeBase64Url(threadId)}/turn/${turnCount}`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -9,6 +9,18 @@ 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" });
|
||||
@@ -28,9 +40,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(),
|
||||
@@ -49,7 +61,6 @@ 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",
|
||||
},
|
||||
@@ -62,6 +73,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Warn",
|
||||
...defaultObservabilityConfig,
|
||||
mode: "desktop",
|
||||
port: 4001,
|
||||
cwd: process.cwd(),
|
||||
@@ -71,7 +83,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
staticDir: undefined,
|
||||
devUrl: new URL("http://127.0.0.1:5173"),
|
||||
noBrowser: true,
|
||||
authToken: "env-token",
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
@@ -89,9 +102,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),
|
||||
@@ -110,7 +123,6 @@ 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",
|
||||
},
|
||||
@@ -123,6 +135,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Debug",
|
||||
...defaultObservabilityConfig,
|
||||
mode: "web",
|
||||
port: 8788,
|
||||
cwd: process.cwd(),
|
||||
@@ -132,13 +145,77 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
staticDir: undefined,
|
||||
devUrl: new URL("http://127.0.0.1:4173"),
|
||||
noBrowser: true,
|
||||
authToken: "flag-token",
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves explicit false CLI boolean flags over env and bootstrap values", () =>
|
||||
Effect.gen(function* () {
|
||||
const { join } = yield* Path.Path;
|
||||
const baseDir = join(os.tmpdir(), "t3-cli-config-false-flags");
|
||||
const fd = yield* openBootstrapFd({
|
||||
noBrowser: true,
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
||||
|
||||
const resolved = yield* resolveServerConfig(
|
||||
{
|
||||
mode: Option.some("web"),
|
||||
port: Option.some(8788),
|
||||
host: Option.some("127.0.0.1"),
|
||||
baseDir: Option.some(baseDir),
|
||||
cwd: Option.none(),
|
||||
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
|
||||
noBrowser: Option.some(false),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.some(false),
|
||||
logWebSocketEvents: Option.some(false),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
ConfigProvider.layer(
|
||||
ConfigProvider.fromEnv({
|
||||
env: {
|
||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
|
||||
T3CODE_LOG_WS_EVENTS: "true",
|
||||
},
|
||||
}),
|
||||
),
|
||||
NetService.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Info",
|
||||
...defaultObservabilityConfig,
|
||||
mode: "web",
|
||||
port: 8788,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
host: "127.0.0.1",
|
||||
staticDir: undefined,
|
||||
devUrl: new URL("http://127.0.0.1:4173"),
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses bootstrap envelope values as fallbacks when flags and env are absent", () =>
|
||||
Effect.gen(function* () {
|
||||
const { join } = yield* Path.Path;
|
||||
@@ -150,9 +227,10 @@ 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"));
|
||||
|
||||
@@ -162,9 +240,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(),
|
||||
@@ -187,6 +265,9 @@ 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(),
|
||||
@@ -196,7 +277,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
staticDir: undefined,
|
||||
devUrl: new URL("http://127.0.0.1:5173"),
|
||||
noBrowser: true,
|
||||
authToken: "bootstrap-token",
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
@@ -209,6 +291,7 @@ 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(
|
||||
{
|
||||
@@ -216,9 +299,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(),
|
||||
@@ -234,6 +317,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
);
|
||||
|
||||
for (const directory of [
|
||||
customCwd,
|
||||
resolved.stateDir,
|
||||
resolved.logsDir,
|
||||
resolved.providerLogsDir,
|
||||
@@ -241,9 +325,11 @@ 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));
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -258,7 +344,6 @@ 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,
|
||||
});
|
||||
@@ -270,9 +355,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(),
|
||||
@@ -300,6 +385,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Debug",
|
||||
...defaultObservabilityConfig,
|
||||
mode: "web",
|
||||
port: 8788,
|
||||
cwd: process.cwd(),
|
||||
@@ -309,10 +395,134 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
staticDir: undefined,
|
||||
devUrl: new URL("http://127.0.0.1:4173"),
|
||||
noBrowser: true,
|
||||
authToken: "flag-token",
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to persisted observability settings when env vars are absent", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-settings-" });
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
|
||||
yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
|
||||
yield* fs.writeFileString(
|
||||
derivedPaths.settingsPath,
|
||||
`${JSON.stringify({
|
||||
observability: {
|
||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
||||
},
|
||||
})}\n`,
|
||||
);
|
||||
|
||||
const resolved = yield* resolveServerConfig(
|
||||
{
|
||||
mode: Option.some("desktop"),
|
||||
port: Option.some(4888),
|
||||
host: Option.none(),
|
||||
baseDir: Option.some(baseDir),
|
||||
cwd: Option.none(),
|
||||
devUrl: Option.none(),
|
||||
noBrowser: Option.none(),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
|
||||
NetService.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(resolved.otlpTracesUrl).toBe("http://localhost:4318/v1/traces");
|
||||
expect(resolved.otlpMetricsUrl).toBe("http://localhost:4318/v1/metrics");
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Info",
|
||||
...defaultObservabilityConfig,
|
||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
||||
mode: "desktop",
|
||||
port: 4888,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
host: "127.0.0.1",
|
||||
staticDir: resolved.staticDir,
|
||||
devUrl: undefined,
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("forces noBrowser and disables auto-bootstrap for headless startup presentation", () =>
|
||||
Effect.gen(function* () {
|
||||
const { join } = yield* Path.Path;
|
||||
const baseDir = join(os.tmpdir(), "t3-cli-config-headless-base");
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
|
||||
|
||||
const resolved = yield* resolveServerConfig(
|
||||
{
|
||||
mode: Option.some("web"),
|
||||
port: Option.some(3773),
|
||||
host: Option.none(),
|
||||
baseDir: Option.some(baseDir),
|
||||
cwd: Option.none(),
|
||||
devUrl: Option.none(),
|
||||
noBrowser: Option.none(),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
{
|
||||
startupPresentation: "headless",
|
||||
},
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
ConfigProvider.layer(
|
||||
ConfigProvider.fromEnv({
|
||||
env: {
|
||||
T3CODE_NO_BROWSER: "false",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
|
||||
},
|
||||
}),
|
||||
),
|
||||
NetService.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Info",
|
||||
...defaultObservabilityConfig,
|
||||
mode: "web",
|
||||
port: 3773,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
host: undefined,
|
||||
staticDir: resolved.staticDir,
|
||||
devUrl: undefined,
|
||||
noBrowser: true,
|
||||
startupPresentation: "headless",
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
+326
-7
@@ -1,28 +1,164 @@
|
||||
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", () =>
|
||||
Command.runWith(cli, { version: "0.0.0" })(["--log-level", "debug", "--version"]).pipe(
|
||||
Effect.provide(CliRuntimeLayer),
|
||||
),
|
||||
runCliWithRuntime(["--log-level", "debug", "--version"]),
|
||||
);
|
||||
|
||||
it.effect("accepts canonical --no-<flag> boolean negation", () =>
|
||||
runCliWithRuntime(["--no-log-websocket-events", "--version"]),
|
||||
);
|
||||
|
||||
it.effect("rejects invalid log-level casing before launching the server", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Command.runWith(cli, { version: "0.0.0" })([
|
||||
"--log-level",
|
||||
"Debug",
|
||||
]).pipe(Effect.provide(CliRuntimeLayer), Effect.flip);
|
||||
const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(Effect.flip);
|
||||
|
||||
if (!CliError.isCliError(error)) {
|
||||
assert.fail(`Expected CliError, got ${String(error)}`);
|
||||
@@ -34,4 +170,187 @@ 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");
|
||||
}),
|
||||
);
|
||||
});
|
||||
+917
-77
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,88 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { DateTime } from "effect";
|
||||
|
||||
import {
|
||||
formatIssuedPairingCredential,
|
||||
formatIssuedSession,
|
||||
formatPairingCredentialList,
|
||||
formatSessionList,
|
||||
} from "./cliAuthFormat.ts";
|
||||
|
||||
it("formats issued pairing credentials with the secret and optional pair URL", () => {
|
||||
const output = formatIssuedPairingCredential(
|
||||
{
|
||||
id: "pairing-1",
|
||||
credential: "secret-pairing-token",
|
||||
role: "client",
|
||||
subject: "one-time-token",
|
||||
createdAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
|
||||
expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
|
||||
},
|
||||
{ baseUrl: "https://example.com", json: false },
|
||||
);
|
||||
|
||||
expect(output).toContain("secret-pairing-token");
|
||||
expect(output).toContain("https://example.com/pair#token=secret-pairing-token");
|
||||
});
|
||||
|
||||
it("formats pairing listings without exposing the secret token", () => {
|
||||
const output = formatPairingCredentialList(
|
||||
[
|
||||
{
|
||||
id: "pairing-1",
|
||||
credential: "secret-pairing-token",
|
||||
subject: "one-time-token",
|
||||
label: "Phone",
|
||||
role: "client",
|
||||
createdAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
|
||||
expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
|
||||
},
|
||||
],
|
||||
{ json: false },
|
||||
);
|
||||
|
||||
expect(output).toContain("pairing-1");
|
||||
expect(output).not.toContain("secret-pairing-token");
|
||||
});
|
||||
|
||||
it("formats issued sessions with the bearer token but omits tokens from listings", () => {
|
||||
const issuedOutput = formatIssuedSession(
|
||||
{
|
||||
sessionId: "session-1" as never,
|
||||
token: "secret-session-token",
|
||||
method: "bearer-session-token",
|
||||
role: "owner",
|
||||
subject: "cli-issued-session",
|
||||
client: {
|
||||
label: "deploy-bot",
|
||||
deviceType: "bot",
|
||||
},
|
||||
expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
|
||||
},
|
||||
{ json: false },
|
||||
);
|
||||
|
||||
const listedOutput = formatSessionList(
|
||||
[
|
||||
{
|
||||
sessionId: "session-1" as never,
|
||||
method: "bearer-session-token",
|
||||
role: "owner",
|
||||
subject: "cli-issued-session",
|
||||
client: {
|
||||
label: "deploy-bot",
|
||||
deviceType: "bot",
|
||||
},
|
||||
connected: false,
|
||||
current: false,
|
||||
issuedAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
|
||||
expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
|
||||
lastConnectedAt: null,
|
||||
},
|
||||
],
|
||||
{ json: false },
|
||||
);
|
||||
|
||||
expect(issuedOutput).toContain("secret-session-token");
|
||||
expect(listedOutput).not.toContain("secret-session-token");
|
||||
});
|
||||
@@ -0,0 +1,190 @@
|
||||
import type { AuthClientMetadata, AuthClientSession, AuthPairingLink } from "@t3tools/contracts";
|
||||
import { DateTime } from "effect";
|
||||
|
||||
import type { IssuedBearerSession, IssuedPairingLink } from "./auth/Services/AuthControlPlane.ts";
|
||||
|
||||
const newline = "\n";
|
||||
|
||||
function serializeOptionalFields(values: ReadonlyArray<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
|
||||
);
|
||||
}
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
resolveCodexModelForAccount,
|
||||
} from "./codexAppServerManager";
|
||||
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
|
||||
|
||||
function createSendTurnHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
@@ -111,9 +111,9 @@ function createPendingUserInputHarness() {
|
||||
},
|
||||
pendingUserInputs: new Map([
|
||||
[
|
||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
ApprovalRequestId.make("req-user-input-1"),
|
||||
{
|
||||
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
requestId: ApprovalRequestId.make("req-user-input-1"),
|
||||
jsonRpcId: 42,
|
||||
threadId: asThreadId("thread_1"),
|
||||
},
|
||||
@@ -743,7 +743,7 @@ describe("respondToUserInput", () => {
|
||||
|
||||
await manager.respondToUserInput(
|
||||
asThreadId("thread_1"),
|
||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
ApprovalRequestId.make("req-user-input-1"),
|
||||
{
|
||||
scope: "All request methods",
|
||||
compat: "Keep current envelope",
|
||||
@@ -780,7 +780,7 @@ describe("respondToUserInput", () => {
|
||||
|
||||
await manager.respondToUserInput(
|
||||
asThreadId("thread_1"),
|
||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
ApprovalRequestId.make("req-user-input-1"),
|
||||
{
|
||||
scope: [],
|
||||
},
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
ProviderInteractionMode,
|
||||
} from "@t3tools/contracts";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { Effect, ServiceMap } from "effect";
|
||||
import { Effect, Context } from "effect";
|
||||
|
||||
import {
|
||||
formatCodexCliUpgradeMessage,
|
||||
@@ -290,20 +290,26 @@ In Default mode, strongly prefer making reasonable assumptions and executing the
|
||||
</collaboration_mode>`;
|
||||
|
||||
function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
|
||||
readonly approvalPolicy: "on-request" | "never";
|
||||
readonly sandbox: "workspace-write" | "danger-full-access";
|
||||
readonly approvalPolicy: "untrusted" | "on-request" | "never";
|
||||
readonly sandbox: "read-only" | "workspace-write" | "danger-full-access";
|
||||
} {
|
||||
if (runtimeMode === "approval-required") {
|
||||
return {
|
||||
approvalPolicy: "on-request",
|
||||
sandbox: "workspace-write",
|
||||
};
|
||||
switch (runtimeMode) {
|
||||
case "approval-required":
|
||||
return {
|
||||
approvalPolicy: "untrusted",
|
||||
sandbox: "read-only",
|
||||
};
|
||||
case "auto-accept-edits":
|
||||
return {
|
||||
approvalPolicy: "on-request",
|
||||
sandbox: "workspace-write",
|
||||
};
|
||||
case "full-access":
|
||||
return {
|
||||
approvalPolicy: "never",
|
||||
sandbox: "danger-full-access",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
approvalPolicy: "never",
|
||||
sandbox: "danger-full-access",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -433,7 +439,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
private readonly sessions = new Map<ThreadId, CodexSessionContext>();
|
||||
|
||||
private runPromise: (effect: Effect.Effect<unknown, never>) => Promise<unknown>;
|
||||
constructor(services?: ServiceMap.ServiceMap<never>) {
|
||||
constructor(services?: Context.Context<never>) {
|
||||
super();
|
||||
this.runPromise = services ? Effect.runPromiseWith(services) : Effect.runPromise;
|
||||
}
|
||||
@@ -634,7 +640,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
this.stopSession(threadId);
|
||||
} else {
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "error",
|
||||
provider: "codex",
|
||||
threadId,
|
||||
@@ -733,7 +739,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
if (!turnIdRaw) {
|
||||
throw new Error("turn/start response did not include a turn id.");
|
||||
}
|
||||
const turnId = TurnId.makeUnsafe(turnIdRaw);
|
||||
const turnId = TurnId.make(turnIdRaw);
|
||||
|
||||
this.updateSession(context, {
|
||||
status: "running",
|
||||
@@ -834,7 +840,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -873,7 +879,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1055,7 +1061,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
: undefined;
|
||||
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1128,7 +1134,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
const requestKind = this.requestKindForMethod(request.method);
|
||||
let requestId: ApprovalRequestId | undefined;
|
||||
if (requestKind) {
|
||||
requestId = ApprovalRequestId.makeUnsafe(randomUUID());
|
||||
requestId = ApprovalRequestId.make(randomUUID());
|
||||
const pendingRequest: PendingApprovalRequest = {
|
||||
requestId,
|
||||
jsonRpcId: request.id,
|
||||
@@ -1147,7 +1153,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
if (request.method === "item/tool/requestUserInput") {
|
||||
requestId = ApprovalRequestId.makeUnsafe(randomUUID());
|
||||
requestId = ApprovalRequestId.make(randomUUID());
|
||||
context.pendingUserInputs.set(requestId, {
|
||||
requestId,
|
||||
jsonRpcId: request.id,
|
||||
@@ -1158,7 +1164,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "request",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1248,7 +1254,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
|
||||
private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "session",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1260,7 +1266,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
|
||||
private emitErrorEvent(context: CodexSessionContext, method: string, message: string): void {
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "error",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1276,7 +1282,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
message: string,
|
||||
): void {
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1335,7 +1341,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
const turns = turnsRaw.map((turnValue, index) => {
|
||||
const turn = this.readObject(turnValue);
|
||||
const turnIdRaw = this.readString(turn, "id") ?? `${threadIdRaw}:turn:${index + 1}`;
|
||||
const turnId = TurnId.makeUnsafe(turnIdRaw);
|
||||
const turnId = TurnId.make(turnIdRaw);
|
||||
const items = this.readArray(turn, "items") ?? [];
|
||||
return {
|
||||
id: turnId,
|
||||
@@ -1584,9 +1590,9 @@ function readResumeThreadId(input: {
|
||||
}
|
||||
|
||||
function toTurnId(value: string | undefined): TurnId | undefined {
|
||||
return brandIfNonEmpty(value, TurnId.makeUnsafe);
|
||||
return brandIfNonEmpty(value, TurnId.make);
|
||||
}
|
||||
|
||||
function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
|
||||
return brandIfNonEmpty(value, ProviderItemId.makeUnsafe);
|
||||
return brandIfNonEmpty(value, ProviderItemId.make);
|
||||
}
|
||||
@@ -6,13 +6,16 @@
|
||||
*
|
||||
* @module ServerConfig
|
||||
*/
|
||||
import { Effect, FileSystem, Layer, LogLevel, Path, Schema, ServiceMap } from "effect";
|
||||
import { Effect, FileSystem, Layer, LogLevel, Path, Schema, Context } from "effect";
|
||||
|
||||
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.
|
||||
*/
|
||||
@@ -25,10 +28,14 @@ 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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -36,6 +43,15 @@ 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;
|
||||
@@ -44,7 +60,8 @@ export interface ServerConfigShape extends ServerDerivedPaths {
|
||||
readonly staticDir: string | undefined;
|
||||
readonly devUrl: URL | undefined;
|
||||
readonly noBrowser: boolean;
|
||||
readonly authToken: string | undefined;
|
||||
readonly startupPresentation: StartupPresentation;
|
||||
readonly desktopBootstrapToken: string | undefined;
|
||||
readonly autoBootstrapProjectFromCwd: boolean;
|
||||
readonly logWebSocketEvents: boolean;
|
||||
}
|
||||
@@ -68,10 +85,14 @@ 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"),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -90,6 +111,7 @@ 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" },
|
||||
);
|
||||
@@ -98,7 +120,7 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server
|
||||
/**
|
||||
* ServerConfig - Service tag for server runtime configuration.
|
||||
*/
|
||||
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
|
||||
export class ServerConfig extends Context.Service<ServerConfig, ServerConfigShape>()(
|
||||
"t3/config/ServerConfig",
|
||||
) {
|
||||
static readonly layerTest = (cwd: string, baseDirOrPrefix: string | { prefix: string }) =>
|
||||
@@ -117,6 +139,15 @@ 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,
|
||||
@@ -125,10 +156,11 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS
|
||||
logWebSocketEvents: false,
|
||||
port: 0,
|
||||
host: undefined,
|
||||
authToken: undefined,
|
||||
desktopBootstrapToken: undefined,
|
||||
staticDir: undefined,
|
||||
devUrl,
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
} satisfies ServerConfigShape;
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
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",
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
|
||||
import { Effect, FileSystem, Layer, Path, Random } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/ServerEnvironment.ts";
|
||||
import { version } from "../../../package.json" with { type: "json" };
|
||||
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
|
||||
|
||||
function platformOs(): ExecutionEnvironmentDescriptor["platform"]["os"] {
|
||||
switch (process.platform) {
|
||||
case "darwin":
|
||||
return "darwin";
|
||||
case "linux":
|
||||
return "linux";
|
||||
case "win32":
|
||||
return "windows";
|
||||
default:
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
function platformArch(): ExecutionEnvironmentDescriptor["platform"]["arch"] {
|
||||
switch (process.arch) {
|
||||
case "arm64":
|
||||
return "arm64";
|
||||
case "x64":
|
||||
return "x64";
|
||||
default:
|
||||
return "other";
|
||||
}
|
||||
}
|
||||
|
||||
export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
|
||||
const readPersistedEnvironmentId = Effect.gen(function* () {
|
||||
const exists = yield* fileSystem
|
||||
.exists(serverConfig.environmentIdPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (!exists) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const raw = yield* fileSystem
|
||||
.readFileString(serverConfig.environmentIdPath)
|
||||
.pipe(Effect.map((value) => value.trim()));
|
||||
|
||||
return raw.length > 0 ? raw : null;
|
||||
});
|
||||
|
||||
const persistEnvironmentId = (value: string) =>
|
||||
fileSystem.writeFileString(serverConfig.environmentIdPath, `${value}\n`);
|
||||
|
||||
const environmentIdRaw = yield* Effect.gen(function* () {
|
||||
const persisted = yield* readPersistedEnvironmentId;
|
||||
if (persisted) {
|
||||
return persisted;
|
||||
}
|
||||
|
||||
const generated = yield* Random.nextUUIDv4;
|
||||
yield* persistEnvironmentId(generated);
|
||||
return generated;
|
||||
});
|
||||
|
||||
const environmentId = EnvironmentId.make(environmentIdRaw);
|
||||
const cwdBaseName = path.basename(serverConfig.cwd).trim();
|
||||
const label = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName,
|
||||
});
|
||||
|
||||
const descriptor: ExecutionEnvironmentDescriptor = {
|
||||
environmentId,
|
||||
label,
|
||||
platform: {
|
||||
os: platformOs(),
|
||||
arch: platformArch(),
|
||||
},
|
||||
serverVersion: version,
|
||||
capabilities: {
|
||||
repositoryIdentity: true,
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
getEnvironmentId: Effect.succeed(environmentId),
|
||||
getDescriptor: Effect.succeed(descriptor),
|
||||
} satisfies ServerEnvironmentShape;
|
||||
});
|
||||
|
||||
export const ServerEnvironmentLive = Layer.effect(ServerEnvironment, makeServerEnvironment());
|
||||
@@ -0,0 +1,150 @@
|
||||
import { afterEach, describe, expect, it } from "@effect/vitest";
|
||||
import { Effect, FileSystem } from "effect";
|
||||
import { vi } from "vitest";
|
||||
|
||||
vi.mock("../../processRunner.ts", () => ({
|
||||
runProcess: vi.fn(),
|
||||
}));
|
||||
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
|
||||
|
||||
const mockedRunProcess = vi.mocked(runProcess);
|
||||
const NoopFileSystemLayer = FileSystem.layerNoop({});
|
||||
|
||||
afterEach(() => {
|
||||
mockedRunProcess.mockReset();
|
||||
});
|
||||
|
||||
describe("resolveServerEnvironmentLabel", () => {
|
||||
it.effect("uses hostname fallback regardless of launch mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "win32",
|
||||
hostname: "macbook-pro",
|
||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||
|
||||
expect(result).toBe("macbook-pro");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers the macOS ComputerName", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: " Julius's MacBook Pro \n",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "darwin",
|
||||
hostname: "macbook-pro",
|
||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||
|
||||
expect(result).toBe("Julius's MacBook Pro");
|
||||
expect(mockedRunProcess).toHaveBeenCalledWith(
|
||||
"scutil",
|
||||
["--get", "ComputerName"],
|
||||
expect.objectContaining({ allowNonZeroExit: true }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers Linux PRETTY_HOSTNAME from machine-info", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "linux",
|
||||
hostname: "buildbox",
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
FileSystem.layerNoop({
|
||||
exists: (path) => Effect.succeed(path === "/etc/machine-info"),
|
||||
readFileString: (path) =>
|
||||
path === "/etc/machine-info"
|
||||
? Effect.succeed('PRETTY_HOSTNAME="Build Agent 01"\nICON_NAME="computer-vm"\n')
|
||||
: Effect.succeed(""),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(result).toBe("Build Agent 01");
|
||||
expect(mockedRunProcess).not.toHaveBeenCalled();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to hostnamectl pretty hostname on Linux", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: "CI Runner\n",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "linux",
|
||||
hostname: "runner-01",
|
||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||
|
||||
expect(result).toBe("CI Runner");
|
||||
expect(mockedRunProcess).toHaveBeenCalledWith(
|
||||
"hostnamectl",
|
||||
["--pretty"],
|
||||
expect.objectContaining({ allowNonZeroExit: true }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to the hostname when friendly labels are unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "win32",
|
||||
hostname: "JULIUS-LAPTOP",
|
||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||
|
||||
expect(result).toBe("JULIUS-LAPTOP");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to the hostname when the friendly-label command is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockRejectedValueOnce(new Error("spawn scutil ENOENT"));
|
||||
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "darwin",
|
||||
hostname: "macbook-pro",
|
||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||
|
||||
expect(result).toBe("macbook-pro");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to the cwd basename when the hostname is blank", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: " ",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "linux",
|
||||
hostname: " ",
|
||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||
|
||||
expect(result).toBe("t3code");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import * as OS from "node:os";
|
||||
|
||||
import { Effect, FileSystem } from "effect";
|
||||
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
|
||||
interface ResolveServerEnvironmentLabelInput {
|
||||
readonly cwdBaseName: string;
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly hostname?: string | null;
|
||||
}
|
||||
|
||||
function normalizeLabel(value: string | null | undefined): string | null {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed && trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function parseMachineInfoValue(raw: string, key: string): string | null {
|
||||
for (const line of raw.split(/\r?\n/g)) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.length === 0 || trimmed.startsWith("#") || !trimmed.startsWith(`${key}=`)) {
|
||||
continue;
|
||||
}
|
||||
const value = trimmed.slice(key.length + 1).trim();
|
||||
if (
|
||||
(value.startsWith('"') && value.endsWith('"')) ||
|
||||
(value.startsWith("'") && value.endsWith("'"))
|
||||
) {
|
||||
return normalizeLabel(value.slice(1, -1));
|
||||
}
|
||||
return normalizeLabel(value);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const readLinuxMachineInfo = Effect.fn("readLinuxMachineInfo")(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const exists = yield* fileSystem
|
||||
.exists("/etc/machine-info")
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (!exists) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return yield* fileSystem
|
||||
.readFileString("/etc/machine-info")
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
});
|
||||
|
||||
const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
) {
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
runProcess(command, args, {
|
||||
allowNonZeroExit: true,
|
||||
}),
|
||||
catch: () => null,
|
||||
}).pipe(Effect.orElseSucceed(() => null));
|
||||
|
||||
if (!result || result.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalizeLabel(result.stdout);
|
||||
});
|
||||
|
||||
const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function* (
|
||||
platform: NodeJS.Platform,
|
||||
) {
|
||||
if (platform === "darwin") {
|
||||
return yield* runFriendlyLabelCommand("scutil", ["--get", "ComputerName"]);
|
||||
}
|
||||
|
||||
if (platform === "linux") {
|
||||
const machineInfo = normalizeLabel(yield* readLinuxMachineInfo());
|
||||
if (machineInfo) {
|
||||
const prettyHostname = parseMachineInfoValue(machineInfo, "PRETTY_HOSTNAME");
|
||||
if (prettyHostname) {
|
||||
return prettyHostname;
|
||||
}
|
||||
}
|
||||
|
||||
return yield* runFriendlyLabelCommand("hostnamectl", ["--pretty"]);
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
export const resolveServerEnvironmentLabel = Effect.fn("resolveServerEnvironmentLabel")(function* (
|
||||
input: ResolveServerEnvironmentLabelInput,
|
||||
) {
|
||||
const platform = input.platform ?? process.platform;
|
||||
const friendlyHostLabel = yield* resolveFriendlyHostLabel(platform);
|
||||
if (friendlyHostLabel) {
|
||||
return friendlyHostLabel;
|
||||
}
|
||||
|
||||
const hostname = normalizeLabel(input.hostname ?? OS.hostname());
|
||||
if (hostname) {
|
||||
return hostname;
|
||||
}
|
||||
|
||||
return normalizeLabel(input.cwdBaseName) ?? "T3 environment";
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { EnvironmentId, ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export interface ServerEnvironmentShape {
|
||||
readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
|
||||
readonly getDescriptor: Effect.Effect<ExecutionEnvironmentDescriptor>;
|
||||
}
|
||||
|
||||
export class ServerEnvironment extends Context.Service<ServerEnvironment, ServerEnvironmentShape>()(
|
||||
"t3/environment/Services/ServerEnvironment",
|
||||
) {}
|
||||
@@ -85,44 +85,43 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
||||
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
const materializeImageAttachments = (
|
||||
const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
|
||||
_operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle",
|
||||
attachments: BranchNameGenerationInput["attachments"],
|
||||
): Effect.Effect<MaterializedImageAttachments, TextGenerationError> =>
|
||||
Effect.gen(function* () {
|
||||
if (!attachments || attachments.length === 0) {
|
||||
return { imagePaths: [] };
|
||||
): 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;
|
||||
}
|
||||
|
||||
const imagePaths: string[] = [];
|
||||
for (const attachment of attachments) {
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolvedPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
|
||||
continue;
|
||||
}
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(resolvedPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
continue;
|
||||
}
|
||||
imagePaths.push(resolvedPath);
|
||||
const resolvedPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
|
||||
continue;
|
||||
}
|
||||
return { imagePaths };
|
||||
});
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(resolvedPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
continue;
|
||||
}
|
||||
imagePaths.push(resolvedPath);
|
||||
}
|
||||
return { imagePaths };
|
||||
});
|
||||
|
||||
const runCodexJson = <S extends Schema.Top>({
|
||||
const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
|
||||
operation,
|
||||
cwd,
|
||||
prompt,
|
||||
@@ -142,138 +141,137 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
imagePaths?: ReadonlyArray<string>;
|
||||
cleanupPaths?: ReadonlyArray<string>;
|
||||
modelSelection: CodexModelSelection;
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const schemaPath = yield* writeTempFile(
|
||||
operation,
|
||||
"codex-schema",
|
||||
JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
|
||||
}): 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,
|
||||
);
|
||||
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
||||
|
||||
const codexSettings = yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => settings.providers.codex,
|
||||
).pipe(Effect.catch(() => Effect.undefined));
|
||||
|
||||
const runCodexCommand = Effect.gen(function* () {
|
||||
const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
|
||||
getCodexModelCapabilities(modelSelection.model),
|
||||
modelSelection.options,
|
||||
);
|
||||
const reasoningEffort =
|
||||
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
|
||||
const command = ChildProcess.make(
|
||||
codexSettings?.binaryPath || "codex",
|
||||
[
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
modelSelection.model,
|
||||
"--config",
|
||||
`model_reasoning_effort="${reasoningEffort}"`,
|
||||
...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
outputPath,
|
||||
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
||||
"-",
|
||||
],
|
||||
{
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
|
||||
},
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdin: {
|
||||
stream: Stream.encodeText(Stream.make(prompt)),
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const child = yield* commandSpawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
|
||||
),
|
||||
);
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
readStreamAsString(operation, child.stdout),
|
||||
readStreamAsString(operation, child.stderr),
|
||||
child.exitCode.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
if (exitCode !== 0) {
|
||||
const stderrDetail = stderr.trim();
|
||||
const stdoutDetail = stdout.trim();
|
||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||
return yield* new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
detail.length > 0
|
||||
? `Codex CLI command failed: ${detail}`
|
||||
: `Codex CLI command failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const cleanup = Effect.all(
|
||||
[schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
|
||||
const reasoningEffort =
|
||||
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
|
||||
const command = ChildProcess.make(
|
||||
codexSettings?.binaryPath || "codex",
|
||||
[
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
modelSelection.model,
|
||||
"--config",
|
||||
`model_reasoning_effort="${reasoningEffort}"`,
|
||||
...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
outputPath,
|
||||
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
||||
"-",
|
||||
],
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
|
||||
},
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdin: {
|
||||
stream: Stream.encodeText(Stream.make(prompt)),
|
||||
},
|
||||
},
|
||||
).pipe(Effect.asVoid);
|
||||
);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
yield* runCodexCommand.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(CODEX_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
|
||||
),
|
||||
onSome: () => Effect.void,
|
||||
const child = yield* commandSpawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
|
||||
),
|
||||
);
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
readStreamAsString(operation, child.stdout),
|
||||
readStreamAsString(operation, child.stderr),
|
||||
child.exitCode.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
if (exitCode !== 0) {
|
||||
const stderrDetail = stderr.trim();
|
||||
const stdoutDetail = stdout.trim();
|
||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||
return yield* new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
detail.length > 0
|
||||
? `Codex CLI command failed: ${detail}`
|
||||
: `Codex CLI command failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const cleanup = Effect.all(
|
||||
[schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
yield* runCodexCommand().pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(CODEX_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
|
||||
),
|
||||
onSome: () => Effect.void,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* fileSystem.readFileString(outputPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Failed to read Codex output file.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Codex returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* fileSystem.readFileString(outputPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Failed to read Codex output file.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Codex returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.ensuring(cleanup));
|
||||
});
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.ensuring(cleanup));
|
||||
});
|
||||
|
||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
|
||||
"CodexTextGeneration.generateCommitMessage",
|
||||
|
||||
@@ -40,6 +40,24 @@ function writeTextFile(
|
||||
});
|
||||
}
|
||||
|
||||
function removePath(
|
||||
targetPath: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.remove(targetPath, { recursive: true, force: true });
|
||||
});
|
||||
}
|
||||
|
||||
function makeDirectory(
|
||||
dirPath: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.makeDirectory(dirPath, { recursive: true });
|
||||
});
|
||||
}
|
||||
|
||||
/** Run a raw git command for test setup (not under test). */
|
||||
function git(
|
||||
cwd: string,
|
||||
@@ -59,6 +77,23 @@ function git(
|
||||
});
|
||||
}
|
||||
|
||||
function configureRemote(
|
||||
cwd: string,
|
||||
remoteName: string,
|
||||
remotePath: string,
|
||||
fetchNamespace: string,
|
||||
): Effect.Effect<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;
|
||||
@@ -202,7 +237,10 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
|
||||
const seenChunks: string[][] = [];
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (input.args.join(" ") !== "check-ignore --no-index -z --stdin") {
|
||||
if (
|
||||
input.args.join(" ") !==
|
||||
"-c core.fsmonitor=false -c core.untrackedCache=false check-ignore --no-index -z --stdin"
|
||||
) {
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
@@ -235,6 +273,35 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
expect(result).toEqual(expectedPaths);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("listWorkspaceFiles disables fsmonitor and untracked cache helpers", () =>
|
||||
Effect.gen(function* () {
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
expect(input.args).toEqual([
|
||||
"-c",
|
||||
"core.fsmonitor=false",
|
||||
"-c",
|
||||
"core.untrackedCache=false",
|
||||
"ls-files",
|
||||
"--cached",
|
||||
"--others",
|
||||
"--exclude-standard",
|
||||
"-z",
|
||||
]);
|
||||
return Effect.succeed({
|
||||
code: 0,
|
||||
stdout: "src/index.ts\0README.md\0",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
});
|
||||
|
||||
const result = yield* core.listWorkspaceFiles("/virtual/repo");
|
||||
expect(result.paths).toEqual(["src/index.ts", "README.md"]);
|
||||
expect(result.truncated).toBe(false);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── listGitBranches ──
|
||||
@@ -250,6 +317,21 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns isRepo: false for deleted directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const deletedDir = path.join(tmp, "deleted-repo");
|
||||
yield* makeDirectory(deletedDir);
|
||||
yield* removePath(deletedDir);
|
||||
|
||||
const result = yield* (yield* GitCore).listBranches({ cwd: deletedDir });
|
||||
|
||||
expect(result.isRepo).toBe(false);
|
||||
expect(result.hasOriginRemote).toBe(false);
|
||||
expect(result.branches).toEqual([]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns the current branch with current: true", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
@@ -369,6 +451,36 @@ 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();
|
||||
@@ -514,6 +626,41 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
expect(remoteBranch?.remoteName).toBe(remoteName);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"filters branch queries before pagination and dedupes origin refs with local matches",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const tmp = yield* makeTmpDir();
|
||||
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
const { initialBranch } = yield* initRepoWithCommit(tmp);
|
||||
yield* git(tmp, ["remote", "add", "origin", remote]);
|
||||
yield* git(tmp, ["push", "-u", "origin", initialBranch]);
|
||||
|
||||
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/demo" });
|
||||
yield* git(tmp, ["push", "-u", "origin", "feature/demo"]);
|
||||
|
||||
yield* git(tmp, ["checkout", "-b", "feature/remote-only"]);
|
||||
yield* git(tmp, ["push", "-u", "origin", "feature/remote-only"]);
|
||||
yield* git(tmp, ["checkout", initialBranch]);
|
||||
yield* git(tmp, ["branch", "-D", "feature/remote-only"]);
|
||||
|
||||
const result = yield* (yield* GitCore).listBranches({
|
||||
cwd: tmp,
|
||||
query: "feature/",
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
expect(result.totalCount).toBe(2);
|
||||
expect(result.nextCursor).toBeNull();
|
||||
expect(result.branches.map((branch) => branch.name)).toEqual([
|
||||
"feature/demo",
|
||||
"origin/feature/remote-only",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── checkoutGitBranch ──
|
||||
@@ -535,8 +682,8 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
|
||||
it.effect("refreshes upstream behind count after checkout when remote branch advanced", () =>
|
||||
Effect.gen(function* () {
|
||||
const services = yield* Effect.services();
|
||||
const runPromise = Effect.runPromiseWith(services);
|
||||
const context = yield* Effect.context<never>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
@@ -587,7 +734,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps checkout successful when upstream refresh fails", () =>
|
||||
it.effect("statusDetails remains successful when upstream refresh fails after checkout", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
@@ -612,7 +759,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
const realGitCore = yield* GitCore;
|
||||
let refreshFetchAttempts = 0;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (input.args[0] === "fetch") {
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
refreshFetchAttempts += 1;
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
@@ -626,16 +773,15 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
return realGitCore.execute(input);
|
||||
});
|
||||
yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
|
||||
yield* Effect.promise(() =>
|
||||
vi.waitFor(() => {
|
||||
expect(refreshFetchAttempts).toBe(1);
|
||||
}),
|
||||
);
|
||||
const status = yield* core.statusDetails(source);
|
||||
expect(refreshFetchAttempts).toBe(1);
|
||||
expect(status.branch).toBe(featureBranch);
|
||||
expect(status.upstreamRef).toBe(`origin/${featureBranch}`);
|
||||
expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refresh fetch is scoped to the checked out branch upstream refspec", () =>
|
||||
it.effect("defers upstream refresh until statusDetails is requested", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
@@ -657,10 +803,10 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
yield* git(source, ["checkout", defaultBranch]);
|
||||
|
||||
const realGitCore = yield* GitCore;
|
||||
let fetchArgs: readonly string[] | null = null;
|
||||
let refreshFetchAttempts = 0;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (input.args[0] === "fetch") {
|
||||
fetchArgs = [...input.args];
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
refreshFetchAttempts += 1;
|
||||
return Effect.succeed({
|
||||
code: 0,
|
||||
stdout: "",
|
||||
@@ -672,76 +818,164 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
return realGitCore.execute(input);
|
||||
});
|
||||
yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
|
||||
yield* Effect.promise(() =>
|
||||
vi.waitFor(() => {
|
||||
expect(fetchArgs).not.toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
|
||||
expect(fetchArgs).toEqual([
|
||||
"fetch",
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
"origin",
|
||||
`+refs/heads/${featureBranch}:refs/remotes/origin/${featureBranch}`,
|
||||
]);
|
||||
yield* Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, 50)));
|
||||
expect(refreshFetchAttempts).toBe(0);
|
||||
const status = yield* core.statusDetails(source);
|
||||
expect(status.branch).toBe(featureBranch);
|
||||
expect(refreshFetchAttempts).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns checkout result before background upstream refresh completes", () =>
|
||||
it.effect("coalesces upstream refreshes across sibling worktrees on the same remote", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
const ok = (stdout = "") =>
|
||||
Effect.succeed({
|
||||
code: 0,
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
|
||||
yield* initRepoWithCommit(source);
|
||||
const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
yield* git(source, ["remote", "add", "origin", remote]);
|
||||
yield* git(source, ["push", "-u", "origin", defaultBranch]);
|
||||
|
||||
const featureBranch = "feature/background-refresh";
|
||||
yield* git(source, ["checkout", "-b", featureBranch]);
|
||||
yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n");
|
||||
yield* git(source, ["add", "feature.txt"]);
|
||||
yield* git(source, ["commit", "-m", "feature base"]);
|
||||
yield* git(source, ["push", "-u", "origin", featureBranch]);
|
||||
yield* git(source, ["checkout", defaultBranch]);
|
||||
|
||||
const realGitCore = yield* GitCore;
|
||||
let fetchStarted = false;
|
||||
let releaseFetch!: () => void;
|
||||
const waitForReleasePromise = new Promise<void>((resolve) => {
|
||||
releaseFetch = resolve;
|
||||
});
|
||||
let fetchCount = 0;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (input.args[0] === "fetch") {
|
||||
fetchStarted = true;
|
||||
return Effect.promise(() =>
|
||||
waitForReleasePromise.then(() => ({
|
||||
code: 0,
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
})),
|
||||
if (
|
||||
input.args[0] === "rev-parse" &&
|
||||
input.args[1] === "--abbrev-ref" &&
|
||||
input.args[2] === "--symbolic-full-name" &&
|
||||
input.args[3] === "@{upstream}"
|
||||
) {
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123" ? "origin/feature/pr-123\n" : "origin/main\n",
|
||||
);
|
||||
}
|
||||
return realGitCore.execute(input);
|
||||
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");
|
||||
expect(input.args).toEqual([
|
||||
"--git-dir",
|
||||
"/repo/.git",
|
||||
"fetch",
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
"origin",
|
||||
]);
|
||||
return ok();
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.status") {
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123"
|
||||
? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n"
|
||||
: "# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n",
|
||||
);
|
||||
}
|
||||
if (
|
||||
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
|
||||
input.operation === "GitCore.statusDetails.stagedNumstat"
|
||||
) {
|
||||
return ok();
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.defaultRef") {
|
||||
return ok("refs/remotes/origin/main\n");
|
||||
}
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "Unexpected git command in shared refresh cache test.",
|
||||
}),
|
||||
);
|
||||
});
|
||||
yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
|
||||
yield* Effect.promise(() =>
|
||||
vi.waitFor(() => {
|
||||
expect(fetchStarted).toBe(true);
|
||||
}),
|
||||
);
|
||||
expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
|
||||
releaseFetch();
|
||||
|
||||
yield* core.statusDetails("/repo/worktrees/main");
|
||||
yield* core.statusDetails("/repo/worktrees/pr-123");
|
||||
expect(fetchCount).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"briefly backs off failed upstream refreshes across sibling worktrees on one remote",
|
||||
() =>
|
||||
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(
|
||||
input.cwd === "/repo/worktrees/pr-123"
|
||||
? "origin/feature/pr-123\n"
|
||||
: "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.operation === "GitCore.statusDetails.status") {
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123"
|
||||
? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n"
|
||||
: "# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n",
|
||||
);
|
||||
}
|
||||
if (
|
||||
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
|
||||
input.operation === "GitCore.statusDetails.stagedNumstat"
|
||||
) {
|
||||
return ok();
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.defaultRef") {
|
||||
return ok("refs/remotes/origin/main\n");
|
||||
}
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "Unexpected git command in refresh failure cooldown test.",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
yield* core.statusDetails("/repo/worktrees/main");
|
||||
yield* core.statusDetails("/repo/worktrees/pr-123");
|
||||
expect(fetchCount).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("throws when branch does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
@@ -779,16 +1013,21 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
it.effect("checks out a remote tracking branch when remote name contains slashes", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const prefixRemote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
const prefixFetchNamespace = "prefix-my-org";
|
||||
const prefixRemoteName = "my-org";
|
||||
const remoteName = "my-org/upstream";
|
||||
const featureBranch = "feature";
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* git(prefixRemote, ["init", "--bare"]);
|
||||
|
||||
yield* initRepoWithCommit(source);
|
||||
const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
yield* git(source, ["remote", "add", remoteName, remote]);
|
||||
yield* configureRemote(source, prefixRemoteName, prefixRemote, prefixFetchNamespace);
|
||||
yield* configureRemote(source, remoteName, remote, remoteName);
|
||||
yield* git(source, ["push", "-u", remoteName, defaultBranch]);
|
||||
|
||||
yield* git(source, ["checkout", "-b", featureBranch]);
|
||||
@@ -799,12 +1038,40 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
yield* git(source, ["checkout", defaultBranch]);
|
||||
yield* git(source, ["branch", "-D", featureBranch]);
|
||||
|
||||
yield* (yield* GitCore).checkoutBranch({
|
||||
const checkoutResult = yield* (yield* GitCore).checkoutBranch({
|
||||
cwd: source,
|
||||
branch: `${remoteName}/${featureBranch}`,
|
||||
});
|
||||
|
||||
expect(checkoutResult.branch).toBe("upstream/feature");
|
||||
expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature");
|
||||
const realGitCore = yield* GitCore;
|
||||
let fetchArgs: readonly string[] | null = null;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
fetchArgs = [...input.args];
|
||||
return Effect.succeed({
|
||||
code: 0,
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
}
|
||||
return realGitCore.execute(input);
|
||||
});
|
||||
|
||||
const status = yield* core.statusDetails(source);
|
||||
expect(status.branch).toBe("upstream/feature");
|
||||
expect(status.upstreamRef).toBe(`${remoteName}/${featureBranch}`);
|
||||
expect(fetchArgs).toEqual([
|
||||
"--git-dir",
|
||||
path.join(source, ".git"),
|
||||
"fetch",
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
remoteName,
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1415,6 +1682,37 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns a non-repo status for deleted directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const deletedDir = path.join(tmp, "deleted-repo");
|
||||
yield* makeDirectory(deletedDir);
|
||||
yield* removePath(deletedDir);
|
||||
const core = yield* GitCore;
|
||||
|
||||
const status = yield* core.statusDetails(deletedDir);
|
||||
const localStatus = yield* core.statusDetailsLocal(deletedDir);
|
||||
|
||||
expect(status).toEqual({
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
upstreamRef: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
});
|
||||
expect(localStatus).toEqual(status);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("computes ahead count against base branch when no upstream is configured", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
@@ -1691,6 +1989,47 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("pushes to the tracked upstream when the remote name contains slashes", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir();
|
||||
const prefixRemote = yield* makeTmpDir();
|
||||
const prefixFetchNamespace = "prefix-my-org";
|
||||
const prefixRemoteName = "my-org";
|
||||
const remoteName = "my-org/upstream";
|
||||
const featureBranch = "feature/slash-remote-push";
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* git(prefixRemote, ["init", "--bare"]);
|
||||
|
||||
const { initialBranch } = yield* initRepoWithCommit(tmp);
|
||||
yield* configureRemote(tmp, prefixRemoteName, prefixRemote, prefixFetchNamespace);
|
||||
yield* configureRemote(tmp, remoteName, remote, remoteName);
|
||||
yield* git(tmp, ["push", "-u", remoteName, initialBranch]);
|
||||
|
||||
yield* git(tmp, ["checkout", "-b", featureBranch]);
|
||||
yield* writeTextFile(path.join(tmp, "feature.txt"), "first revision\n");
|
||||
yield* git(tmp, ["add", "feature.txt"]);
|
||||
yield* git(tmp, ["commit", "-m", "feature base"]);
|
||||
yield* git(tmp, ["push", "-u", remoteName, featureBranch]);
|
||||
|
||||
yield* writeTextFile(path.join(tmp, "feature.txt"), "second revision\n");
|
||||
yield* git(tmp, ["add", "feature.txt"]);
|
||||
yield* git(tmp, ["commit", "-m", "feature update"]);
|
||||
|
||||
const core = yield* GitCore;
|
||||
const pushed = yield* core.pushCurrentBranch(tmp, null);
|
||||
expect(pushed.status).toBe("pushed");
|
||||
expect(pushed.setUpstream).toBe(false);
|
||||
expect(pushed.upstreamBranch).toBe(`${remoteName}/${featureBranch}`);
|
||||
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
|
||||
`${remoteName}/${featureBranch}`,
|
||||
);
|
||||
expect(yield* git(tmp, ["ls-remote", "--heads", remoteName, featureBranch])).toContain(
|
||||
featureBranch,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("includes command context when worktree removal fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
|
||||
@@ -18,15 +18,24 @@ import {
|
||||
} from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
import { GitCommandError, type GitBranch } from "@t3tools/contracts";
|
||||
import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
|
||||
import { compactTraceAttributes } from "../../observability/Attributes.ts";
|
||||
import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../../observability/Metrics.ts";
|
||||
import {
|
||||
GitCore,
|
||||
type ExecuteGitProgress,
|
||||
type GitCommitOptions,
|
||||
type GitCoreShape,
|
||||
type GitStatusDetails,
|
||||
type ExecuteGitInput,
|
||||
type ExecuteGitResult,
|
||||
} from "../Services/GitCore.ts";
|
||||
import {
|
||||
parseRemoteNames,
|
||||
parseRemoteNamesInGitOrder,
|
||||
parseRemoteRefWithRemoteNames,
|
||||
} from "../remoteRefs.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
|
||||
@@ -39,21 +48,39 @@ const RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES = 19_000;
|
||||
const RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000;
|
||||
const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
|
||||
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
|
||||
const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
|
||||
"-c",
|
||||
"core.fsmonitor=false",
|
||||
"-c",
|
||||
"core.untrackedCache=false",
|
||||
] as const;
|
||||
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
|
||||
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
|
||||
const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);
|
||||
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
|
||||
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
|
||||
const GIT_LIST_BRANCHES_DEFAULT_LIMIT = 100;
|
||||
const NON_REPOSITORY_STATUS_DETAILS = Object.freeze<GitStatusDetails>({
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
upstreamRef: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
});
|
||||
|
||||
type TraceTailState = {
|
||||
processedChars: number;
|
||||
remainder: string;
|
||||
};
|
||||
|
||||
class StatusUpstreamRefreshCacheKey extends Data.Class<{
|
||||
cwd: string;
|
||||
upstreamRef: string;
|
||||
class StatusRemoteRefreshCacheKey extends Data.Class<{
|
||||
gitCommonDir: string;
|
||||
remoteName: string;
|
||||
upstreamBranch: string;
|
||||
}> {}
|
||||
|
||||
interface ExecuteGitOptions {
|
||||
@@ -177,12 +204,38 @@ function parseBranchLine(line: string): { name: string; current: boolean } | nul
|
||||
};
|
||||
}
|
||||
|
||||
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 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 sanitizeRemoteName(value: string): string {
|
||||
@@ -217,30 +270,41 @@ function parseRemoteFetchUrls(stdout: string): Map<string, string> {
|
||||
return remotes;
|
||||
}
|
||||
|
||||
function parseRemoteRefWithRemoteNames(
|
||||
branchName: string,
|
||||
function parseUpstreamRefWithRemoteNames(
|
||||
upstreamRef: string,
|
||||
remoteNames: ReadonlyArray<string>,
|
||||
): { remoteRef: string; remoteName: string; localBranch: string } | null {
|
||||
const trimmedBranchName = branchName.trim();
|
||||
if (trimmedBranchName.length === 0) return null;
|
||||
|
||||
for (const remoteName of remoteNames) {
|
||||
const remotePrefix = `${remoteName}/`;
|
||||
if (!trimmedBranchName.startsWith(remotePrefix)) {
|
||||
continue;
|
||||
}
|
||||
const localBranch = trimmedBranchName.slice(remotePrefix.length).trim();
|
||||
if (localBranch.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
remoteRef: trimmedBranchName,
|
||||
remoteName,
|
||||
localBranch,
|
||||
};
|
||||
): { upstreamRef: string; remoteName: string; upstreamBranch: string } | null {
|
||||
const parsed = parseRemoteRefWithRemoteNames(upstreamRef, remoteNames);
|
||||
if (!parsed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return null;
|
||||
return {
|
||||
upstreamRef,
|
||||
remoteName: parsed.remoteName,
|
||||
upstreamBranch: parsed.branchName,
|
||||
};
|
||||
}
|
||||
|
||||
function parseUpstreamRefByFirstSeparator(
|
||||
upstreamRef: string,
|
||||
): { upstreamRef: string; remoteName: string; upstreamBranch: string } | null {
|
||||
const separatorIndex = upstreamRef.indexOf("/");
|
||||
if (separatorIndex <= 0 || separatorIndex === upstreamRef.length - 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const remoteName = upstreamRef.slice(0, separatorIndex).trim();
|
||||
const upstreamBranch = upstreamRef.slice(separatorIndex + 1).trim();
|
||||
if (remoteName.length === 0 || upstreamBranch.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
upstreamRef,
|
||||
remoteName,
|
||||
upstreamBranch,
|
||||
};
|
||||
}
|
||||
|
||||
function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null {
|
||||
@@ -306,6 +370,16 @@ function quoteGitCommand(args: ReadonlyArray<string>): string {
|
||||
return `git ${args.join(" ")}`;
|
||||
}
|
||||
|
||||
function isMissingGitCwdError(error: GitCommandError): boolean {
|
||||
const normalized = `${error.detail}\n${error.message}`.toLowerCase();
|
||||
return (
|
||||
normalized.includes("no such file or directory") ||
|
||||
normalized.includes("notfound: filesystem.access") ||
|
||||
normalized.includes("enoent") ||
|
||||
normalized.includes("not a directory")
|
||||
);
|
||||
}
|
||||
|
||||
function toGitCommandError(
|
||||
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
detail: string,
|
||||
@@ -327,6 +401,18 @@ 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") {
|
||||
@@ -399,6 +485,9 @@ const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* (
|
||||
|
||||
if (event === "child_start") {
|
||||
hookStartByChildKey.set(childKey, { hookName, startedAtMs: Date.now() });
|
||||
yield* addCurrentSpanEvent("git.hook.started", {
|
||||
hookName,
|
||||
});
|
||||
if (progress.onHookStarted) {
|
||||
yield* progress.onHookStarted(hookName);
|
||||
}
|
||||
@@ -407,12 +496,19 @@ const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* (
|
||||
|
||||
if (event === "child_exit") {
|
||||
hookStartByChildKey.delete(childKey);
|
||||
const code = traceRecord.success.code;
|
||||
const exitCode = typeof code === "number" && Number.isInteger(code) ? code : null;
|
||||
const durationMs = started ? Math.max(0, Date.now() - started.startedAtMs) : null;
|
||||
yield* addCurrentSpanEvent("git.hook.finished", {
|
||||
hookName: started?.hookName ?? hookName,
|
||||
exitCode,
|
||||
durationMs,
|
||||
});
|
||||
if (progress.onHookFinished) {
|
||||
const code = traceRecord.success.code;
|
||||
yield* progress.onHookFinished({
|
||||
hookName: started?.hookName ?? hookName,
|
||||
exitCode: typeof code === "number" && Number.isInteger(code) ? code : null,
|
||||
durationMs: started ? Math.max(0, Date.now() - started.startedAtMs) : null,
|
||||
exitCode,
|
||||
durationMs,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -564,13 +660,13 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
const path = yield* Path.Path;
|
||||
const { worktreesDir } = yield* ServerConfig;
|
||||
|
||||
let execute: GitCoreShape["execute"];
|
||||
let executeRaw: GitCoreShape["execute"];
|
||||
|
||||
if (options?.executeOverride) {
|
||||
execute = options.executeOverride;
|
||||
executeRaw = options.executeOverride;
|
||||
} else {
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
execute = Effect.fnUntraced(function* (input) {
|
||||
executeRaw = Effect.fnUntraced(function* (input) {
|
||||
const commandInput = {
|
||||
...input,
|
||||
args: [...input.args],
|
||||
@@ -671,6 +767,25 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
});
|
||||
}
|
||||
|
||||
const execute: GitCoreShape["execute"] = (input) =>
|
||||
executeRaw(input).pipe(
|
||||
withMetrics({
|
||||
counter: gitCommandsTotal,
|
||||
timer: gitCommandDuration,
|
||||
attributes: {
|
||||
operation: input.operation,
|
||||
},
|
||||
}),
|
||||
Effect.withSpan(input.operation, {
|
||||
kind: "client",
|
||||
attributes: {
|
||||
"git.operation": input.operation,
|
||||
"git.cwd": input.cwd,
|
||||
"git.args_count": input.args.length,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const executeGit = (
|
||||
operation: string,
|
||||
cwd: string,
|
||||
@@ -792,45 +907,26 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
return null;
|
||||
}
|
||||
|
||||
const separatorIndex = upstreamRef.indexOf("/");
|
||||
if (separatorIndex <= 0) {
|
||||
return null;
|
||||
}
|
||||
const remoteName = upstreamRef.slice(0, separatorIndex);
|
||||
const upstreamBranch = upstreamRef.slice(separatorIndex + 1);
|
||||
if (remoteName.length === 0 || upstreamBranch.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
upstreamRef,
|
||||
remoteName,
|
||||
upstreamBranch,
|
||||
};
|
||||
const remoteNames = yield* runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe(
|
||||
Effect.map(parseRemoteNames),
|
||||
Effect.catch(() => Effect.succeed<ReadonlyArray<string>>([])),
|
||||
);
|
||||
return (
|
||||
parseUpstreamRefWithRemoteNames(upstreamRef, remoteNames) ??
|
||||
parseUpstreamRefByFirstSeparator(upstreamRef)
|
||||
);
|
||||
});
|
||||
|
||||
const fetchUpstreamRef = (
|
||||
cwd: string,
|
||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
||||
const fetchRemoteForStatus = (
|
||||
gitCommonDir: string,
|
||||
remoteName: 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",
|
||||
cwd,
|
||||
["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
|
||||
"GitCore.fetchRemoteForStatus",
|
||||
fetchCwd,
|
||||
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", remoteName],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
|
||||
@@ -838,22 +934,28 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
).pipe(Effect.asVoid);
|
||||
};
|
||||
|
||||
const refreshStatusUpstreamCacheEntry = Effect.fn("refreshStatusUpstreamCacheEntry")(function* (
|
||||
cacheKey: StatusUpstreamRefreshCacheKey,
|
||||
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 refreshStatusRemoteCacheEntry = Effect.fn("refreshStatusRemoteCacheEntry")(function* (
|
||||
cacheKey: StatusRemoteRefreshCacheKey,
|
||||
) {
|
||||
yield* fetchUpstreamRefForStatus(cacheKey.cwd, {
|
||||
upstreamRef: cacheKey.upstreamRef,
|
||||
remoteName: cacheKey.remoteName,
|
||||
upstreamBranch: cacheKey.upstreamBranch,
|
||||
});
|
||||
yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName);
|
||||
return true as const;
|
||||
});
|
||||
|
||||
const statusUpstreamRefreshCache = yield* Cache.makeWith({
|
||||
const statusRemoteRefreshCache = yield* Cache.makeWith(refreshStatusRemoteCacheEntry, {
|
||||
capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
|
||||
lookup: refreshStatusUpstreamCacheEntry,
|
||||
// Keep successful refreshes warm; drop failures immediately so next request can retry.
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_UPSTREAM_REFRESH_INTERVAL : Duration.zero),
|
||||
// Keep successful refreshes warm and briefly back off failed refreshes to avoid retry storms.
|
||||
timeToLive: (exit) =>
|
||||
Exit.isSuccess(exit)
|
||||
? STATUS_UPSTREAM_REFRESH_INTERVAL
|
||||
: STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN,
|
||||
});
|
||||
|
||||
const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* (
|
||||
@@ -861,25 +963,16 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
) {
|
||||
const upstream = yield* resolveCurrentUpstream(cwd);
|
||||
if (!upstream) return;
|
||||
const gitCommonDir = yield* resolveGitCommonDir(cwd);
|
||||
yield* Cache.get(
|
||||
statusUpstreamRefreshCache,
|
||||
new StatusUpstreamRefreshCacheKey({
|
||||
cwd,
|
||||
upstreamRef: upstream.upstreamRef,
|
||||
statusRemoteRefreshCache,
|
||||
new StatusRemoteRefreshCacheKey({
|
||||
gitCommonDir,
|
||||
remoteName: upstream.remoteName,
|
||||
upstreamBranch: upstream.upstreamBranch,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const refreshCheckedOutBranchUpstream = Effect.fn("refreshCheckedOutBranchUpstream")(function* (
|
||||
cwd: string,
|
||||
) {
|
||||
const upstream = yield* resolveCurrentUpstream(cwd);
|
||||
if (!upstream) return;
|
||||
yield* fetchUpstreamRef(cwd, upstream);
|
||||
});
|
||||
|
||||
const resolveDefaultBranchName = (
|
||||
cwd: string,
|
||||
remoteName: string,
|
||||
@@ -919,7 +1012,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((stdout) => parseRemoteNames(stdout).toReversed()),
|
||||
Effect.map(parseRemoteNamesInGitOrder),
|
||||
);
|
||||
|
||||
const resolvePrimaryRemoteName = Effect.fn("resolvePrimaryRemoteName")(function* (cwd: string) {
|
||||
@@ -1103,17 +1196,56 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
return branchLastCommit;
|
||||
});
|
||||
|
||||
const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) {
|
||||
yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true }));
|
||||
const readStatusDetailsLocal = Effect.fn("readStatusDetailsLocal")(function* (cwd: string) {
|
||||
const statusResult = yield* executeGit(
|
||||
"GitCore.statusDetails.status",
|
||||
cwd,
|
||||
["status", "--porcelain=2", "--branch"],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(Effect.catchIf(isMissingGitCwdError, () => Effect.succeed(null)));
|
||||
|
||||
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all(
|
||||
[
|
||||
runGitStdout("GitCore.statusDetails.status", cwd, ["status", "--porcelain=2", "--branch"]),
|
||||
runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]),
|
||||
runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, ["diff", "--cached", "--numstat"]),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
if (statusResult === null) {
|
||||
return NON_REPOSITORY_STATUS_DETAILS;
|
||||
}
|
||||
|
||||
if (statusResult.code !== 0) {
|
||||
const stderr = statusResult.stderr.trim();
|
||||
return yield* createGitCommandError(
|
||||
"GitCore.statusDetails.status",
|
||||
cwd,
|
||||
["status", "--porcelain=2", "--branch"],
|
||||
stderr || "git status failed",
|
||||
);
|
||||
}
|
||||
|
||||
const [unstagedNumstatStdout, stagedNumstatStdout, defaultRefResult, hasOriginRemote] =
|
||||
yield* Effect.all(
|
||||
[
|
||||
runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]),
|
||||
runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, [
|
||||
"diff",
|
||||
"--cached",
|
||||
"--numstat",
|
||||
]),
|
||||
executeGit(
|
||||
"GitCore.statusDetails.defaultRef",
|
||||
cwd,
|
||||
["symbolic-ref", "refs/remotes/origin/HEAD"],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
originRemoteExists(cwd).pipe(Effect.catch(() => Effect.succeed(false))),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const statusStdout = statusResult.stdout;
|
||||
const defaultBranch =
|
||||
defaultRefResult.code === 0
|
||||
? defaultRefResult.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
|
||||
: null;
|
||||
|
||||
let branch: string | null = null;
|
||||
let upstreamRef: string | null = null;
|
||||
@@ -1181,6 +1313,12 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
files.sort((a, b) => a.path.localeCompare(b.path));
|
||||
|
||||
return {
|
||||
isRepo: true,
|
||||
hasOriginRemote,
|
||||
isDefaultBranch:
|
||||
branch !== null &&
|
||||
(branch === defaultBranch ||
|
||||
(defaultBranch === null && (branch === "main" || branch === "master"))),
|
||||
branch,
|
||||
upstreamRef,
|
||||
hasWorkingTreeChanges,
|
||||
@@ -1195,9 +1333,26 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
};
|
||||
});
|
||||
|
||||
const statusDetailsLocal: GitCoreShape["statusDetailsLocal"] = Effect.fn("statusDetailsLocal")(
|
||||
function* (cwd) {
|
||||
return yield* readStatusDetailsLocal(cwd);
|
||||
},
|
||||
);
|
||||
|
||||
const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) {
|
||||
yield* refreshStatusUpstreamIfStale(cwd).pipe(
|
||||
Effect.catchIf(isMissingGitCwdError, () => Effect.void),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
);
|
||||
return yield* readStatusDetailsLocal(cwd);
|
||||
});
|
||||
|
||||
const status: GitCoreShape["status"] = (input) =>
|
||||
statusDetails(input.cwd).pipe(
|
||||
Effect.map((details) => ({
|
||||
isRepo: details.isRepo,
|
||||
hasOriginRemote: details.hasOriginRemote,
|
||||
isDefaultBranch: details.isDefaultBranch,
|
||||
branch: details.branch,
|
||||
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
|
||||
workingTree: details.workingTree,
|
||||
@@ -1346,7 +1501,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
"push",
|
||||
"-u",
|
||||
publishRemoteName,
|
||||
branch,
|
||||
`HEAD:refs/heads/${branch}`,
|
||||
]);
|
||||
return {
|
||||
status: "pushed" as const,
|
||||
@@ -1490,7 +1645,14 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
executeGit(
|
||||
"GitCore.listWorkspaceFiles",
|
||||
cwd,
|
||||
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
||||
[
|
||||
...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
|
||||
"ls-files",
|
||||
"--cached",
|
||||
"--others",
|
||||
"--exclude-standard",
|
||||
"-z",
|
||||
],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
@@ -1508,7 +1670,14 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
createGitCommandError(
|
||||
"GitCore.listWorkspaceFiles",
|
||||
cwd,
|
||||
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
||||
[
|
||||
...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
|
||||
"ls-files",
|
||||
"--cached",
|
||||
"--others",
|
||||
"--exclude-standard",
|
||||
"-z",
|
||||
],
|
||||
result.stderr.trim().length > 0 ? result.stderr.trim() : "git ls-files failed",
|
||||
),
|
||||
),
|
||||
@@ -1528,7 +1697,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
const result = yield* executeGit(
|
||||
"GitCore.filterIgnoredPaths",
|
||||
cwd,
|
||||
["check-ignore", "--no-index", "-z", "--stdin"],
|
||||
[...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
|
||||
{
|
||||
stdin: `${chunk.join("\0")}\0`,
|
||||
allowNonZeroExit: true,
|
||||
@@ -1542,7 +1711,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
return yield* createGitCommandError(
|
||||
"GitCore.filterIgnoredPaths",
|
||||
cwd,
|
||||
["check-ignore", "--no-index", "-z", "--stdin"],
|
||||
[...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
|
||||
result.stderr.trim().length > 0 ? result.stderr.trim() : "git check-ignore failed",
|
||||
);
|
||||
}
|
||||
@@ -1571,12 +1740,28 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
timeoutMs: 10_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catchIf(isMissingGitCwdError, () =>
|
||||
Effect.succeed({
|
||||
code: 128,
|
||||
stdout: "",
|
||||
stderr: "fatal: not a git repository",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (localBranchResult.code !== 0) {
|
||||
const stderr = localBranchResult.stderr.trim();
|
||||
if (stderr.toLowerCase().includes("not a git repository")) {
|
||||
return { branches: [], isRepo: false, hasOriginRemote: false };
|
||||
return {
|
||||
branches: [],
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
nextCursor: null,
|
||||
totalCount: 0,
|
||||
};
|
||||
}
|
||||
return yield* createGitCommandError(
|
||||
"GitCore.listBranches",
|
||||
@@ -1740,9 +1925,22 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
})
|
||||
: [];
|
||||
|
||||
const branches = [...localBranches, ...remoteBranches];
|
||||
const branches = paginateBranches({
|
||||
branches: filterBranchesForListQuery(
|
||||
dedupeRemoteBranchesWithLocalMatches([...localBranches, ...remoteBranches]),
|
||||
input.query,
|
||||
),
|
||||
cursor: input.cursor,
|
||||
limit: input.limit,
|
||||
});
|
||||
|
||||
return { branches, isRepo: true, hasOriginRemote: remoteNames.includes("origin") };
|
||||
return {
|
||||
branches: [...branches.branches],
|
||||
isRepo: true,
|
||||
hasOriginRemote: remoteNames.includes("origin"),
|
||||
nextCursor: branches.nextCursor,
|
||||
totalCount: branches.totalCount,
|
||||
};
|
||||
});
|
||||
|
||||
const createWorktree: GitCoreShape["createWorktree"] = Effect.fn("createWorktree")(
|
||||
@@ -1834,7 +2032,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
"GitCore.removeWorktree",
|
||||
input.cwd,
|
||||
args,
|
||||
`${commandLabel(args)} failed (cwd: ${input.cwd}): ${error instanceof Error ? error.message : String(error)}`,
|
||||
`${commandLabel(args)} failed (cwd: ${input.cwd}): ${error.message}`,
|
||||
error,
|
||||
),
|
||||
),
|
||||
@@ -1861,12 +2059,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
return { branch: targetBranch };
|
||||
});
|
||||
|
||||
const createBranch: GitCoreShape["createBranch"] = (input) =>
|
||||
executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], {
|
||||
timeoutMs: 10_000,
|
||||
fallbackErrorMessage: "git branch create failed",
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const checkoutBranch: GitCoreShape["checkoutBranch"] = Effect.fn("checkoutBranch")(
|
||||
function* (input) {
|
||||
const [localInputExists, remoteExists] = yield* Effect.all(
|
||||
@@ -1940,14 +2132,27 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
fallbackErrorMessage: "git checkout failed",
|
||||
});
|
||||
|
||||
// Refresh upstream refs in the background so checkout remains responsive.
|
||||
yield* refreshCheckedOutBranchUpstream(input.cwd).pipe(
|
||||
Effect.ignoreCause({ log: true }),
|
||||
Effect.forkDetach({ startImmediately: true }),
|
||||
);
|
||||
const branch = yield* runGitStdout("GitCore.checkoutBranch.currentBranch", input.cwd, [
|
||||
"branch",
|
||||
"--show-current",
|
||||
]).pipe(Effect.map((stdout) => stdout.trim() || null));
|
||||
|
||||
return { branch };
|
||||
},
|
||||
);
|
||||
|
||||
const createBranch: GitCoreShape["createBranch"] = Effect.fn("createBranch")(function* (input) {
|
||||
yield* executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], {
|
||||
timeoutMs: 10_000,
|
||||
fallbackErrorMessage: "git branch create failed",
|
||||
});
|
||||
if (input.checkout) {
|
||||
yield* checkoutBranch({ cwd: input.cwd, branch: input.branch });
|
||||
}
|
||||
|
||||
return { branch: input.branch };
|
||||
});
|
||||
|
||||
const initRepo: GitCoreShape["initRepo"] = (input) =>
|
||||
executeGit("GitCore.initRepo", input.cwd, ["init"], {
|
||||
timeoutMs: 10_000,
|
||||
@@ -1973,6 +2178,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
execute,
|
||||
status,
|
||||
statusDetails,
|
||||
statusDetailsLocal,
|
||||
prepareCommitContext,
|
||||
commit,
|
||||
pushCurrentBranch,
|
||||
|
||||
@@ -76,6 +76,105 @@ layer("GitHubCliLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("trims pull request fields decoded from gh json", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
number: 42,
|
||||
title: " Add PR thread creation \n",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/42 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: "\tfeature/pr-threads\t",
|
||||
state: "OPEN",
|
||||
mergedAt: null,
|
||||
isCrossRepository: true,
|
||||
headRepository: {
|
||||
nameWithOwner: " octocat/codething-mvp ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " octocat ",
|
||||
},
|
||||
}),
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli;
|
||||
return yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
number: 42,
|
||||
title: "Add PR thread creation",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-threads",
|
||||
state: "open",
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "octocat/codething-mvp",
|
||||
headRepositoryOwnerLogin: "octocat",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips invalid entries when parsing pr lists", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify([
|
||||
{
|
||||
number: 0,
|
||||
title: "invalid",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/0",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/invalid",
|
||||
},
|
||||
{
|
||||
number: 43,
|
||||
title: " Valid PR ",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/43 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: " feature/pr-list ",
|
||||
headRepository: {
|
||||
nameWithOwner: " ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " ",
|
||||
},
|
||||
},
|
||||
]),
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli;
|
||||
return yield* gh.listOpenPullRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/pr-list",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, [
|
||||
{
|
||||
number: 43,
|
||||
title: "Valid PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/43",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-list",
|
||||
state: "open",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads repository clone URLs", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Result, Schema, SchemaIssue } from "effect";
|
||||
import { TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
|
||||
import { runProcess } from "../../processRunner";
|
||||
import { GitHubCliError } from "@t3tools/contracts";
|
||||
@@ -7,8 +7,12 @@ import {
|
||||
GitHubCli,
|
||||
type GitHubRepositoryCloneUrls,
|
||||
type GitHubCliShape,
|
||||
type GitHubPullRequestSummary,
|
||||
} from "../Services/GitHubCli.ts";
|
||||
import {
|
||||
decodeGitHubPullRequestJson,
|
||||
decodeGitHubPullRequestListJson,
|
||||
formatGitHubJsonDecodeError,
|
||||
} from "../githubPullRequests.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
@@ -63,76 +67,12 @@ function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown
|
||||
});
|
||||
}
|
||||
|
||||
function normalizePullRequestState(input: {
|
||||
state?: string | null | undefined;
|
||||
mergedAt?: string | null | undefined;
|
||||
}): "open" | "closed" | "merged" {
|
||||
const mergedAt = input.mergedAt;
|
||||
const state = input.state;
|
||||
if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
|
||||
return "merged";
|
||||
}
|
||||
if (state === "CLOSED") {
|
||||
return "closed";
|
||||
}
|
||||
return "open";
|
||||
}
|
||||
|
||||
const RawGitHubPullRequestSchema = Schema.Struct({
|
||||
number: PositiveInt,
|
||||
title: TrimmedNonEmptyString,
|
||||
url: TrimmedNonEmptyString,
|
||||
baseRefName: TrimmedNonEmptyString,
|
||||
headRefName: TrimmedNonEmptyString,
|
||||
state: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
isCrossRepository: Schema.optional(Schema.Boolean),
|
||||
headRepository: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
nameWithOwner: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
headRepositoryOwner: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
login: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
|
||||
nameWithOwner: TrimmedNonEmptyString,
|
||||
url: TrimmedNonEmptyString,
|
||||
sshUrl: TrimmedNonEmptyString,
|
||||
});
|
||||
|
||||
function normalizePullRequestSummary(
|
||||
raw: Schema.Schema.Type<typeof RawGitHubPullRequestSchema>,
|
||||
): GitHubPullRequestSummary {
|
||||
const headRepositoryNameWithOwner = raw.headRepository?.nameWithOwner ?? null;
|
||||
const headRepositoryOwnerLogin =
|
||||
raw.headRepositoryOwner?.login ??
|
||||
(typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/")
|
||||
? (headRepositoryNameWithOwner.split("/")[0] ?? null)
|
||||
: null);
|
||||
return {
|
||||
number: raw.number,
|
||||
title: raw.title,
|
||||
url: raw.url,
|
||||
baseRefName: raw.baseRefName,
|
||||
headRefName: raw.headRefName,
|
||||
state: normalizePullRequestState(raw),
|
||||
...(typeof raw.isCrossRepository === "boolean"
|
||||
? { isCrossRepository: raw.isCrossRepository }
|
||||
: {}),
|
||||
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
|
||||
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeRepositoryCloneUrls(
|
||||
raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
|
||||
): GitHubRepositoryCloneUrls {
|
||||
@@ -154,7 +94,7 @@ function decodeGitHubJson<S extends Schema.Top>(
|
||||
(error) =>
|
||||
new GitHubCliError({
|
||||
operation,
|
||||
detail: error instanceof Error ? `${invalidDetail}: ${error.message}` : invalidDetail,
|
||||
detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
@@ -187,21 +127,31 @@ const makeGitHubCli = Effect.sync(() => {
|
||||
"--limit",
|
||||
String(input.limit ?? 1),
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName",
|
||||
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
||||
],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
raw.length === 0
|
||||
? Effect.succeed([])
|
||||
: decodeGitHubJson(
|
||||
raw,
|
||||
Schema.Array(RawGitHubPullRequestSchema),
|
||||
"listOpenPullRequests",
|
||||
"GitHub CLI returned invalid PR list JSON.",
|
||||
: Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitHubCliError({
|
||||
operation: "listOpenPullRequests",
|
||||
detail: `GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed(
|
||||
decoded.success.map(({ updatedAt: _updatedAt, ...summary }) => summary),
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.map((pullRequests) => pullRequests.map(normalizePullRequestSummary)),
|
||||
),
|
||||
getPullRequest: (input) =>
|
||||
execute({
|
||||
@@ -216,14 +166,24 @@ const makeGitHubCli = Effect.sync(() => {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitHubJson(
|
||||
raw,
|
||||
RawGitHubPullRequestSchema,
|
||||
"getPullRequest",
|
||||
"GitHub CLI returned invalid pull request JSON.",
|
||||
Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitHubCliError({
|
||||
operation: "getPullRequest",
|
||||
detail: `GitHub CLI returned invalid pull request JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed(
|
||||
(({ updatedAt: _updatedAt, ...summary }) => summary)(decoded.success),
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.map(normalizePullRequestSummary),
|
||||
),
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
execute({
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,312 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Deferred, Effect, Exit, Layer, Option, Scope, Stream } from "effect";
|
||||
import type {
|
||||
GitStatusLocalResult,
|
||||
GitStatusRemoteResult,
|
||||
GitStatusResult,
|
||||
GitStatusStreamEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe } from "vitest";
|
||||
|
||||
import { GitStatusBroadcaster } from "../Services/GitStatusBroadcaster.ts";
|
||||
import { GitStatusBroadcasterLive } from "./GitStatusBroadcaster.ts";
|
||||
import { type GitManagerShape, GitManager } from "../Services/GitManager.ts";
|
||||
|
||||
const baseLocalStatus: GitStatusLocalResult = {
|
||||
isRepo: true,
|
||||
hostingProvider: {
|
||||
kind: "github",
|
||||
name: "GitHub",
|
||||
baseUrl: "https://github.com",
|
||||
},
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "feature/status-broadcast",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
};
|
||||
|
||||
const baseRemoteStatus: GitStatusRemoteResult = {
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
};
|
||||
|
||||
const baseStatus: GitStatusResult = {
|
||||
...baseLocalStatus,
|
||||
...baseRemoteStatus,
|
||||
};
|
||||
|
||||
function makeTestLayer(state: {
|
||||
currentLocalStatus: GitStatusLocalResult;
|
||||
currentRemoteStatus: GitStatusRemoteResult | null;
|
||||
localStatusCalls: number;
|
||||
remoteStatusCalls: number;
|
||||
localInvalidationCalls: number;
|
||||
remoteInvalidationCalls: number;
|
||||
}) {
|
||||
const gitManager: GitManagerShape = {
|
||||
localStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localStatusCalls += 1;
|
||||
return state.currentLocalStatus;
|
||||
}),
|
||||
remoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteStatusCalls += 1;
|
||||
return state.currentRemoteStatus;
|
||||
}),
|
||||
status: () => Effect.die("status should not be called in this test"),
|
||||
invalidateLocalStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateRemoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateStatus: () => Effect.die("invalidateStatus should not be called in this test"),
|
||||
resolvePullRequest: () => Effect.die("resolvePullRequest should not be called in this test"),
|
||||
preparePullRequestThread: () =>
|
||||
Effect.die("preparePullRequestThread should not be called in this test"),
|
||||
runStackedAction: () => Effect.die("runStackedAction should not be called in this test"),
|
||||
};
|
||||
|
||||
return GitStatusBroadcasterLive.pipe(Layer.provide(Layer.succeed(GitManager, gitManager)));
|
||||
}
|
||||
|
||||
describe("GitStatusBroadcasterLive", () => {
|
||||
it.effect("reuses the cached git status across repeated reads", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: baseRemoteStatus,
|
||||
localStatusCalls: 0,
|
||||
remoteStatusCalls: 0,
|
||||
localInvalidationCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* GitStatusBroadcaster;
|
||||
|
||||
const first = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
const second = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
|
||||
assert.deepStrictEqual(first, baseStatus);
|
||||
assert.deepStrictEqual(second, baseStatus);
|
||||
assert.equal(state.localStatusCalls, 1);
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
assert.equal(state.localInvalidationCalls, 0);
|
||||
assert.equal(state.remoteInvalidationCalls, 0);
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it.effect("refreshes the cached snapshot after explicit invalidation", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: baseRemoteStatus,
|
||||
localStatusCalls: 0,
|
||||
remoteStatusCalls: 0,
|
||||
localInvalidationCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* GitStatusBroadcaster;
|
||||
const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
|
||||
state.currentLocalStatus = {
|
||||
...baseLocalStatus,
|
||||
branch: "feature/updated-status",
|
||||
};
|
||||
state.currentRemoteStatus = {
|
||||
...baseRemoteStatus,
|
||||
aheadCount: 2,
|
||||
};
|
||||
const refreshed = yield* broadcaster.refreshStatus("/repo");
|
||||
const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
|
||||
assert.deepStrictEqual(initial, baseStatus);
|
||||
assert.deepStrictEqual(refreshed, {
|
||||
...state.currentLocalStatus,
|
||||
...state.currentRemoteStatus,
|
||||
});
|
||||
assert.deepStrictEqual(cached, {
|
||||
...state.currentLocalStatus,
|
||||
...state.currentRemoteStatus,
|
||||
});
|
||||
assert.equal(state.localStatusCalls, 2);
|
||||
assert.equal(state.remoteStatusCalls, 2);
|
||||
assert.equal(state.localInvalidationCalls, 1);
|
||||
assert.equal(state.remoteInvalidationCalls, 1);
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it.effect("refreshes only the cached local snapshot when requested", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: baseRemoteStatus,
|
||||
localStatusCalls: 0,
|
||||
remoteStatusCalls: 0,
|
||||
localInvalidationCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* GitStatusBroadcaster;
|
||||
const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
|
||||
state.currentLocalStatus = {
|
||||
...baseLocalStatus,
|
||||
branch: "feature/local-only-refresh",
|
||||
hasWorkingTreeChanges: true,
|
||||
};
|
||||
|
||||
const refreshedLocal = yield* broadcaster.refreshLocalStatus("/repo");
|
||||
const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
|
||||
assert.deepStrictEqual(initial, baseStatus);
|
||||
assert.deepStrictEqual(refreshedLocal, state.currentLocalStatus);
|
||||
assert.deepStrictEqual(cached, {
|
||||
...state.currentLocalStatus,
|
||||
...baseRemoteStatus,
|
||||
});
|
||||
assert.equal(state.localStatusCalls, 2);
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
assert.equal(state.localInvalidationCalls, 1);
|
||||
assert.equal(state.remoteInvalidationCalls, 0);
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it.effect("streams a local snapshot first and remote updates later", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: baseRemoteStatus,
|
||||
localStatusCalls: 0,
|
||||
remoteStatusCalls: 0,
|
||||
localInvalidationCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* GitStatusBroadcaster;
|
||||
const snapshotDeferred = yield* Deferred.make<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));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,311 @@
|
||||
import { realpathSync } from "node:fs";
|
||||
|
||||
import {
|
||||
Duration,
|
||||
Effect,
|
||||
Exit,
|
||||
Fiber,
|
||||
Layer,
|
||||
PubSub,
|
||||
Ref,
|
||||
Scope,
|
||||
Stream,
|
||||
SynchronizedRef,
|
||||
} from "effect";
|
||||
import type {
|
||||
GitStatusInput,
|
||||
GitStatusLocalResult,
|
||||
GitStatusRemoteResult,
|
||||
GitStatusStreamEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { mergeGitStatusParts } from "@t3tools/shared/git";
|
||||
|
||||
import {
|
||||
GitStatusBroadcaster,
|
||||
type GitStatusBroadcasterShape,
|
||||
} from "../Services/GitStatusBroadcaster.ts";
|
||||
import { GitManager } from "../Services/GitManager.ts";
|
||||
|
||||
const GIT_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
|
||||
|
||||
interface GitStatusChange {
|
||||
readonly cwd: string;
|
||||
readonly event: GitStatusStreamEvent;
|
||||
}
|
||||
|
||||
interface CachedValue<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;
|
||||
}),
|
||||
);
|
||||
@@ -9,7 +9,7 @@
|
||||
*
|
||||
* @module RoutingTextGeneration
|
||||
*/
|
||||
import { Effect, Layer, ServiceMap } from "effect";
|
||||
import { Effect, Layer, Context } from "effect";
|
||||
|
||||
import {
|
||||
TextGeneration,
|
||||
@@ -23,11 +23,11 @@ import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
|
||||
// Internal service tags so both concrete layers can coexist.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class CodexTextGen extends ServiceMap.Service<CodexTextGen, TextGenerationShape>()(
|
||||
class CodexTextGen extends Context.Service<CodexTextGen, TextGenerationShape>()(
|
||||
"t3/git/Layers/RoutingTextGeneration/CodexTextGen",
|
||||
) {}
|
||||
|
||||
class ClaudeTextGen extends ServiceMap.Service<ClaudeTextGen, TextGenerationShape>()(
|
||||
class ClaudeTextGen extends Context.Service<ClaudeTextGen, TextGenerationShape>()(
|
||||
"t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
|
||||
) {}
|
||||
|
||||
|
||||
@@ -6,11 +6,13 @@
|
||||
*
|
||||
* @module GitCore
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect, Scope } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type {
|
||||
GitCheckoutInput,
|
||||
GitCheckoutResult,
|
||||
GitCreateBranchInput,
|
||||
GitCreateBranchResult,
|
||||
GitCreateWorktreeInput,
|
||||
GitCreateWorktreeResult,
|
||||
GitInitInput,
|
||||
@@ -156,6 +158,11 @@ 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.
|
||||
*/
|
||||
@@ -278,14 +285,16 @@ export interface GitCoreShape {
|
||||
/**
|
||||
* Create a local branch.
|
||||
*/
|
||||
readonly createBranch: (input: GitCreateBranchInput) => Effect.Effect<void, GitCommandError>;
|
||||
readonly createBranch: (
|
||||
input: GitCreateBranchInput,
|
||||
) => Effect.Effect<GitCreateBranchResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Checkout an existing branch and refresh its upstream metadata in background.
|
||||
*/
|
||||
readonly checkoutBranch: (
|
||||
input: GitCheckoutInput,
|
||||
) => Effect.Effect<void, GitCommandError, Scope.Scope>;
|
||||
) => Effect.Effect<GitCheckoutResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Initialize a repository in the provided directory.
|
||||
@@ -301,6 +310,4 @@ export interface GitCoreShape {
|
||||
/**
|
||||
* GitCore - Service tag for low-level Git repository operations.
|
||||
*/
|
||||
export class GitCore extends ServiceMap.Service<GitCore, GitCoreShape>()(
|
||||
"t3/git/Services/GitCore",
|
||||
) {}
|
||||
export class GitCore extends Context.Service<GitCore, GitCoreShape>()("t3/git/Services/GitCore") {}
|
||||
@@ -5,7 +5,7 @@
|
||||
*
|
||||
* @module GitHubCli
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProcessRunResult } from "../../processRunner";
|
||||
@@ -98,6 +98,6 @@ export interface GitHubCliShape {
|
||||
/**
|
||||
* GitHubCli - Service tag for GitHub CLI process execution.
|
||||
*/
|
||||
export class GitHubCli extends ServiceMap.Service<GitHubCli, GitHubCliShape>()(
|
||||
export class GitHubCli extends Context.Service<GitHubCli, GitHubCliShape>()(
|
||||
"t3/git/Services/GitHubCli",
|
||||
) {}
|
||||
@@ -14,10 +14,12 @@ import {
|
||||
GitResolvePullRequestResult,
|
||||
GitRunStackedActionInput,
|
||||
GitRunStackedActionResult,
|
||||
GitStatusLocalResult,
|
||||
GitStatusRemoteResult,
|
||||
GitStatusInput,
|
||||
GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||
|
||||
@@ -41,6 +43,35 @@ 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.
|
||||
*/
|
||||
@@ -56,7 +87,7 @@ export interface GitManagerShape {
|
||||
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
|
||||
|
||||
/**
|
||||
* Run a stacked Git action (`commit`, `commit_push`, `commit_push_pr`).
|
||||
* Run a Git action (`commit`, `push`, `create_pr`, `commit_push`, `commit_push_pr`).
|
||||
* When `featureBranch` is set, creates and checks out a feature branch first.
|
||||
*/
|
||||
readonly runStackedAction: (
|
||||
@@ -68,6 +99,6 @@ export interface GitManagerShape {
|
||||
/**
|
||||
* GitManager - Service tag for stacked Git workflow orchestration.
|
||||
*/
|
||||
export class GitManager extends ServiceMap.Service<GitManager, GitManagerShape>()(
|
||||
export class GitManager extends Context.Service<GitManager, GitManagerShape>()(
|
||||
"t3/git/Services/GitManager",
|
||||
) {}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { Context } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
import type {
|
||||
GitManagerServiceError,
|
||||
GitStatusInput,
|
||||
GitStatusLocalResult,
|
||||
GitStatusResult,
|
||||
GitStatusStreamEvent,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export interface GitStatusBroadcasterShape {
|
||||
readonly getStatus: (
|
||||
input: GitStatusInput,
|
||||
) => Effect.Effect<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 Context.Service<
|
||||
GitStatusBroadcaster,
|
||||
GitStatusBroadcasterShape
|
||||
>()("t3/git/Services/GitStatusBroadcaster") {}
|
||||
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* @module TextGeneration
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
|
||||
|
||||
@@ -118,6 +118,6 @@ export interface TextGenerationShape {
|
||||
/**
|
||||
* TextGeneration - Service tag for commit and PR text generation.
|
||||
*/
|
||||
export class TextGeneration extends ServiceMap.Service<TextGeneration, TextGenerationShape>()(
|
||||
export class TextGeneration extends Context.Service<TextGeneration, TextGenerationShape>()(
|
||||
"t3/git/Services/TextGeneration",
|
||||
) {}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { Cause, Exit, Result, Schema } from "effect";
|
||||
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
|
||||
|
||||
export interface NormalizedGitHubPullRequestRecord {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
readonly url: string;
|
||||
readonly baseRefName: string;
|
||||
readonly headRefName: string;
|
||||
readonly state: "open" | "closed" | "merged";
|
||||
readonly updatedAt: string | null;
|
||||
readonly isCrossRepository?: boolean;
|
||||
readonly headRepositoryNameWithOwner?: string | null;
|
||||
readonly headRepositoryOwnerLogin?: string | null;
|
||||
}
|
||||
|
||||
const GitHubPullRequestSchema = Schema.Struct({
|
||||
number: PositiveInt,
|
||||
title: TrimmedNonEmptyString,
|
||||
url: TrimmedNonEmptyString,
|
||||
baseRefName: TrimmedNonEmptyString,
|
||||
headRefName: TrimmedNonEmptyString,
|
||||
state: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
updatedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
isCrossRepository: Schema.optional(Schema.Boolean),
|
||||
headRepository: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
nameWithOwner: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
headRepositoryOwner: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
login: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
function trimOptionalString(value: string | null | undefined): string | null {
|
||||
const trimmed = value?.trim() ?? "";
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function normalizeGitHubPullRequestState(input: {
|
||||
state?: string | null | undefined;
|
||||
mergedAt?: string | null | undefined;
|
||||
}): "open" | "closed" | "merged" {
|
||||
const normalizedState = input.state?.trim().toUpperCase();
|
||||
if (
|
||||
(typeof input.mergedAt === "string" && input.mergedAt.trim().length > 0) ||
|
||||
normalizedState === "MERGED"
|
||||
) {
|
||||
return "merged";
|
||||
}
|
||||
if (normalizedState === "CLOSED") {
|
||||
return "closed";
|
||||
}
|
||||
return "open";
|
||||
}
|
||||
|
||||
function normalizeGitHubPullRequestRecord(
|
||||
raw: Schema.Schema.Type<typeof GitHubPullRequestSchema>,
|
||||
): NormalizedGitHubPullRequestRecord {
|
||||
const headRepositoryNameWithOwner = trimOptionalString(raw.headRepository?.nameWithOwner);
|
||||
const headRepositoryOwnerLogin =
|
||||
trimOptionalString(raw.headRepositoryOwner?.login) ??
|
||||
(typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/")
|
||||
? (headRepositoryNameWithOwner.split("/")[0] ?? null)
|
||||
: null);
|
||||
|
||||
return {
|
||||
number: raw.number,
|
||||
title: raw.title,
|
||||
url: raw.url,
|
||||
baseRefName: raw.baseRefName,
|
||||
headRefName: raw.headRefName,
|
||||
state: normalizeGitHubPullRequestState(raw),
|
||||
updatedAt:
|
||||
typeof raw.updatedAt === "string" && raw.updatedAt.trim().length > 0 ? raw.updatedAt : null,
|
||||
...(typeof raw.isCrossRepository === "boolean"
|
||||
? { isCrossRepository: raw.isCrossRepository }
|
||||
: {}),
|
||||
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
|
||||
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
const decodeGitHubPullRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));
|
||||
const decodeGitHubPullRequest = decodeJsonResult(GitHubPullRequestSchema);
|
||||
const decodeGitHubPullRequestEntry = Schema.decodeUnknownExit(GitHubPullRequestSchema);
|
||||
|
||||
export const formatGitHubJsonDecodeError = formatSchemaError;
|
||||
|
||||
export function decodeGitHubPullRequestListJson(
|
||||
raw: string,
|
||||
): Result.Result<
|
||||
ReadonlyArray<NormalizedGitHubPullRequestRecord>,
|
||||
Cause.Cause<Schema.SchemaError>
|
||||
> {
|
||||
const result = decodeGitHubPullRequestList(raw);
|
||||
if (Result.isSuccess(result)) {
|
||||
const pullRequests: NormalizedGitHubPullRequestRecord[] = [];
|
||||
for (const entry of result.success) {
|
||||
const decodedEntry = decodeGitHubPullRequestEntry(entry);
|
||||
if (Exit.isFailure(decodedEntry)) {
|
||||
continue;
|
||||
}
|
||||
pullRequests.push(normalizeGitHubPullRequestRecord(decodedEntry.value));
|
||||
}
|
||||
return Result.succeed(pullRequests);
|
||||
}
|
||||
return Result.fail(result.failure);
|
||||
}
|
||||
|
||||
export function decodeGitHubPullRequestJson(
|
||||
raw: string,
|
||||
): Result.Result<NormalizedGitHubPullRequestRecord, Cause.Cause<Schema.SchemaError>> {
|
||||
const result = decodeGitHubPullRequest(raw);
|
||||
if (Result.isSuccess(result)) {
|
||||
return Result.succeed(normalizeGitHubPullRequestRecord(result.success));
|
||||
}
|
||||
return Result.fail(result.failure);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { isLoopbackHostname, resolveDevRedirectUrl } from "./http.ts";
|
||||
|
||||
describe("http dev routing", () => {
|
||||
it("treats localhost and loopback addresses as local", () => {
|
||||
expect(isLoopbackHostname("127.0.0.1")).toBe(true);
|
||||
expect(isLoopbackHostname("localhost")).toBe(true);
|
||||
expect(isLoopbackHostname("::1")).toBe(true);
|
||||
expect(isLoopbackHostname("[::1]")).toBe(true);
|
||||
});
|
||||
|
||||
it("does not treat LAN addresses as local", () => {
|
||||
expect(isLoopbackHostname("192.168.86.35")).toBe(false);
|
||||
expect(isLoopbackHostname("10.0.0.24")).toBe(false);
|
||||
expect(isLoopbackHostname("example.local")).toBe(false);
|
||||
});
|
||||
|
||||
it("preserves path and query when redirecting to the dev server", () => {
|
||||
const devUrl = new URL("http://127.0.0.1:5173/");
|
||||
const requestUrl = new URL("http://127.0.0.1:3774/pair?token=test-token");
|
||||
|
||||
expect(resolveDevRedirectUrl(devUrl, requestUrl)).toBe(
|
||||
"http://127.0.0.1:5173/pair?token=test-token",
|
||||
);
|
||||
});
|
||||
});
|
||||
+123
-9
@@ -1,6 +1,15 @@
|
||||
import Mime from "@effect/platform-node/Mime";
|
||||
import { Effect, FileSystem, Option, Path } from "effect";
|
||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
import { Data, Effect, FileSystem, Option, Path } from "effect";
|
||||
import { cast } from "effect/Function";
|
||||
import {
|
||||
HttpBody,
|
||||
HttpClient,
|
||||
HttpClientResponse,
|
||||
HttpRouter,
|
||||
HttpServerResponse,
|
||||
HttpServerRequest,
|
||||
} from "effect/unstable/http";
|
||||
import { OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
import {
|
||||
ATTACHMENTS_ROUTE_PREFIX,
|
||||
@@ -8,16 +17,117 @@ import {
|
||||
resolveAttachmentRelativePath,
|
||||
} from "./attachmentPaths";
|
||||
import { resolveAttachmentPathById } from "./attachmentStore";
|
||||
import { ServerConfig } from "./config";
|
||||
import { resolveStaticDir, ServerConfig } from "./config";
|
||||
import { decodeOtlpTraceRecords } from "./observability/TraceRecord.ts";
|
||||
import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts";
|
||||
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver";
|
||||
import { ServerAuth } from "./auth/Services/ServerAuth.ts";
|
||||
import { respondToAuthError } from "./auth/http.ts";
|
||||
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
|
||||
|
||||
const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600";
|
||||
const FALLBACK_PROJECT_FAVICON_SVG = `<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)) {
|
||||
@@ -66,13 +176,14 @@ 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)) {
|
||||
@@ -106,7 +217,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(
|
||||
@@ -120,11 +231,14 @@ export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
}
|
||||
|
||||
const config = yield* ServerConfig;
|
||||
if (config.devUrl) {
|
||||
return HttpServerResponse.redirect(config.devUrl.href, { status: 302 });
|
||||
if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
|
||||
return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
|
||||
status: 302,
|
||||
});
|
||||
}
|
||||
|
||||
if (!config.staticDir) {
|
||||
const staticDir = config.staticDir ?? (config.devUrl ? yield* resolveStaticDir() : undefined);
|
||||
if (!staticDir) {
|
||||
return HttpServerResponse.text("No static directory configured and no dev URL set.", {
|
||||
status: 503,
|
||||
});
|
||||
@@ -132,7 +246,7 @@ export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const staticRoot = path.resolve(config.staticDir);
|
||||
const staticRoot = path.resolve(staticDir);
|
||||
const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
|
||||
const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
|
||||
const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
|
||||
|
||||
Loaded 100 of 526 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user