Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
243e8a44a9 | ||
|
|
77a64493bb | ||
|
|
c3af56e177 | ||
|
|
22cf222e20 | ||
|
|
d2c62488b2 | ||
|
|
5a57ada95b |
No files matched your search
@@ -1,22 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "T3 Code Dev",
|
|
||||||
"image": "debian:bookworm",
|
|
||||||
"features": {
|
|
||||||
"ghcr.io/devcontainers-extra/features/bun:1": {},
|
|
||||||
"ghcr.io/devcontainers/features/node:1": {
|
|
||||||
"version": "24",
|
|
||||||
"nodeGypDependencies": true
|
|
||||||
},
|
|
||||||
"ghcr.io/devcontainers/features/python:1": {
|
|
||||||
"version": "3.12"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"postCreateCommand": {
|
|
||||||
"bun-install": "bun install --backend=copyfile --frozen-lockfile"
|
|
||||||
},
|
|
||||||
"customizations": {
|
|
||||||
"vscode": {
|
|
||||||
"extensions": ["oxc.oxc-vscode"]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,302 +0,0 @@
|
|||||||
# Remote Architecture
|
|
||||||
|
|
||||||
This document describes the target architecture for first-class remote environments in T3 Code.
|
|
||||||
|
|
||||||
It is intentionally architecture-first. It does not define a complete implementation plan or user-facing rollout checklist. The goal is to establish the core model so remote support can be added without another broad rewrite.
|
|
||||||
|
|
||||||
## Goals
|
|
||||||
|
|
||||||
- Treat remote environments as first-class product primitives, not special cases.
|
|
||||||
- Support multiple ways to reach the same environment.
|
|
||||||
- Keep the T3 server as the execution boundary.
|
|
||||||
- Let desktop, mobile, and web all share the same conceptual model.
|
|
||||||
- Avoid introducing a local control plane unless product pressure proves it is necessary.
|
|
||||||
|
|
||||||
## Non-goals
|
|
||||||
|
|
||||||
- Replacing the existing WebSocket server boundary with a custom transport protocol.
|
|
||||||
- Making SSH the only remote story.
|
|
||||||
- Syncing provider auth across machines.
|
|
||||||
- Shipping every access method in the first iteration.
|
|
||||||
|
|
||||||
## High-level architecture
|
|
||||||
|
|
||||||
T3 already has a clean runtime boundary: the client talks to a T3 server over HTTP/WebSocket, and the server owns orchestration, providers, terminals, git, and filesystem operations.
|
|
||||||
|
|
||||||
Remote support should preserve that boundary.
|
|
||||||
|
|
||||||
```text
|
|
||||||
┌──────────────────────────────────────────────┐
|
|
||||||
│ Client (desktop / mobile / web) │
|
|
||||||
│ │
|
|
||||||
│ - known environments │
|
|
||||||
│ - connection manager │
|
|
||||||
│ - environment-aware routing │
|
|
||||||
└───────────────┬──────────────────────────────┘
|
|
||||||
│
|
|
||||||
│ resolves one access endpoint
|
|
||||||
│
|
|
||||||
┌───────────────▼──────────────────────────────┐
|
|
||||||
│ Access method │
|
|
||||||
│ │
|
|
||||||
│ - direct ws / wss │
|
|
||||||
│ - tunneled ws / wss │
|
|
||||||
│ - desktop-managed ssh bootstrap + forward │
|
|
||||||
└───────────────┬──────────────────────────────┘
|
|
||||||
│
|
|
||||||
│ connects to one T3 server
|
|
||||||
│
|
|
||||||
┌───────────────▼──────────────────────────────┐
|
|
||||||
│ Execution environment = one T3 server │
|
|
||||||
│ │
|
|
||||||
│ - environment identity │
|
|
||||||
│ - provider state │
|
|
||||||
│ - projects / threads / terminals │
|
|
||||||
│ - git / filesystem / process runtime │
|
|
||||||
└──────────────────────────────────────────────┘
|
|
||||||
```
|
|
||||||
|
|
||||||
The important decision is that remoteness is expressed at the environment connection layer, not by splitting the T3 runtime itself.
|
|
||||||
|
|
||||||
## Domain model
|
|
||||||
|
|
||||||
### ExecutionEnvironment
|
|
||||||
|
|
||||||
An `ExecutionEnvironment` is one running T3 server instance.
|
|
||||||
|
|
||||||
It is the unit that owns:
|
|
||||||
|
|
||||||
- provider availability and auth state
|
|
||||||
- model availability
|
|
||||||
- projects and threads
|
|
||||||
- terminal processes
|
|
||||||
- filesystem access
|
|
||||||
- git operations
|
|
||||||
- server settings
|
|
||||||
|
|
||||||
It is identified by a stable `environmentId`.
|
|
||||||
|
|
||||||
This is the shared cross-client primitive. Desktop, mobile, and web should all reason about the same concept here.
|
|
||||||
|
|
||||||
### KnownEnvironment
|
|
||||||
|
|
||||||
A `KnownEnvironment` is a client-side saved entry for an environment the client knows how to reach.
|
|
||||||
|
|
||||||
It is not server-authored. It is local to a device or client profile.
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
|
|
||||||
- a saved LAN URL
|
|
||||||
- a saved public `wss://` endpoint
|
|
||||||
- a desktop-managed SSH host entry
|
|
||||||
- a saved tunneled environment
|
|
||||||
|
|
||||||
A known environment may or may not know the target `environmentId` before first successful connect.
|
|
||||||
|
|
||||||
### AccessEndpoint
|
|
||||||
|
|
||||||
An `AccessEndpoint` is one concrete way to reach a known environment.
|
|
||||||
|
|
||||||
This is the key abstraction that keeps SSH from taking over the model.
|
|
||||||
|
|
||||||
A single environment may have many endpoints:
|
|
||||||
|
|
||||||
- `wss://t3.example.com`
|
|
||||||
- `ws://10.0.0.25:3773`
|
|
||||||
- a tunneled relay URL
|
|
||||||
- a desktop-managed SSH tunnel that resolves to a local forwarded WebSocket URL
|
|
||||||
|
|
||||||
The environment stays the same. Only the access path changes.
|
|
||||||
|
|
||||||
### RepositoryIdentity
|
|
||||||
|
|
||||||
`RepositoryIdentity` remains a best-effort logical repo grouping mechanism across environments.
|
|
||||||
|
|
||||||
It is not used for routing. It is only used for UI grouping and correlation between local and remote clones of the same repository.
|
|
||||||
|
|
||||||
### Workspace / Project
|
|
||||||
|
|
||||||
The current `Project` model remains environment-local.
|
|
||||||
|
|
||||||
That means:
|
|
||||||
|
|
||||||
- a local clone and a remote clone are different projects
|
|
||||||
- they may share a `RepositoryIdentity`
|
|
||||||
- threads still bind to one project in one environment
|
|
||||||
|
|
||||||
## Access methods
|
|
||||||
|
|
||||||
Access methods answer one question:
|
|
||||||
|
|
||||||
How does the client speak WebSocket to a T3 server?
|
|
||||||
|
|
||||||
They do not answer:
|
|
||||||
|
|
||||||
- how the server got started
|
|
||||||
- who manages the server process
|
|
||||||
- whether the environment is local or remote
|
|
||||||
|
|
||||||
### 1. Direct WebSocket access
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
|
|
||||||
- `ws://10.0.0.15:3773`
|
|
||||||
- `wss://t3.example.com`
|
|
||||||
|
|
||||||
This is the base model and should be the first-class default.
|
|
||||||
|
|
||||||
Benefits:
|
|
||||||
|
|
||||||
- works for desktop, mobile, and web
|
|
||||||
- no client-specific process management required
|
|
||||||
- best fit for hosted or self-managed remote T3 deployments
|
|
||||||
|
|
||||||
### 2. Tunneled WebSocket access
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
|
|
||||||
- public relay URLs
|
|
||||||
- private network relay URLs
|
|
||||||
- local tunnel products such as pipenet
|
|
||||||
|
|
||||||
This is still direct WebSocket access from the client's perspective. The difference is that the route is mediated by a tunnel or relay.
|
|
||||||
|
|
||||||
For T3, tunnels are best modeled as another `AccessEndpoint`, not as a different kind of environment.
|
|
||||||
|
|
||||||
This is especially useful when:
|
|
||||||
|
|
||||||
- the host is behind NAT
|
|
||||||
- inbound ports are unavailable
|
|
||||||
- mobile must reach a desktop-hosted environment
|
|
||||||
- a machine should be reachable without exposing raw LAN or public ports
|
|
||||||
|
|
||||||
### 3. Desktop-managed SSH access
|
|
||||||
|
|
||||||
SSH is an access and launch helper, not a separate environment type.
|
|
||||||
|
|
||||||
The desktop main process can use SSH to:
|
|
||||||
|
|
||||||
- reach a machine
|
|
||||||
- probe it
|
|
||||||
- launch or reuse a remote T3 server
|
|
||||||
- establish a local port forward
|
|
||||||
|
|
||||||
After that, the renderer should still connect using an ordinary WebSocket URL against the forwarded local port.
|
|
||||||
|
|
||||||
This keeps the renderer transport model consistent with every other access method.
|
|
||||||
|
|
||||||
## Launch methods
|
|
||||||
|
|
||||||
Launch methods answer a different question:
|
|
||||||
|
|
||||||
How does a T3 server come to exist on the target machine?
|
|
||||||
|
|
||||||
Launch and access should stay separate in the design.
|
|
||||||
|
|
||||||
### 1. Pre-existing server
|
|
||||||
|
|
||||||
The simplest launch method is no launch at all.
|
|
||||||
|
|
||||||
The user or operator already runs T3 on the target machine, and the client connects through a direct or tunneled WebSocket endpoint.
|
|
||||||
|
|
||||||
This should be the first remote mode shipped because it validates the environment model with minimal extra machinery.
|
|
||||||
|
|
||||||
### 2. Desktop-managed remote launch over SSH
|
|
||||||
|
|
||||||
This is the main place where Zed is a useful reference.
|
|
||||||
|
|
||||||
Useful ideas to borrow from Zed:
|
|
||||||
|
|
||||||
- remote probing
|
|
||||||
- platform detection
|
|
||||||
- session directories with pid/log metadata
|
|
||||||
- reconnect-friendly launcher behavior
|
|
||||||
- desktop-owned connection UX
|
|
||||||
|
|
||||||
What should be different in T3:
|
|
||||||
|
|
||||||
- no custom stdio/socket proxy protocol between renderer and remote runtime
|
|
||||||
- no attempt to make the remote runtime look like an editor transport
|
|
||||||
- keep the final client-to-server connection as WebSocket
|
|
||||||
|
|
||||||
The recommended T3 flow is:
|
|
||||||
|
|
||||||
1. Desktop connects over SSH.
|
|
||||||
2. Desktop probes the remote machine and verifies T3 availability.
|
|
||||||
3. Desktop launches or reuses a remote T3 server.
|
|
||||||
4. Desktop establishes local port forwarding.
|
|
||||||
5. Renderer connects to the forwarded WebSocket endpoint as a normal environment.
|
|
||||||
|
|
||||||
### 3. Client-managed local publish
|
|
||||||
|
|
||||||
This is the inverse of remote launch: a local T3 server is already running, and the client publishes it through a tunnel.
|
|
||||||
|
|
||||||
This is useful for:
|
|
||||||
|
|
||||||
- exposing a desktop-hosted environment to mobile
|
|
||||||
- temporary remote access without changing router or firewall settings
|
|
||||||
|
|
||||||
This is still a launch concern, not a new environment kind.
|
|
||||||
|
|
||||||
## Why access and launch must stay separate
|
|
||||||
|
|
||||||
These concerns are easy to conflate, but separating them prevents architectural drift.
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
|
|
||||||
- A manually hosted T3 server might be reached through direct `wss`.
|
|
||||||
- The same server might also be reachable through a tunnel.
|
|
||||||
- An SSH-managed server might be launched over SSH but then reached through forwarded WebSocket.
|
|
||||||
- A local desktop server might be published through a tunnel for mobile.
|
|
||||||
|
|
||||||
In all of those cases, the `ExecutionEnvironment` is the same kind of thing.
|
|
||||||
|
|
||||||
Only the launch and access paths differ.
|
|
||||||
|
|
||||||
## Security model
|
|
||||||
|
|
||||||
Remote support must assume that some environments will be reachable over untrusted networks.
|
|
||||||
|
|
||||||
That means:
|
|
||||||
|
|
||||||
- remote-capable environments should require explicit authentication
|
|
||||||
- tunnel exposure should not rely on obscurity
|
|
||||||
- client-saved endpoints should carry enough auth metadata to reconnect safely
|
|
||||||
|
|
||||||
T3 already supports a WebSocket auth token on the server. That should become a first-class part of environment access rather than remaining an incidental query parameter convention.
|
|
||||||
|
|
||||||
For publicly reachable environments, authenticated access should be treated as required.
|
|
||||||
|
|
||||||
## Relationship to Zed
|
|
||||||
|
|
||||||
Zed is a useful reference implementation for managed remote launch and reconnect behavior.
|
|
||||||
|
|
||||||
The relevant lessons are:
|
|
||||||
|
|
||||||
- remote bootstrap should be explicit
|
|
||||||
- reconnect should be first-class
|
|
||||||
- connection UX belongs in the client shell
|
|
||||||
- runtime ownership should stay clearly on the remote host
|
|
||||||
|
|
||||||
The important mismatch is transport shape.
|
|
||||||
|
|
||||||
Zed needs a custom proxy/server protocol because its remote boundary sits below the editor and project runtime.
|
|
||||||
|
|
||||||
T3 should not copy that part.
|
|
||||||
|
|
||||||
T3 already has the right runtime boundary:
|
|
||||||
|
|
||||||
- one T3 server per environment
|
|
||||||
- ordinary HTTP/WebSocket between client and environment
|
|
||||||
|
|
||||||
So T3 should borrow Zed's launch discipline, not its transport protocol.
|
|
||||||
|
|
||||||
## Recommended rollout
|
|
||||||
|
|
||||||
1. First-class known environments and access endpoints.
|
|
||||||
2. Direct `ws` / `wss` remote environments.
|
|
||||||
3. Authenticated tunnel-backed environments.
|
|
||||||
4. Desktop-managed SSH launch and forwarding.
|
|
||||||
5. Multi-environment UI improvements after the base runtime path is proven.
|
|
||||||
|
|
||||||
This ordering keeps the architecture network-first and transport-agnostic while still leaving room for richer managed remote flows.
|
|
||||||
+1
-1
@@ -5,7 +5,7 @@
|
|||||||
- `bun run dev:web` — Starts just the Vite dev server for the web app.
|
- `bun run dev:web` — Starts just the Vite dev server for the web app.
|
||||||
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
|
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
|
||||||
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
|
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
|
||||||
`bun run dev -- --base-dir ~/.t3-2`
|
`bun run dev -- --state-dir ~/.t3/another-dev-state`
|
||||||
- `bun run start` — Runs the production server (serves built web app as static files).
|
- `bun run start` — Runs the production server (serves built web app as static files).
|
||||||
- `bun run build` — Builds contracts, web app, and server through Turbo.
|
- `bun run build` — Builds contracts, web app, and server through Turbo.
|
||||||
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
||||||
|
|||||||
@@ -1,2 +0,0 @@
|
|||||||
# git autocrlf=true converts LF to CRLF on Windows, causing issues with oxfmt
|
|
||||||
* text=auto eol=lf
|
|
||||||
+1
-2
@@ -28,5 +28,4 @@ github:realAhmedRoach
|
|||||||
github:shiroyasha9
|
github:shiroyasha9
|
||||||
github:Yash-Singh1
|
github:Yash-Singh1
|
||||||
github:eggfriedrice24
|
github:eggfriedrice24
|
||||||
github:Ymit24
|
github:Ymit24
|
||||||
github:shivamhwp
|
|
||||||
@@ -10,7 +10,6 @@ jobs:
|
|||||||
quality:
|
quality:
|
||||||
name: Format, Lint, Typecheck, Test, Browser Test, Build
|
name: Format, Lint, Typecheck, Test, Browser Test, Build
|
||||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||||
timeout-minutes: 10
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v6
|
||||||
@@ -72,12 +71,11 @@ jobs:
|
|||||||
- name: Verify preload bundle output
|
- name: Verify preload bundle output
|
||||||
run: |
|
run: |
|
||||||
test -f apps/desktop/dist-electron/preload.js
|
test -f apps/desktop/dist-electron/preload.js
|
||||||
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
|
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
|
||||||
|
|
||||||
release_smoke:
|
release_smoke:
|
||||||
name: Release Smoke
|
name: Release Smoke
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
timeout-minutes: 10
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v6
|
||||||
|
|||||||
+11
-101
@@ -24,32 +24,32 @@ jobs:
|
|||||||
{
|
{
|
||||||
name: "size:XS",
|
name: "size:XS",
|
||||||
color: "0e8a16",
|
color: "0e8a16",
|
||||||
description: "0-9 effective changed lines (test files excluded in mixed PRs).",
|
description: "0-9 changed lines (additions + deletions).",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "size:S",
|
name: "size:S",
|
||||||
color: "5ebd3e",
|
color: "5ebd3e",
|
||||||
description: "10-29 effective changed lines (test files excluded in mixed PRs).",
|
description: "10-29 changed lines (additions + deletions).",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "size:M",
|
name: "size:M",
|
||||||
color: "fbca04",
|
color: "fbca04",
|
||||||
description: "30-99 effective changed lines (test files excluded in mixed PRs).",
|
description: "30-99 changed lines (additions + deletions).",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "size:L",
|
name: "size:L",
|
||||||
color: "fe7d37",
|
color: "fe7d37",
|
||||||
description: "100-499 effective changed lines (test files excluded in mixed PRs).",
|
description: "100-499 changed lines (additions + deletions).",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "size:XL",
|
name: "size:XL",
|
||||||
color: "d93f0b",
|
color: "d93f0b",
|
||||||
description: "500-999 effective changed lines (test files excluded in mixed PRs).",
|
description: "500-999 changed lines (additions + deletions).",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "size:XXL",
|
name: "size:XXL",
|
||||||
color: "b60205",
|
color: "b60205",
|
||||||
description: "1,000+ effective changed lines (test files excluded in mixed PRs).",
|
description: "1,000+ changed lines (additions + deletions).",
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -124,49 +124,19 @@ jobs:
|
|||||||
group: pr-size-${{ github.event.pull_request.number }}
|
group: pr-size-${{ github.event.pull_request.number }}
|
||||||
cancel-in-progress: true
|
cancel-in-progress: true
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout base repository
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
- name: Sync PR size label
|
- name: Sync PR size label
|
||||||
uses: actions/github-script@v8
|
uses: actions/github-script@v8
|
||||||
env:
|
env:
|
||||||
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
|
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
|
||||||
with:
|
with:
|
||||||
script: |
|
script: |
|
||||||
const { execFileSync } = require("node:child_process");
|
|
||||||
|
|
||||||
const issueNumber = context.payload.pull_request.number;
|
const issueNumber = context.payload.pull_request.number;
|
||||||
const baseSha = context.payload.pull_request.base.sha;
|
const additions = context.payload.pull_request.additions ?? 0;
|
||||||
const headSha = context.payload.pull_request.head.sha;
|
const deletions = context.payload.pull_request.deletions ?? 0;
|
||||||
const headTrackingRef = `refs/remotes/pr-size/${issueNumber}`;
|
const changedLines = additions + deletions;
|
||||||
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
|
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
|
||||||
|
|
||||||
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
|
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
|
||||||
// Keep this aligned with the repo's test entrypoints and test-only support files.
|
|
||||||
const testExcludePathspecs = [
|
|
||||||
":(glob,exclude)**/__tests__/**",
|
|
||||||
":(glob,exclude)**/test/**",
|
|
||||||
":(glob,exclude)**/tests/**",
|
|
||||||
":(glob,exclude)apps/server/integration/**",
|
|
||||||
":(glob,exclude)**/*.test.*",
|
|
||||||
":(glob,exclude)**/*.spec.*",
|
|
||||||
":(glob,exclude)**/*.browser.*",
|
|
||||||
":(glob,exclude)**/*.integration.*",
|
|
||||||
];
|
|
||||||
|
|
||||||
const sumNumstat = (text) =>
|
|
||||||
text
|
|
||||||
.split("\n")
|
|
||||||
.filter(Boolean)
|
|
||||||
.reduce((total, line) => {
|
|
||||||
const [insertionsRaw = "0", deletionsRaw = "0"] = line.split("\t");
|
|
||||||
const additions =
|
|
||||||
insertionsRaw === "-" ? 0 : Number.parseInt(insertionsRaw, 10) || 0;
|
|
||||||
const deletions =
|
|
||||||
deletionsRaw === "-" ? 0 : Number.parseInt(deletionsRaw, 10) || 0;
|
|
||||||
|
|
||||||
return total + additions + deletions;
|
|
||||||
}, 0);
|
|
||||||
|
|
||||||
const resolveSizeLabel = (totalChangedLines) => {
|
const resolveSizeLabel = (totalChangedLines) => {
|
||||||
if (totalChangedLines < 10) {
|
if (totalChangedLines < 10) {
|
||||||
@@ -192,55 +162,6 @@ jobs:
|
|||||||
return "size:XXL";
|
return "size:XXL";
|
||||||
};
|
};
|
||||||
|
|
||||||
execFileSync("git", ["fetch", "--no-tags", "origin", baseSha], {
|
|
||||||
stdio: "inherit",
|
|
||||||
});
|
|
||||||
|
|
||||||
execFileSync(
|
|
||||||
"git",
|
|
||||||
["fetch", "--no-tags", "origin", `+refs/pull/${issueNumber}/head:${headTrackingRef}`],
|
|
||||||
{
|
|
||||||
stdio: "inherit",
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
const resolvedHeadSha = execFileSync("git", ["rev-parse", headTrackingRef], {
|
|
||||||
encoding: "utf8",
|
|
||||||
}).trim();
|
|
||||||
|
|
||||||
if (resolvedHeadSha !== headSha) {
|
|
||||||
core.warning(
|
|
||||||
`Fetched head SHA ${resolvedHeadSha} does not match pull request head SHA ${headSha}; using fetched ref for sizing.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
execFileSync("git", ["cat-file", "-e", `${baseSha}^{commit}`], {
|
|
||||||
stdio: "inherit",
|
|
||||||
});
|
|
||||||
|
|
||||||
const diffArgs = [
|
|
||||||
"diff",
|
|
||||||
"--numstat",
|
|
||||||
"--ignore-all-space",
|
|
||||||
"--ignore-blank-lines",
|
|
||||||
`${baseSha}...${resolvedHeadSha}`,
|
|
||||||
];
|
|
||||||
|
|
||||||
const totalChangedLines = sumNumstat(
|
|
||||||
execFileSync(
|
|
||||||
"git",
|
|
||||||
diffArgs,
|
|
||||||
{ encoding: "utf8" },
|
|
||||||
),
|
|
||||||
);
|
|
||||||
const nonTestChangedLines = sumNumstat(
|
|
||||||
execFileSync("git", [...diffArgs, "--", ".", ...testExcludePathspecs], {
|
|
||||||
encoding: "utf8",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const testChangedLines = Math.max(0, totalChangedLines - nonTestChangedLines);
|
|
||||||
|
|
||||||
const changedLines = nonTestChangedLines === 0 ? testChangedLines : nonTestChangedLines;
|
|
||||||
const nextLabelName = resolveSizeLabel(changedLines);
|
const nextLabelName = resolveSizeLabel(changedLines);
|
||||||
|
|
||||||
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
|
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
|
||||||
@@ -278,15 +199,4 @@ jobs:
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const classification =
|
core.info(`PR #${issueNumber}: ${changedLines} changed lines -> ${nextLabelName}`);
|
||||||
nonTestChangedLines === 0
|
|
||||||
? testChangedLines > 0
|
|
||||||
? "test-only PR"
|
|
||||||
: "no line changes"
|
|
||||||
: testChangedLines > 0
|
|
||||||
? "test lines excluded"
|
|
||||||
: "all non-test changes";
|
|
||||||
|
|
||||||
core.info(
|
|
||||||
`PR #${issueNumber}: ${nonTestChangedLines} non-test lines, ${testChangedLines} test lines, ${changedLines} effective lines -> ${nextLabelName} (${classification})`,
|
|
||||||
);
|
|
||||||
@@ -19,7 +19,6 @@ jobs:
|
|||||||
preflight:
|
preflight:
|
||||||
name: Preflight
|
name: Preflight
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
timeout-minutes: 10
|
|
||||||
outputs:
|
outputs:
|
||||||
version: ${{ steps.release_meta.outputs.version }}
|
version: ${{ steps.release_meta.outputs.version }}
|
||||||
tag: ${{ steps.release_meta.outputs.tag }}
|
tag: ${{ steps.release_meta.outputs.tag }}
|
||||||
@@ -82,7 +81,6 @@ jobs:
|
|||||||
name: Build ${{ matrix.label }}
|
name: Build ${{ matrix.label }}
|
||||||
needs: preflight
|
needs: preflight
|
||||||
runs-on: ${{ matrix.runner }}
|
runs-on: ${{ matrix.runner }}
|
||||||
timeout-minutes: 30
|
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
@@ -229,7 +227,6 @@ jobs:
|
|||||||
name: Publish CLI to npm
|
name: Publish CLI to npm
|
||||||
needs: [preflight, build]
|
needs: [preflight, build]
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
timeout-minutes: 10
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v6
|
||||||
@@ -263,7 +260,6 @@ jobs:
|
|||||||
name: Publish GitHub Release
|
name: Publish GitHub Release
|
||||||
needs: [preflight, build, publish_cli]
|
needs: [preflight, build, publish_cli]
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
timeout-minutes: 10
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v6
|
||||||
@@ -311,13 +307,12 @@ jobs:
|
|||||||
name: Finalize release
|
name: Finalize release
|
||||||
needs: [preflight, release]
|
needs: [preflight, release]
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
timeout-minutes: 10
|
|
||||||
steps:
|
steps:
|
||||||
- id: app_token
|
- id: app_token
|
||||||
name: Mint release app token
|
name: Mint release app token
|
||||||
uses: actions/create-github-app-token@v2
|
uses: actions/create-github-app-token@v2
|
||||||
with:
|
with:
|
||||||
app-id: ${{ secrets.RELEASE_APP_ID }}
|
app-id: ${{ vars.RELEASE_APP_ID }}
|
||||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||||
owner: ${{ github.repository_owner }}
|
owner: ${{ github.repository_owner }}
|
||||||
|
|
||||||
|
|||||||
+1
-5
@@ -12,13 +12,9 @@ packages/*/dist
|
|||||||
build/
|
build/
|
||||||
.logs/
|
.logs/
|
||||||
release/
|
release/
|
||||||
release-mock/
|
|
||||||
.t3
|
.t3
|
||||||
.idea/
|
.idea/
|
||||||
apps/web/.playwright
|
apps/web/.playwright
|
||||||
apps/web/playwright-report
|
apps/web/playwright-report
|
||||||
apps/web/src/components/__screenshots__
|
apps/web/src/components/__screenshots__
|
||||||
.vitest-*
|
.vitest-*
|
||||||
__screenshots__/
|
|
||||||
.tanstack
|
|
||||||
squashfs-root/
|
|
||||||
+1
-3
@@ -1,7 +1,6 @@
|
|||||||
{
|
{
|
||||||
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
||||||
"ignorePatterns": [
|
"ignorePatterns": [
|
||||||
".reference",
|
|
||||||
".plans",
|
".plans",
|
||||||
"dist",
|
"dist",
|
||||||
"dist-electron",
|
"dist-electron",
|
||||||
@@ -9,8 +8,7 @@
|
|||||||
"bun.lock",
|
"bun.lock",
|
||||||
"*.tsbuildinfo",
|
"*.tsbuildinfo",
|
||||||
"**/routeTree.gen.ts",
|
"**/routeTree.gen.ts",
|
||||||
"apps/web/public/mockServiceWorker.js",
|
"apps/web/public/mockServiceWorker.js"
|
||||||
"apps/web/src/lib/vendor/qrcodegen.ts"
|
|
||||||
],
|
],
|
||||||
"sortPackageJson": {}
|
"sortPackageJson": {}
|
||||||
}
|
}
|
||||||
@@ -1,441 +0,0 @@
|
|||||||
# Plan: Claude Code Integration (Orchestration Architecture)
|
|
||||||
|
|
||||||
## Why this plan was rewritten
|
|
||||||
|
|
||||||
The previous plan targeted a pre-orchestration architecture (`ProviderManager`, provider-native WS event methods, and direct provider UI wiring). The current app now routes everything through:
|
|
||||||
|
|
||||||
1. `orchestration.dispatchCommand` (client intent)
|
|
||||||
2. `OrchestrationEngine` (decide + persist + publish domain events)
|
|
||||||
3. `ProviderCommandReactor` (domain intent -> `ProviderService`)
|
|
||||||
4. `ProviderService` (adapter routing + canonical runtime stream)
|
|
||||||
5. `ProviderRuntimeIngestion` (provider runtime -> internal orchestration commands)
|
|
||||||
6. `orchestration.domainEvent` (single push channel consumed by web)
|
|
||||||
|
|
||||||
Claude integration must plug into this path instead of reintroducing legacy provider-specific flows.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Current constraints to design around (post-Stage 1)
|
|
||||||
|
|
||||||
1. Provider runtime ingestion expects canonical `ProviderRuntimeEvent` shapes, not provider-native payloads.
|
|
||||||
2. Start input now uses typed `providerOptions` and generic `resumeCursor`; top-level provider-specific fields were removed.
|
|
||||||
3. `resumeCursor` is intentionally opaque outside adapters and must never be synthesized from `providerThreadId`.
|
|
||||||
4. `ProviderService` still requires adapter `startSession()` to return a `ProviderSession` with `threadId`.
|
|
||||||
5. Checkpoint revert currently calls `providerService.rollbackConversation()`, so Claude adapter needs a rollback strategy compatible with current reactor behavior.
|
|
||||||
6. Web currently marks Claude as unavailable (`"Claude Code (soon)"`) and model picker is Codex-only.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Architecture target
|
|
||||||
|
|
||||||
Add Claude as a first-class provider adapter that emits canonical runtime events and works with existing orchestration reactors without adding new WS channels or bypass paths.
|
|
||||||
|
|
||||||
Key decisions:
|
|
||||||
|
|
||||||
1. Keep orchestration provider-agnostic; adapt Claude inside adapter/layer boundaries.
|
|
||||||
2. Use the existing canonical runtime stream (`ProviderRuntimeEvent`) as the only ingestion contract.
|
|
||||||
3. Keep provider session routing in `ProviderService` and `ProviderSessionDirectory`.
|
|
||||||
4. Add explicit provider selection to turn-start intent so first turn can start Claude session intentionally.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase 1: Contracts and command shape updates
|
|
||||||
|
|
||||||
### 1.1 Provider-aware model contract
|
|
||||||
|
|
||||||
Update `packages/contracts/src/model.ts` so model resolution can be provider-aware instead of Codex-only.
|
|
||||||
|
|
||||||
Expected outcomes:
|
|
||||||
|
|
||||||
1. Introduce provider-scoped model lists (Codex + Claude).
|
|
||||||
2. Add helpers that resolve model by provider.
|
|
||||||
3. Preserve backwards compatibility for existing Codex defaults.
|
|
||||||
|
|
||||||
### 1.2 Turn-start provider intent
|
|
||||||
|
|
||||||
Update `packages/contracts/src/orchestration.ts`:
|
|
||||||
|
|
||||||
1. Add optional `provider: ProviderKind` to `ThreadTurnStartCommand`.
|
|
||||||
2. Carry provider through `ThreadTurnStartRequestedPayload`.
|
|
||||||
3. Keep existing command valid when provider is omitted.
|
|
||||||
|
|
||||||
This removes the implicit “Codex unless session already exists” behavior as the only path.
|
|
||||||
|
|
||||||
### 1.3 Provider session start input for Claude runtime knobs (completed)
|
|
||||||
|
|
||||||
Update `packages/contracts/src/provider.ts`:
|
|
||||||
|
|
||||||
1. Move provider-specific start fields into typed `providerOptions`:
|
|
||||||
- `providerOptions.codex`
|
|
||||||
- `providerOptions.claudeCode`
|
|
||||||
2. Keep `resumeCursor` as the single cross-provider resume input in `ProviderSessionStartInput`.
|
|
||||||
3. Deprecate/remove `resumeThreadId` from the generic start contract.
|
|
||||||
4. Treat `resumeCursor` as adapter-owned opaque state.
|
|
||||||
|
|
||||||
### 1.4 Contract tests (completed)
|
|
||||||
|
|
||||||
Update/add tests in `packages/contracts/src/*.test.ts` for:
|
|
||||||
|
|
||||||
1. New command payload shape.
|
|
||||||
2. Provider-aware model resolution behavior.
|
|
||||||
3. Breaking-change expectations for removed top-level provider fields.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase 2: Claude adapter implementation
|
|
||||||
|
|
||||||
### 2.1 Add adapter service + layer
|
|
||||||
|
|
||||||
Create:
|
|
||||||
|
|
||||||
1. `apps/server/src/provider/Services/ClaudeAdapter.ts`
|
|
||||||
2. `apps/server/src/provider/Layers/ClaudeAdapter.ts`
|
|
||||||
|
|
||||||
Adapter must implement `ProviderAdapterShape<ProviderAdapterError>`.
|
|
||||||
|
|
||||||
### 2.1.a SDK dependency and baseline config
|
|
||||||
|
|
||||||
Add server dependency:
|
|
||||||
|
|
||||||
1. `@anthropic-ai/claude-agent-sdk`
|
|
||||||
|
|
||||||
Baseline adapter options to support from day one:
|
|
||||||
|
|
||||||
1. `cwd`
|
|
||||||
2. `model`
|
|
||||||
3. `pathToClaudeCodeExecutable` (from `providerOptions.claudeCode.binaryPath`)
|
|
||||||
4. `permissionMode` (from `providerOptions.claudeCode.permissionMode`)
|
|
||||||
5. `maxThinkingTokens` (from `providerOptions.claudeCode.maxThinkingTokens`)
|
|
||||||
6. `resume`
|
|
||||||
7. `resumeSessionAt`
|
|
||||||
8. `includePartialMessages`
|
|
||||||
9. `canUseTool`
|
|
||||||
10. `hooks`
|
|
||||||
11. `env` and `additionalDirectories` (if needed for sandbox/workspace parity)
|
|
||||||
|
|
||||||
### 2.2 Claude runtime bridge
|
|
||||||
|
|
||||||
Implement a Claude runtime bridge (either directly in adapter layer or via dedicated manager file) that wraps Agent SDK query lifecycle.
|
|
||||||
|
|
||||||
Required capabilities:
|
|
||||||
|
|
||||||
1. Long-lived session context per adapter session.
|
|
||||||
2. Multi-turn input queue.
|
|
||||||
3. Interrupt support.
|
|
||||||
4. Approval request/response bridge.
|
|
||||||
5. Resume support via opaque `resumeCursor` (parsed inside Claude adapter only).
|
|
||||||
|
|
||||||
#### 2.2.a Agent SDK details to preserve
|
|
||||||
|
|
||||||
The adapter should explicitly rely on these SDK capabilities:
|
|
||||||
|
|
||||||
1. `query()` returns an async iterable message stream and control methods (`interrupt`, `setModel`, `setPermissionMode`, `setMaxThinkingTokens`, account/status helpers).
|
|
||||||
2. Multi-turn input is supported via async-iterable prompt input.
|
|
||||||
3. Tool approval decisions are provided via `canUseTool`.
|
|
||||||
4. Resume support uses `resume` and optional `resumeSessionAt`, both derived by parsing adapter-owned `resumeCursor`.
|
|
||||||
5. Hooks can be used for lifecycle signals (`Stop`, `PostToolUse`, etc.) when we need adapter-originated checkpoint/runtime events.
|
|
||||||
|
|
||||||
#### 2.2.b Effect-native session lifecycle skeleton
|
|
||||||
|
|
||||||
```ts
|
|
||||||
import { query } from "@anthropic-ai/claude-agent-sdk";
|
|
||||||
import { Effect } from "effect";
|
|
||||||
|
|
||||||
const acquireSession = (input: ProviderSessionStartInput) =>
|
|
||||||
Effect.acquireRelease(
|
|
||||||
Effect.tryPromise({
|
|
||||||
try: async () => {
|
|
||||||
const claudeOptions = input.providerOptions?.claudeCode;
|
|
||||||
const resumeState = readClaudeResumeState(input.resumeCursor);
|
|
||||||
const abortController = new AbortController();
|
|
||||||
const result = query({
|
|
||||||
prompt: makePromptAsyncIterable(),
|
|
||||||
options: {
|
|
||||||
cwd: input.cwd,
|
|
||||||
model: input.model,
|
|
||||||
permissionMode: claudeOptions?.permissionMode,
|
|
||||||
maxThinkingTokens: claudeOptions?.maxThinkingTokens,
|
|
||||||
pathToClaudeCodeExecutable: claudeOptions?.binaryPath,
|
|
||||||
resume: resumeState?.threadId,
|
|
||||||
resumeSessionAt: resumeState?.sessionAt,
|
|
||||||
signal: abortController.signal,
|
|
||||||
includePartialMessages: true,
|
|
||||||
canUseTool: makeCanUseTool(),
|
|
||||||
hooks: makeClaudeHooks(),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
return { abortController, result };
|
|
||||||
},
|
|
||||||
catch: (cause) =>
|
|
||||||
new ProviderAdapterProcessError({
|
|
||||||
provider: "claudeCode",
|
|
||||||
sessionId: "pending",
|
|
||||||
detail: "Failed to start Claude runtime session.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
({ abortController }) => Effect.sync(() => abortController.abort()),
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 2.2.c AsyncIterable -> Effect Stream integration
|
|
||||||
|
|
||||||
Preferred when available in the pinned Effect version:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
const sdkMessageStream = Stream.fromAsyncIterable(
|
|
||||||
session.result,
|
|
||||||
(cause) =>
|
|
||||||
new ProviderAdapterProcessError({
|
|
||||||
provider: "claudeCode",
|
|
||||||
sessionId,
|
|
||||||
detail: "Claude runtime stream failed.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
Portable fallback (already aligned with current server patterns):
|
|
||||||
|
|
||||||
```ts
|
|
||||||
const sdkMessageStream = Stream.async<ClaudeSdkMessage, ProviderAdapterProcessError>((emit) => {
|
|
||||||
let cancelled = false;
|
|
||||||
void (async () => {
|
|
||||||
try {
|
|
||||||
for await (const message of session.result) {
|
|
||||||
if (cancelled) break;
|
|
||||||
emit.single(message);
|
|
||||||
}
|
|
||||||
emit.end();
|
|
||||||
} catch (cause) {
|
|
||||||
emit.fail(
|
|
||||||
new ProviderAdapterProcessError({
|
|
||||||
provider: "claudeCode",
|
|
||||||
sessionId,
|
|
||||||
detail: "Claude runtime stream failed.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
return Effect.sync(() => {
|
|
||||||
cancelled = true;
|
|
||||||
});
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2.3 Canonical event mapping
|
|
||||||
|
|
||||||
Claude adapter must translate Agent SDK output into canonical `ProviderRuntimeEvent`.
|
|
||||||
|
|
||||||
Initial mapping target:
|
|
||||||
|
|
||||||
1. assistant text deltas -> `content.delta`
|
|
||||||
2. final assistant text -> `item.completed` and/or `turn.completed`
|
|
||||||
3. approval requests -> `request.opened`
|
|
||||||
4. approval results -> `request.resolved`
|
|
||||||
5. system lifecycle -> `session.*`, `thread.*`, `turn.*`
|
|
||||||
6. errors -> `runtime.error`
|
|
||||||
7. plan/proposed-plan content when derivable
|
|
||||||
|
|
||||||
Implementation note:
|
|
||||||
|
|
||||||
1. Keep raw Claude message on `raw` for debugging.
|
|
||||||
2. Prefer canonical item/request kinds over provider-native enums.
|
|
||||||
3. If Claude emits extra event kinds we do not model yet, map them to `tool.summary`, `runtime.warning`, or `unknown`-compatible payloads instead of dropping silently.
|
|
||||||
|
|
||||||
### 2.4 Resume cursor strategy
|
|
||||||
|
|
||||||
Define Claude-owned opaque resume state, e.g.:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
interface ClaudeResumeCursor {
|
|
||||||
readonly version: 1;
|
|
||||||
readonly threadId?: string;
|
|
||||||
readonly sessionAt?: string;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Rules:
|
|
||||||
|
|
||||||
1. Serialize only adapter-owned state into `resumeCursor`.
|
|
||||||
2. Parse/validate only inside Claude adapter.
|
|
||||||
3. Store updated cursor when Claude runtime yields enough data to resume safely.
|
|
||||||
4. Never overload orchestration thread id as Claude thread id.
|
|
||||||
|
|
||||||
### 2.5 Interrupt and stop semantics
|
|
||||||
|
|
||||||
Map orchestration stop/interrupt expectations onto SDK controls:
|
|
||||||
|
|
||||||
1. `interruptTurn()` -> active query interrupt.
|
|
||||||
2. `stopSession()` -> close session resources and prevent future sends.
|
|
||||||
3. `rollbackThread()` -> see Phase 4.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase 3: Provider service and composition
|
|
||||||
|
|
||||||
### 3.1 Register Claude adapter
|
|
||||||
|
|
||||||
Update provider registry layer to include Claude:
|
|
||||||
|
|
||||||
1. add `claudeCode` -> `ClaudeAdapter`
|
|
||||||
2. ensure `ProviderService.listProviderStatuses()` reports Claude availability
|
|
||||||
|
|
||||||
### 3.2 Persist provider binding
|
|
||||||
|
|
||||||
Current `ProviderSessionDirectory` already stores provider/thread binding and opaque `resumeCursor`.
|
|
||||||
|
|
||||||
Required validation:
|
|
||||||
|
|
||||||
1. Claude bindings survive restart.
|
|
||||||
2. resume cursor remains opaque and round-trips untouched.
|
|
||||||
3. stopAll + restart can recover Claude sessions when possible.
|
|
||||||
|
|
||||||
### 3.3 Provider start routing
|
|
||||||
|
|
||||||
Update `ProviderCommandReactor` / orchestration flow:
|
|
||||||
|
|
||||||
1. If a thread turn start requests `provider: "claudeCode"`, start Claude if no active session exists.
|
|
||||||
2. If a thread already has Claude session binding, reuse it.
|
|
||||||
3. If provider switches between Codex and Claude, explicitly stop/rebind before next send.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase 4: Checkpoint and revert strategy
|
|
||||||
|
|
||||||
Claude does not necessarily expose the same conversation rewind primitive as Codex app-server. Current architecture expects `providerService.rollbackConversation()`.
|
|
||||||
|
|
||||||
Pick one explicit strategy:
|
|
||||||
|
|
||||||
### Option A: provider-native rewind
|
|
||||||
|
|
||||||
If SDK/runtime supports safe rewind:
|
|
||||||
|
|
||||||
1. implement in Claude adapter
|
|
||||||
2. keep `CheckpointReactor` unchanged
|
|
||||||
|
|
||||||
### Option B: session restart + state truncation shim
|
|
||||||
|
|
||||||
If no native rewind exists:
|
|
||||||
|
|
||||||
1. Claude adapter returns successful rollback by:
|
|
||||||
- stopping current Claude session
|
|
||||||
- clearing/rewriting stored Claude resume cursor to last safe resumable point
|
|
||||||
- forcing next turn to recreate session from persisted orchestration state
|
|
||||||
2. Document that rollback is “conversation reset to checkpoint boundary”, not provider-native turn deletion.
|
|
||||||
|
|
||||||
Whichever option is chosen:
|
|
||||||
|
|
||||||
1. behavior must be deterministic
|
|
||||||
2. checkpoint revert tests must pass under orchestration expectations
|
|
||||||
3. user-visible activity log should explain failures clearly when provider rollback is impossible
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase 5: Web integration
|
|
||||||
|
|
||||||
### 5.1 Provider picker and model picker
|
|
||||||
|
|
||||||
Update web state/UI:
|
|
||||||
|
|
||||||
1. allow choosing Claude as thread provider before first turn
|
|
||||||
2. show Claude model list from provider-aware model helpers
|
|
||||||
3. preserve existing Codex default behavior when provider omitted
|
|
||||||
|
|
||||||
Likely touch points:
|
|
||||||
|
|
||||||
1. `apps/web/src/store.ts`
|
|
||||||
2. `apps/web/src/components/ChatView.tsx`
|
|
||||||
3. `apps/web/src/types.ts`
|
|
||||||
4. `packages/shared/src/model.ts`
|
|
||||||
|
|
||||||
### 5.2 Settings for Claude executable/options
|
|
||||||
|
|
||||||
Add app settings if needed for:
|
|
||||||
|
|
||||||
1. Claude binary path
|
|
||||||
2. default permission mode
|
|
||||||
3. default max thinking tokens
|
|
||||||
|
|
||||||
Do not hardcode provider-specific config into generic session state if it belongs in app settings or typed `providerOptions`.
|
|
||||||
|
|
||||||
### 5.3 Session rendering
|
|
||||||
|
|
||||||
No new WS channel should be needed. Claude should appear through existing:
|
|
||||||
|
|
||||||
1. thread messages
|
|
||||||
2. activities/worklog
|
|
||||||
3. approvals
|
|
||||||
4. session state
|
|
||||||
5. checkpoints/diffs
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase 6: Testing strategy
|
|
||||||
|
|
||||||
### 6.1 Contract tests
|
|
||||||
|
|
||||||
Cover:
|
|
||||||
|
|
||||||
1. provider-aware model schemas
|
|
||||||
2. provider field on turn-start command
|
|
||||||
3. provider-specific start options schema
|
|
||||||
|
|
||||||
### 6.2 Adapter layer tests
|
|
||||||
|
|
||||||
Add `ClaudeAdapter.test.ts` covering:
|
|
||||||
|
|
||||||
1. session start
|
|
||||||
2. event mapping
|
|
||||||
3. approval bridge
|
|
||||||
4. resume cursor parse/serialize
|
|
||||||
5. interrupt behavior
|
|
||||||
6. rollback behavior or explicit unsupported error path
|
|
||||||
|
|
||||||
Use SDK-facing layer tests/mocks only at the boundary. Do not mock orchestration business logic in higher-level tests.
|
|
||||||
|
|
||||||
### 6.3 Provider service integration tests
|
|
||||||
|
|
||||||
Extend provider integration coverage so Claude is exercised through `ProviderService`:
|
|
||||||
|
|
||||||
1. start Claude session
|
|
||||||
2. send turn
|
|
||||||
3. receive canonical runtime events
|
|
||||||
4. restart/recover using persisted binding
|
|
||||||
|
|
||||||
### 6.4 Orchestration integration tests
|
|
||||||
|
|
||||||
Add/extend integration tests around:
|
|
||||||
|
|
||||||
1. first-turn provider selection
|
|
||||||
2. Claude approval requests routed through orchestration
|
|
||||||
3. Claude runtime ingestion -> messages/activities/session updates
|
|
||||||
4. checkpoint revert behavior under Claude
|
|
||||||
5. stopAll/restart recovery
|
|
||||||
|
|
||||||
These should validate real orchestration flows, not just adapter behavior.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase 7: Rollout order
|
|
||||||
|
|
||||||
Recommended implementation order:
|
|
||||||
|
|
||||||
1. contracts/provider-aware models
|
|
||||||
2. provider field on turn-start
|
|
||||||
3. Claude adapter skeleton + start/send/stream
|
|
||||||
4. canonical event mapping
|
|
||||||
5. provider registry/service wiring
|
|
||||||
6. orchestration recovery + checkpoint strategy
|
|
||||||
7. web provider/model picker
|
|
||||||
8. full integration tests
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Non-goals
|
|
||||||
|
|
||||||
1. Reintroducing provider-specific WS methods/channels.
|
|
||||||
2. Storing provider-native thread ids as orchestration ids.
|
|
||||||
3. Bypassing orchestration engine for Claude-specific UI flows.
|
|
||||||
4. Encoding Claude resume semantics outside adapter-owned `resumeCursor`.
|
|
||||||
@@ -1,823 +0,0 @@
|
|||||||
# Server Auth Model Plan
|
|
||||||
|
|
||||||
## Purpose
|
|
||||||
|
|
||||||
Define the long-term server auth architecture for T3 Code before first-class remote environments ship.
|
|
||||||
|
|
||||||
This plan is deliberately broader than the current WebSocket token check and narrower than a complete remote collaboration system. The goal is to make the server secure by default, keep local desktop UX frictionless, and leave clean integration points for future remote access methods.
|
|
||||||
|
|
||||||
This document is written in terms of Effect-native services and layers because auth needs to be a core runtime concern, not route-local glue code.
|
|
||||||
|
|
||||||
## Primary goals
|
|
||||||
|
|
||||||
- Make auth server-wide, not WebSocket-only.
|
|
||||||
- Make insecure exposure hard to do accidentally.
|
|
||||||
- Preserve zero-login local desktop UX for desktop-managed environments.
|
|
||||||
- Support browser-native pairing and session auth.
|
|
||||||
- Leave room for native/mobile credentials later without rewriting the server boundary.
|
|
||||||
- Keep auth separate from transport and launch method.
|
|
||||||
|
|
||||||
## Non-goals
|
|
||||||
|
|
||||||
- Full multi-user authorization and RBAC.
|
|
||||||
- OAuth / SSO / enterprise identity.
|
|
||||||
- Passkeys or biometric UX in v1.
|
|
||||||
- Syncing auth state across environments.
|
|
||||||
- Designing the full remote environment product in this document.
|
|
||||||
|
|
||||||
## Core decisions
|
|
||||||
|
|
||||||
### 1. Auth is a server concern
|
|
||||||
|
|
||||||
Every privileged surface of the T3 server must go through the same auth policy engine:
|
|
||||||
|
|
||||||
- HTTP routes
|
|
||||||
- WebSocket upgrades
|
|
||||||
- RPC methods reached through WebSocket
|
|
||||||
|
|
||||||
The current split where [`/ws`](../apps/server/src/ws.ts) checks `authToken` but routes in [`http.ts`](../apps/server/src/http.ts) do not is not sufficient for a remote-capable product.
|
|
||||||
|
|
||||||
### 2. Pairing and session are different things
|
|
||||||
|
|
||||||
The system should distinguish:
|
|
||||||
|
|
||||||
- bootstrap credentials
|
|
||||||
- session credentials
|
|
||||||
|
|
||||||
Bootstrap credentials are short-lived and high-trust. They allow a client to become authenticated.
|
|
||||||
|
|
||||||
Session credentials are the durable credentials used after pairing.
|
|
||||||
|
|
||||||
Bootstrap should never become the long-lived request credential.
|
|
||||||
|
|
||||||
### 3. Auth and transport are separate
|
|
||||||
|
|
||||||
Auth must not be defined by how the client reached the server.
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
|
|
||||||
- local desktop-managed server
|
|
||||||
- LAN `ws://`
|
|
||||||
- public `wss://`
|
|
||||||
- tunneled `wss://`
|
|
||||||
- SSH-forwarded `ws://127.0.0.1:<port>`
|
|
||||||
|
|
||||||
All of these should feed into the same auth model.
|
|
||||||
|
|
||||||
### 4. Exposure level changes defaults
|
|
||||||
|
|
||||||
The more exposed an environment is, the narrower the safe default should be.
|
|
||||||
|
|
||||||
Safe default expectations:
|
|
||||||
|
|
||||||
- local desktop-managed: auto-pair allowed
|
|
||||||
- loopback browser access: explicit bootstrap allowed
|
|
||||||
- non-loopback bind: auth required
|
|
||||||
- tunnel/public endpoint: auth required, explicit enablement required
|
|
||||||
|
|
||||||
### 5. Browser and native clients may use different session credentials
|
|
||||||
|
|
||||||
The auth model should support more than one session credential type even if only one ships first.
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
|
|
||||||
- browser session cookie
|
|
||||||
- native bearer/device token
|
|
||||||
|
|
||||||
This should be represented in the model now, even if browser cookies are the first implementation.
|
|
||||||
|
|
||||||
## Target auth domain
|
|
||||||
|
|
||||||
### Route classes
|
|
||||||
|
|
||||||
Every route or transport entrypoint should be classified as one of:
|
|
||||||
|
|
||||||
1. `public`
|
|
||||||
2. `bootstrap`
|
|
||||||
3. `authenticated`
|
|
||||||
|
|
||||||
#### `public`
|
|
||||||
|
|
||||||
Unauthenticated by definition.
|
|
||||||
|
|
||||||
Should be extremely small. Examples:
|
|
||||||
|
|
||||||
- static shell needed to render the pairing/login UI
|
|
||||||
- favicon/assets required for the pairing screen
|
|
||||||
- a minimal server health/version endpoint if needed
|
|
||||||
|
|
||||||
#### `bootstrap`
|
|
||||||
|
|
||||||
Used only to exchange a bootstrap credential for a session.
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
|
|
||||||
- Initial bootstrap envelope over file descriptor at startup
|
|
||||||
- `POST /api/auth/bootstrap`
|
|
||||||
- `GET /api/auth/session` if unauthenticated checks are part of bootstrap UX
|
|
||||||
|
|
||||||
#### `authenticated`
|
|
||||||
|
|
||||||
Everything that reveals machine state or mutates it.
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
|
|
||||||
- WebSocket upgrade
|
|
||||||
- orchestration snapshot and events
|
|
||||||
- terminal open/write/close
|
|
||||||
- project search and file writes
|
|
||||||
- git routes
|
|
||||||
- attachments
|
|
||||||
- project favicon lookup
|
|
||||||
- server settings
|
|
||||||
|
|
||||||
The default stance should be: if it touches the machine, it is authenticated.
|
|
||||||
|
|
||||||
## Credential model
|
|
||||||
|
|
||||||
### Bootstrap credentials
|
|
||||||
|
|
||||||
Initial credential types to model:
|
|
||||||
|
|
||||||
- `desktop-bootstrap`
|
|
||||||
- `one-time-token`
|
|
||||||
|
|
||||||
Possible future credential types:
|
|
||||||
|
|
||||||
- `device-code`
|
|
||||||
- `passkey-assertion`
|
|
||||||
- `external-identity`
|
|
||||||
|
|
||||||
#### `desktop-bootstrap`
|
|
||||||
|
|
||||||
Used when the desktop shell manages the server and should be the only default pairing method for desktop-local environments.
|
|
||||||
|
|
||||||
Properties:
|
|
||||||
|
|
||||||
- launcher-provided
|
|
||||||
- short-lived
|
|
||||||
- one-time or bounded-use
|
|
||||||
- never shown to the user as a reusable password
|
|
||||||
|
|
||||||
#### `one-time-token`
|
|
||||||
|
|
||||||
Used for explicit browser/mobile pairing flows.
|
|
||||||
|
|
||||||
Properties:
|
|
||||||
|
|
||||||
- short TTL
|
|
||||||
- one-time use
|
|
||||||
- safe to embed in a pairing URL fragment
|
|
||||||
- exchanged for a session credential
|
|
||||||
|
|
||||||
### Session credentials
|
|
||||||
|
|
||||||
Initial credential types to model:
|
|
||||||
|
|
||||||
- `browser-session-cookie`
|
|
||||||
- `bearer-session-token`
|
|
||||||
|
|
||||||
#### `browser-session-cookie`
|
|
||||||
|
|
||||||
Primary browser credential.
|
|
||||||
|
|
||||||
Properties:
|
|
||||||
|
|
||||||
- signed
|
|
||||||
- `HttpOnly`
|
|
||||||
- bounded lifetime
|
|
||||||
- revocable by server key rotation or session invalidation
|
|
||||||
|
|
||||||
#### `bearer-session-token`
|
|
||||||
|
|
||||||
Reserved for native/mobile or non-browser clients.
|
|
||||||
|
|
||||||
Properties:
|
|
||||||
|
|
||||||
- opaque token, not a bootstrap secret
|
|
||||||
- long enough lifetime to survive reconnects
|
|
||||||
- stored in secure client storage when available
|
|
||||||
|
|
||||||
## Auth policy model
|
|
||||||
|
|
||||||
Auth behavior should be driven by an explicit environment auth policy, not route-local heuristics.
|
|
||||||
|
|
||||||
### Policy examples
|
|
||||||
|
|
||||||
#### `DesktopManagedLocalPolicy`
|
|
||||||
|
|
||||||
Default for desktop-managed local server.
|
|
||||||
|
|
||||||
Allowed bootstrap methods:
|
|
||||||
|
|
||||||
- `desktop-bootstrap`
|
|
||||||
|
|
||||||
Allowed session methods:
|
|
||||||
|
|
||||||
- `browser-session-cookie`
|
|
||||||
|
|
||||||
Disabled by default:
|
|
||||||
|
|
||||||
- `one-time-token`
|
|
||||||
- `bearer-session-token`
|
|
||||||
- password login
|
|
||||||
- public pairing
|
|
||||||
|
|
||||||
#### `LoopbackBrowserPolicy`
|
|
||||||
|
|
||||||
Used for browser access on localhost without desktop-managed bootstrap.
|
|
||||||
|
|
||||||
Allowed bootstrap methods:
|
|
||||||
|
|
||||||
- `one-time-token`
|
|
||||||
|
|
||||||
Allowed session methods:
|
|
||||||
|
|
||||||
- `browser-session-cookie`
|
|
||||||
|
|
||||||
#### `RemoteReachablePolicy`
|
|
||||||
|
|
||||||
Used when binding non-loopback or using an explicit remote/tunnel workflow.
|
|
||||||
|
|
||||||
Allowed bootstrap methods:
|
|
||||||
|
|
||||||
- `one-time-token`
|
|
||||||
- possibly `desktop-bootstrap` when a desktop shell is brokering access
|
|
||||||
|
|
||||||
Allowed session methods:
|
|
||||||
|
|
||||||
- `browser-session-cookie`
|
|
||||||
- `bearer-session-token`
|
|
||||||
|
|
||||||
#### `UnsafeNoAuthPolicy`
|
|
||||||
|
|
||||||
Should exist only as an explicit escape hatch.
|
|
||||||
|
|
||||||
Requirements:
|
|
||||||
|
|
||||||
- explicit opt-in flag
|
|
||||||
- loud startup warnings
|
|
||||||
- never defaulted automatically
|
|
||||||
|
|
||||||
## Effect-native service model
|
|
||||||
|
|
||||||
### `ServerAuth`
|
|
||||||
|
|
||||||
The main auth facade used by HTTP routes and WebSocket upgrade handling.
|
|
||||||
|
|
||||||
Responsibilities:
|
|
||||||
|
|
||||||
- classify requests
|
|
||||||
- authenticate requests
|
|
||||||
- authorize bootstrap attempts
|
|
||||||
- create sessions from bootstrap credentials
|
|
||||||
- enforce policy by environment mode
|
|
||||||
|
|
||||||
Sketch:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
export interface ServerAuthShape {
|
|
||||||
readonly getCapabilities: Effect.Effect<AuthCapabilities>;
|
|
||||||
readonly authenticateHttpRequest: (
|
|
||||||
request: HttpServerRequest.HttpServerRequest,
|
|
||||||
routeClass: RouteAuthClass,
|
|
||||||
) => Effect.Effect<AuthContext, AuthError>;
|
|
||||||
readonly authenticateWebSocketUpgrade: (
|
|
||||||
request: HttpServerRequest.HttpServerRequest,
|
|
||||||
) => Effect.Effect<AuthContext, AuthError>;
|
|
||||||
readonly exchangeBootstrapCredential: (
|
|
||||||
input: BootstrapExchangeInput,
|
|
||||||
) => Effect.Effect<SessionGrant, AuthError>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class ServerAuth extends ServiceMap.Service<ServerAuth, ServerAuthShape>()(
|
|
||||||
"t3/ServerAuth",
|
|
||||||
) {}
|
|
||||||
```
|
|
||||||
|
|
||||||
### `BootstrapCredentialService`
|
|
||||||
|
|
||||||
Owns issuance, storage, validation, and consumption of bootstrap credentials.
|
|
||||||
|
|
||||||
Responsibilities:
|
|
||||||
|
|
||||||
- issue desktop bootstrap grants
|
|
||||||
- issue one-time pairing tokens
|
|
||||||
- validate TTL and single-use semantics
|
|
||||||
- consume bootstrap grants atomically
|
|
||||||
|
|
||||||
Sketch:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
export interface BootstrapCredentialServiceShape {
|
|
||||||
readonly issueDesktopBootstrap: (
|
|
||||||
input: IssueDesktopBootstrapInput,
|
|
||||||
) => Effect.Effect<BootstrapCredential>;
|
|
||||||
readonly issueOneTimeToken: (
|
|
||||||
input: IssueOneTimeTokenInput,
|
|
||||||
) => Effect.Effect<BootstrapCredential>;
|
|
||||||
readonly consume: (
|
|
||||||
presented: PresentedBootstrapCredential,
|
|
||||||
) => Effect.Effect<ConsumedBootstrapCredential, BootstrapCredentialError>;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### `SessionCredentialService`
|
|
||||||
|
|
||||||
Owns creation and validation of authenticated sessions.
|
|
||||||
|
|
||||||
Responsibilities:
|
|
||||||
|
|
||||||
- mint cookie sessions
|
|
||||||
- mint bearer sessions
|
|
||||||
- validate active session credentials
|
|
||||||
- revoke sessions if needed later
|
|
||||||
|
|
||||||
Sketch:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
export interface SessionCredentialServiceShape {
|
|
||||||
readonly createBrowserSession: (
|
|
||||||
input: CreateSessionFromBootstrapInput,
|
|
||||||
) => Effect.Effect<BrowserSessionGrant, SessionCredentialError>;
|
|
||||||
readonly createBearerSession: (
|
|
||||||
input: CreateSessionFromBootstrapInput,
|
|
||||||
) => Effect.Effect<BearerSessionGrant, SessionCredentialError>;
|
|
||||||
readonly authenticateCookie: (
|
|
||||||
request: HttpServerRequest.HttpServerRequest,
|
|
||||||
) => Effect.Effect<AuthContext, SessionCredentialError>;
|
|
||||||
readonly authenticateBearer: (
|
|
||||||
request: HttpServerRequest.HttpServerRequest,
|
|
||||||
) => Effect.Effect<AuthContext, SessionCredentialError>;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### `ServerAuthPolicy`
|
|
||||||
|
|
||||||
Pure policy/config service that decides which credential types are allowed.
|
|
||||||
|
|
||||||
Responsibilities:
|
|
||||||
|
|
||||||
- map runtime mode and bind/exposure settings to allowed auth methods
|
|
||||||
- answer whether a route can be public
|
|
||||||
- answer whether remote exposure requires auth
|
|
||||||
|
|
||||||
This should stay mostly pure and cheap to test.
|
|
||||||
|
|
||||||
### `ServerSecretStore`
|
|
||||||
|
|
||||||
Owns long-lived server signing keys and secrets.
|
|
||||||
|
|
||||||
Responsibilities:
|
|
||||||
|
|
||||||
- get or create signing key
|
|
||||||
- rotate signing key
|
|
||||||
- abstract secure OS-backed storage vs filesystem fallback
|
|
||||||
|
|
||||||
Important:
|
|
||||||
|
|
||||||
- prefer platform secure storage when available
|
|
||||||
- support hardened filesystem fallback for headless/server-only environments
|
|
||||||
|
|
||||||
### `BrowserSessionCookieCodec`
|
|
||||||
|
|
||||||
Focused utility service for cookie encode/decode/signing behavior.
|
|
||||||
|
|
||||||
This should not own policy. It should only own the cookie format.
|
|
||||||
|
|
||||||
### `AuthRouteGuards`
|
|
||||||
|
|
||||||
Thin helper layer used by routes to enforce auth consistently.
|
|
||||||
|
|
||||||
Responsibilities:
|
|
||||||
|
|
||||||
- require auth for HTTP route handlers
|
|
||||||
- classify route auth mode
|
|
||||||
- convert auth failures into `401` / `403`
|
|
||||||
|
|
||||||
This prevents every route from re-implementing the same pattern.
|
|
||||||
|
|
||||||
Integrates with `HttpRouter.middleware` to enforce auth consistently.
|
|
||||||
|
|
||||||
## Suggested layer graph
|
|
||||||
|
|
||||||
```text
|
|
||||||
ServerSecretStore
|
|
||||||
├─> BootstrapCredentialService
|
|
||||||
├─> BrowserSessionCookieCodec
|
|
||||||
└─> SessionCredentialService
|
|
||||||
|
|
||||||
ServerAuthPolicy
|
|
||||||
├─> BootstrapCredentialService
|
|
||||||
├─> SessionCredentialService
|
|
||||||
└─> ServerAuth
|
|
||||||
|
|
||||||
ServerAuth
|
|
||||||
└─> AuthRouteGuards
|
|
||||||
```
|
|
||||||
|
|
||||||
Layer naming should follow existing repo style:
|
|
||||||
|
|
||||||
- `ServerSecretStoreLive`
|
|
||||||
- `BootstrapCredentialServiceLive`
|
|
||||||
- `SessionCredentialServiceLive`
|
|
||||||
- `ServerAuthPolicyLive`
|
|
||||||
- `ServerAuthLive`
|
|
||||||
- `AuthRouteGuardsLive`
|
|
||||||
|
|
||||||
## High-level implementation examples
|
|
||||||
|
|
||||||
### Example: WebSocket upgrade auth
|
|
||||||
|
|
||||||
Current state:
|
|
||||||
|
|
||||||
- `authToken` query param is checked in [`ws.ts`](../apps/server/src/ws.ts)
|
|
||||||
|
|
||||||
Target shape:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
const websocketUpgradeAuth = HttpMiddleware.make((httpApp) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
||||||
const serverAuth = yield* ServerAuth;
|
|
||||||
yield* serverAuth.authenticateWebSocketUpgrade(request);
|
|
||||||
return yield* httpApp;
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
Then the `/ws` route becomes:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
export const websocketRpcRouteLayer = HttpRouter.add(
|
|
||||||
"GET",
|
|
||||||
"/ws",
|
|
||||||
rpcWebSocketHttpEffect.pipe(
|
|
||||||
websocketUpgradeAuth,
|
|
||||||
Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
This keeps the route itself declarative and makes auth compose like normal HTTP middleware.
|
|
||||||
|
|
||||||
### Example: authenticated HTTP route
|
|
||||||
|
|
||||||
For routes like attachments or project favicon:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
const authenticatedRoute = (routeClass: RouteAuthClass) =>
|
|
||||||
HttpMiddleware.make((httpApp) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
||||||
const serverAuth = yield* ServerAuth;
|
|
||||||
yield* serverAuth.authenticateHttpRequest(request, routeClass);
|
|
||||||
return yield* httpApp;
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
Then:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
export const attachmentsRouteLayer = HttpRouter.add(
|
|
||||||
"GET",
|
|
||||||
`${ATTACHMENTS_ROUTE_PREFIX}/*`,
|
|
||||||
serveAttachment.pipe(
|
|
||||||
authenticatedRoute(RouteAuthClass.Authenticated),
|
|
||||||
Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
### Example: desktop bootstrap exchange
|
|
||||||
|
|
||||||
The desktop shell launches the local server and gets a short-lived bootstrap grant through a trusted side channel.
|
|
||||||
|
|
||||||
That grant is then exchanged for a browser cookie session when the renderer loads.
|
|
||||||
|
|
||||||
Sketch:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
const pairDesktopRenderer = Effect.gen(function* () {
|
|
||||||
const bootstrapService = yield* BootstrapCredentialService;
|
|
||||||
const credential = yield* bootstrapService.issueDesktopBootstrap({
|
|
||||||
audience: "desktop-renderer",
|
|
||||||
ttlMs: 30_000,
|
|
||||||
});
|
|
||||||
return credential;
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
The renderer then calls a bootstrap endpoint and receives a cookie session. The bootstrap credential is consumed and becomes invalid.
|
|
||||||
|
|
||||||
### Example: one-time pairing URL
|
|
||||||
|
|
||||||
For browser-driven pairing:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
const createPairingToken = Effect.gen(function* () {
|
|
||||||
const bootstrapService = yield* BootstrapCredentialService;
|
|
||||||
return yield* bootstrapService.issueOneTimeToken({
|
|
||||||
ttlMs: 5 * 60_000,
|
|
||||||
audience: "browser",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
The server can emit a pairing URL where the token lives in the URL fragment so it is not automatically sent to the server before the client explicitly exchanges it.
|
|
||||||
|
|
||||||
## Sequence diagrams
|
|
||||||
|
|
||||||
These flows are meant to anchor the auth model in concrete user journeys.
|
|
||||||
|
|
||||||
The important invariant across all of them is:
|
|
||||||
|
|
||||||
- access method is not the auth method
|
|
||||||
- launch method is not the auth method
|
|
||||||
- bootstrap credential is not the session credential
|
|
||||||
|
|
||||||
### Normal desktop user
|
|
||||||
|
|
||||||
This is the default desktop-managed local flow.
|
|
||||||
|
|
||||||
The desktop shell is trusted to bootstrap the local renderer, but the renderer should still exchange that one-time bootstrap grant for a normal browser session cookie.
|
|
||||||
|
|
||||||
```text
|
|
||||||
Participants:
|
|
||||||
DesktopMain = Electron main
|
|
||||||
SecretStore = secure local secret backend
|
|
||||||
T3Server = local backend child process
|
|
||||||
Frontend = desktop renderer
|
|
||||||
|
|
||||||
DesktopMain -> SecretStore : getOrCreate("server-signing-key")
|
|
||||||
SecretStore --> DesktopMain : signing key available
|
|
||||||
|
|
||||||
DesktopMain -> T3Server : spawn server (--bootstrap-fd ...)
|
|
||||||
DesktopMain -> T3Server : send desktop bootstrap envelope
|
|
||||||
note over T3Server : policy = DesktopManagedLocalPolicy
|
|
||||||
note over T3Server : allowed pairing = desktop-bootstrap only
|
|
||||||
|
|
||||||
Frontend -> DesktopMain : request local bootstrap grant
|
|
||||||
DesktopMain --> Frontend : short-lived desktop bootstrap grant
|
|
||||||
|
|
||||||
Frontend -> T3Server : POST /api/auth/bootstrap
|
|
||||||
T3Server -> T3Server : validate desktop bootstrap grant
|
|
||||||
T3Server -> T3Server : create browser session
|
|
||||||
T3Server --> Frontend : Set-Cookie: session=...
|
|
||||||
|
|
||||||
Frontend -> T3Server : GET /ws + authenticated cookie
|
|
||||||
T3Server -> T3Server : validate cookie session
|
|
||||||
T3Server --> Frontend : websocket accepted
|
|
||||||
```
|
|
||||||
|
|
||||||
### `npx t3` user
|
|
||||||
|
|
||||||
This is the standalone local server flow.
|
|
||||||
|
|
||||||
There is no trusted desktop shell here, so pairing should be explicit.
|
|
||||||
|
|
||||||
```text
|
|
||||||
Participants:
|
|
||||||
UserShell = npx t3 launcher
|
|
||||||
T3Server = standalone local server
|
|
||||||
Browser = browser tab
|
|
||||||
|
|
||||||
UserShell -> T3Server : start server
|
|
||||||
T3Server -> T3Server : getOrCreate("server-signing-key")
|
|
||||||
note over T3Server : policy = LoopbackBrowserPolicy
|
|
||||||
|
|
||||||
UserShell -> T3Server : issue one-time pairing token
|
|
||||||
T3Server --> UserShell : pairing URL or pairing token
|
|
||||||
|
|
||||||
UserShell --> Browser : open /pair?token=...
|
|
||||||
|
|
||||||
Browser -> T3Server : GET /pair?token=...
|
|
||||||
T3Server -> T3Server : validate one-time token
|
|
||||||
T3Server -> T3Server : create browser session
|
|
||||||
T3Server --> Browser : Set-Cookie: session=...
|
|
||||||
T3Server --> Browser : redirect to app
|
|
||||||
|
|
||||||
Browser -> T3Server : GET /ws + authenticated cookie
|
|
||||||
T3Server --> Browser : websocket accepted
|
|
||||||
```
|
|
||||||
|
|
||||||
### Phone user with tunneled host
|
|
||||||
|
|
||||||
This is the explicit remote access flow for a browser on another device.
|
|
||||||
|
|
||||||
The tunnel only provides reachability. It must not imply trust.
|
|
||||||
|
|
||||||
Recommended UX:
|
|
||||||
|
|
||||||
- desktop shows a QR code
|
|
||||||
- desktop also shows a copyable pairing URL
|
|
||||||
- if the phone opens the host URL without a valid token, the server should render a login or pairing screen rather than granting access
|
|
||||||
|
|
||||||
```text
|
|
||||||
Participants:
|
|
||||||
DesktopUser = user at the host machine
|
|
||||||
DesktopMain = desktop app
|
|
||||||
Tunnel = tunnel provider
|
|
||||||
T3Server = T3 server
|
|
||||||
PhoneBrowser = mobile browser
|
|
||||||
|
|
||||||
DesktopUser -> DesktopMain : enable remote access via tunnel
|
|
||||||
DesktopMain -> T3Server : switch policy to RemoteReachablePolicy
|
|
||||||
DesktopMain -> Tunnel : publish local T3 endpoint
|
|
||||||
Tunnel --> DesktopMain : public https/wss URL
|
|
||||||
|
|
||||||
DesktopMain -> T3Server : issue one-time pairing token
|
|
||||||
T3Server --> DesktopMain : pairing token
|
|
||||||
DesktopMain -> DesktopUser : show QR code / shareable URL
|
|
||||||
|
|
||||||
DesktopUser -> PhoneBrowser : scan QR / open URL
|
|
||||||
PhoneBrowser -> Tunnel : GET https://public-host/pair?token=...
|
|
||||||
Tunnel -> T3Server : forward request
|
|
||||||
T3Server -> T3Server : validate one-time token
|
|
||||||
T3Server -> T3Server : create mobile browser session
|
|
||||||
T3Server --> PhoneBrowser : Set-Cookie: session=...
|
|
||||||
T3Server --> PhoneBrowser : redirect to app
|
|
||||||
|
|
||||||
PhoneBrowser -> Tunnel : GET /ws + authenticated cookie
|
|
||||||
Tunnel -> T3Server : forward websocket upgrade
|
|
||||||
T3Server --> PhoneBrowser : websocket accepted
|
|
||||||
```
|
|
||||||
|
|
||||||
### Phone user with private network
|
|
||||||
|
|
||||||
This is operationally similar to the tunnel flow, but the access endpoint is on a private network such as Tailscale.
|
|
||||||
|
|
||||||
The auth flow should stay the same.
|
|
||||||
|
|
||||||
```text
|
|
||||||
Participants:
|
|
||||||
DesktopUser = user at the host machine
|
|
||||||
T3Server = T3 server
|
|
||||||
PrivateNet = tailscale / private LAN
|
|
||||||
PhoneBrowser = mobile browser
|
|
||||||
|
|
||||||
DesktopUser -> T3Server : enable private-network access
|
|
||||||
T3Server -> T3Server : switch policy to RemoteReachablePolicy
|
|
||||||
DesktopUser -> T3Server : issue one-time pairing token
|
|
||||||
T3Server --> DesktopUser : pairing URL / QR
|
|
||||||
|
|
||||||
DesktopUser -> PhoneBrowser : open private-network URL
|
|
||||||
PhoneBrowser -> PrivateNet : GET http(s)://private-host/pair?token=...
|
|
||||||
PrivateNet -> T3Server : route request
|
|
||||||
T3Server -> T3Server : validate one-time token
|
|
||||||
T3Server -> T3Server : create mobile browser session
|
|
||||||
T3Server --> PhoneBrowser : Set-Cookie: session=...
|
|
||||||
T3Server --> PhoneBrowser : redirect to app
|
|
||||||
|
|
||||||
PhoneBrowser -> PrivateNet : GET /ws + authenticated cookie
|
|
||||||
PrivateNet -> T3Server : websocket upgrade
|
|
||||||
T3Server --> PhoneBrowser : websocket accepted
|
|
||||||
```
|
|
||||||
|
|
||||||
### Desktop user adding new SSH hosts
|
|
||||||
|
|
||||||
SSH should be treated as launch and reachability plumbing, not as the long-term auth model.
|
|
||||||
|
|
||||||
The desktop app uses SSH to start or reach the remote server, then the renderer pairs against that server using the same bootstrap/session split as every other environment.
|
|
||||||
|
|
||||||
```text
|
|
||||||
Participants:
|
|
||||||
DesktopUser = local desktop user
|
|
||||||
DesktopMain = desktop app
|
|
||||||
SSH = ssh transport/session
|
|
||||||
RemoteHost = remote machine
|
|
||||||
RemoteT3 = remote T3 server
|
|
||||||
Frontend = desktop renderer
|
|
||||||
|
|
||||||
DesktopUser -> DesktopMain : add SSH host
|
|
||||||
DesktopMain -> SSH : connect to remote host
|
|
||||||
SSH -> RemoteHost : probe environment / verify t3 availability
|
|
||||||
DesktopMain -> SSH : run remote launch command
|
|
||||||
SSH -> RemoteHost : t3 remote launch --json
|
|
||||||
RemoteHost -> RemoteT3 : start or reuse server
|
|
||||||
RemoteT3 --> RemoteHost : port + environment metadata
|
|
||||||
RemoteHost --> SSH : launch result JSON
|
|
||||||
SSH --> DesktopMain : remote server details
|
|
||||||
|
|
||||||
DesktopMain -> SSH : establish local port forward
|
|
||||||
SSH --> DesktopMain : localhost:FORWARDED_PORT ready
|
|
||||||
|
|
||||||
note over RemoteT3 : policy = RemoteReachablePolicy
|
|
||||||
note over DesktopMain,RemoteT3 : desktop may use a trusted bootstrap flow here
|
|
||||||
|
|
||||||
Frontend -> DesktopMain : request bootstrap for selected environment
|
|
||||||
DesktopMain --> Frontend : short-lived bootstrap grant
|
|
||||||
|
|
||||||
Frontend -> RemoteT3 : POST /api/auth/bootstrap via forwarded port
|
|
||||||
RemoteT3 -> RemoteT3 : validate bootstrap grant
|
|
||||||
RemoteT3 -> RemoteT3 : create browser session
|
|
||||||
RemoteT3 --> Frontend : Set-Cookie: session=...
|
|
||||||
|
|
||||||
Frontend -> RemoteT3 : GET /ws + authenticated cookie
|
|
||||||
RemoteT3 --> Frontend : websocket accepted
|
|
||||||
```
|
|
||||||
|
|
||||||
## Storage decisions
|
|
||||||
|
|
||||||
### Server secrets
|
|
||||||
|
|
||||||
Use a `ServerSecretStore` abstraction.
|
|
||||||
|
|
||||||
Preferred order (use a layer for each, resolve on startup):
|
|
||||||
|
|
||||||
1. OS secure storage if available
|
|
||||||
2. hardened filesystem fallback if not
|
|
||||||
|
|
||||||
The filesystem fallback should store only opaque signing material with strict file permissions. It should not store user passwords or reusable third-party credentials.
|
|
||||||
|
|
||||||
### Client credentials
|
|
||||||
|
|
||||||
Client-side credential persistence should prefer secure storage when available:
|
|
||||||
|
|
||||||
- desktop: OS keychain / secure store
|
|
||||||
- mobile: platform secure storage
|
|
||||||
- browser: cookie session for browser auth
|
|
||||||
|
|
||||||
This concern should stay in the client shell/runtime layer, not the server auth layer.
|
|
||||||
|
|
||||||
## What to build now
|
|
||||||
|
|
||||||
These are the parts worth building before remote environments ship:
|
|
||||||
|
|
||||||
1. `ServerAuth` service boundary.
|
|
||||||
2. route classification and route guards.
|
|
||||||
3. `ServerSecretStore` abstraction.
|
|
||||||
4. bootstrap vs session credential split.
|
|
||||||
5. browser session cookie codec as one session method.
|
|
||||||
6. explicit auth capabilities/config surfaced in contracts.
|
|
||||||
|
|
||||||
Even if only one pairing flow is used initially, these seams will keep future remote and mobile work contained.
|
|
||||||
|
|
||||||
## What to add as part of first remote-capable auth
|
|
||||||
|
|
||||||
1. Browser pairing flow using one-time bootstrap token and cookie session.
|
|
||||||
2. Desktop-managed auto-bootstrap for the local desktop-managed environment.
|
|
||||||
3. Auth-required defaults for any non-loopback or explicitly published server.
|
|
||||||
4. Explicit environment auth policy selection instead of scattered `if (host !== localhost)` checks.
|
|
||||||
|
|
||||||
## What to defer
|
|
||||||
|
|
||||||
- passkeys / WebAuthn
|
|
||||||
- iCloud Keychain / Face ID-specific UX
|
|
||||||
- multi-user permissions
|
|
||||||
- collaboration roles
|
|
||||||
- OAuth / SSO
|
|
||||||
- polished session management UI
|
|
||||||
- complex device approval flows
|
|
||||||
|
|
||||||
These can all sit on top of the same bootstrap/session/service split.
|
|
||||||
|
|
||||||
## Relationship to future remote environments
|
|
||||||
|
|
||||||
Remote access is one reason this auth model matters, but the auth model should not be remote-shaped.
|
|
||||||
|
|
||||||
Keep the design focused on:
|
|
||||||
|
|
||||||
- one T3 server
|
|
||||||
- one auth policy
|
|
||||||
- multiple credential types
|
|
||||||
- multiple future access methods
|
|
||||||
|
|
||||||
That keeps the server auth model stable even as access methods expand later.
|
|
||||||
|
|
||||||
## Recommended implementation order
|
|
||||||
|
|
||||||
### Phase 1
|
|
||||||
|
|
||||||
- Introduce route auth classes.
|
|
||||||
- Add `ServerAuth` and `AuthRouteGuards`.
|
|
||||||
- Move existing `authToken` check behind `ServerAuth`.
|
|
||||||
- Require auth for all privileged HTTP routes as well as WebSocket.
|
|
||||||
|
|
||||||
### Phase 2
|
|
||||||
|
|
||||||
- Add `ServerSecretStore` service with platform-specific layer implementations.
|
|
||||||
- `layerOSXKeychain`, `layer
|
|
||||||
- Add bootstrap/session split.
|
|
||||||
- Add browser session cookie support.
|
|
||||||
- Add one-time bootstrap exchange endpoint.
|
|
||||||
|
|
||||||
### Phase 3
|
|
||||||
|
|
||||||
- Add desktop bootstrap flow on top of the same services.
|
|
||||||
- Make desktop-managed local environments default to bootstrap-only pairing.
|
|
||||||
- Surface auth capabilities in shared contracts and renderer bootstrap.
|
|
||||||
|
|
||||||
### Phase 4
|
|
||||||
|
|
||||||
- Add non-browser bearer session support if mobile/native needs it.
|
|
||||||
- Add richer policy modes for remote-reachable environments.
|
|
||||||
|
|
||||||
## Acceptance criteria
|
|
||||||
|
|
||||||
- No privileged HTTP or WebSocket path bypasses auth policy.
|
|
||||||
- Local desktop-managed flows still avoid a visible login screen.
|
|
||||||
- Non-loopback or published environments require explicit authenticated pairing by default.
|
|
||||||
- Bootstrap and session credentials are distinct in code and in behavior.
|
|
||||||
- Auth logic is centralized in Effect services/layers rather than route-local branching.
|
|
||||||
@@ -1,89 +0,0 @@
|
|||||||
# Replace React Query With AtomRpc + Atom State
|
|
||||||
|
|
||||||
## Summary
|
|
||||||
- Use `effect/unstable/reactivity/AtomRpc` over the existing `WsRpcGroup`; stop wrapping RPC in promises via [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts) and [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts).
|
|
||||||
- Keep Zustand for orchestration read model and UI state.
|
|
||||||
- Keep a narrow `desktopBridge` adapter for dialogs, menus, external links, theme, and updater APIs.
|
|
||||||
- Do not introduce Suspense in this migration. Atom-backed hooks should keep returning `data`, `error`, `isLoading|isPending`, `refresh`, and `mutateAsync`-style surfaces so component churn stays low.
|
|
||||||
|
|
||||||
## Target Architecture
|
|
||||||
- Extract the websocket `RpcClient.Protocol` layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) into `rpc/protocol.ts`.
|
|
||||||
- Define one `AtomRpc.Service` for `WsRpcGroup` in `rpc/client.ts`.
|
|
||||||
- Add `rpc/invalidation.ts` with explicit scoped invalidation keys: `git:${cwd}`, `project:${cwd}`, `checkpoint:${threadId}`, `server-config`.
|
|
||||||
- Add `platform/desktopBridge.ts` as the only browser/desktop facade.
|
|
||||||
- Remove from web by the end: [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts), [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts), [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts), [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx), [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts), and all `*ReactQuery.ts` modules.
|
|
||||||
|
|
||||||
## Phase 1: Infrastructure First
|
|
||||||
1. Extract the shared websocket RPC protocol layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) without changing behavior.
|
|
||||||
2. Build the AtomRpc client on top of that layer.
|
|
||||||
3. Add one temporary `runRpc` helper for imperative handlers that still want `Promise` ergonomics; it must call the AtomRpc service directly and must not reintroduce a facade object.
|
|
||||||
4. Replace manual registry wiring with one app-level registry provider based on `@effect/atom-react`.
|
|
||||||
5. Land this as a no-behavior-change PR.
|
|
||||||
|
|
||||||
## Phase 2: Replace `wsNativeApi`-Owned Push State
|
|
||||||
1. Migrate welcome/config/provider/settings state first, because it is already atom-shaped and is the lowest-risk way to delete `wsNativeApi` responsibilities.
|
|
||||||
2. Replace [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts) with `rpc/serverState.ts`, updated directly from `subscribeServerLifecycle` and `subscribeServerConfig`.
|
|
||||||
3. Keep the current hook names for one PR: `useServerConfig`, `useServerSettings`, `useServerProviders`, `useServerKeybindings`, `useServerWelcomeSubscription`, `useServerConfigUpdatedSubscription`.
|
|
||||||
4. Move bootstrap side effects out of [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx) into a new root bootstrap component mounted from [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
|
|
||||||
5. Delete the `server.getConfig()` fallback logic from [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts); snapshot fetch now lives beside the stream atoms.
|
|
||||||
|
|
||||||
## Phase 3: Replace React Query Domain By Domain
|
|
||||||
1. Replace [gitReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/gitReactQuery.ts) first.
|
|
||||||
2. Add `rpc/gitAtoms.ts` and `rpc/useGit.ts` with `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, and `useGitMutation`.
|
|
||||||
3. Mutation settlement must invalidate scoped keys, not a global cache. `checkout`, `pull`, `init`, `createWorktree`, `removeWorktree`, `preparePullRequestThread`, and stacked actions invalidate `git:${cwd}`. Worktree create/remove also invalidates `project:${cwd}`.
|
|
||||||
4. Replace [projectReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/projectReactQuery.ts) second. `useProjectSearchEntries` must preserve current “keep previous results while loading” behavior.
|
|
||||||
5. Replace [providerReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/providerReactQuery.ts) third. Preserve current checkpoint error normalization and retry/backoff semantics inside the atom effect. Invalidate by `checkpoint:${threadId}`.
|
|
||||||
6. Defer the desktop updater until the last phase.
|
|
||||||
|
|
||||||
## Phase 4: Move Root Invalidation Off `queryClient`
|
|
||||||
1. In [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx), remove `QueryClient` usage and replace the throttled `invalidateQueries` block with throttled invalidation helpers.
|
|
||||||
2. Keep Zustand orchestration/event application unchanged.
|
|
||||||
3. Map current effects exactly:
|
|
||||||
- git or checkpoint-affecting orchestration events touch `checkpoint:${threadId}`
|
|
||||||
- file creation/deletion/restoration touches `project:${cwd}`
|
|
||||||
- config-affecting server events touch `server-config`
|
|
||||||
|
|
||||||
## Phase 5: Remove Imperative `NativeApi` Usage
|
|
||||||
1. Create narrow modules instead of a replacement mega-facade:
|
|
||||||
- `rpc/orchestrationActions.ts`
|
|
||||||
- `rpc/terminalActions.ts`
|
|
||||||
- `rpc/gitActions.ts`
|
|
||||||
- `rpc/projectActions.ts`
|
|
||||||
- `platform/desktopBridge.ts`
|
|
||||||
2. Migrate direct [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) callers by domain, not file-by-file: git-heavy components first, then orchestration/thread actions, then shell/dialog helpers.
|
|
||||||
3. After the last caller is gone, delete [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) and the `window.nativeApi` fallback entirely.
|
|
||||||
4. In the final cleanup PR, remove `NativeApi` from [ipc.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/packages/contracts/src/ipc.ts) if nothing outside web still needs it.
|
|
||||||
|
|
||||||
## Phase 6: Remove React Query Completely
|
|
||||||
1. Delete `@tanstack/react-query` from `apps/web/package.json`.
|
|
||||||
2. Remove `QueryClientProvider` and router context from [router.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/router.ts) and [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
|
|
||||||
3. Replace [desktopUpdateReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/desktopUpdateReactQuery.ts) with a writable atom plus `desktopBridge.onUpdateState`.
|
|
||||||
4. Delete the old query-option tests.
|
|
||||||
|
|
||||||
## Public Interfaces And Types
|
|
||||||
- Preserve the current server-state hook names during the transition.
|
|
||||||
- Add permanent domain hooks: `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, `useProjectSearchEntries`, `useCheckpointDiff`, `useDesktopUpdateState`.
|
|
||||||
- Do not expose raw AtomRpc clients to components.
|
|
||||||
- Do not add Suspense as part of this migration.
|
|
||||||
- Final boundary is direct RPC for server features plus `desktopBridge` for local desktop features.
|
|
||||||
|
|
||||||
## Test Plan
|
|
||||||
- Add unit tests for `rpc/serverState.ts`: snapshot bootstrapping, stream replay, provider/settings updates.
|
|
||||||
- Add unit tests for git/project/checkpoint hooks: loading, error mapping, retry behavior, invalidation, keep-previous-result behavior.
|
|
||||||
- Update the browser harness in [wsRpcHarness.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/test/wsRpcHarness.ts) to assert direct RPC + atom behavior instead of `__resetNativeApiForTests`.
|
|
||||||
- Replace [wsNativeApi.test.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.test.ts), `gitReactQuery.test.ts`, `providerReactQuery.test.ts`, and `desktopUpdateReactQuery.test.ts` with equivalent atom-backed coverage.
|
|
||||||
- Acceptance scenarios:
|
|
||||||
- welcome still bootstraps snapshot and navigation
|
|
||||||
- keybindings toast still responds to config stream updates
|
|
||||||
- git status/branches refresh after checkout/pull/worktree actions
|
|
||||||
- PR resolve dialog keeps cached result while typing
|
|
||||||
- `@` path search refreshes after file mutations and orchestration events
|
|
||||||
- diff panel refreshes when checkpoints arrive
|
|
||||||
- desktop updater still reflects push events and button actions
|
|
||||||
|
|
||||||
## Assumptions And Defaults
|
|
||||||
- Zustand stays in scope; only `react-query` is being removed.
|
|
||||||
- `desktopBridge` remains the only non-RPC boundary.
|
|
||||||
- The migration lands as 5-6 small PRs, each green independently.
|
|
||||||
- Invalidations are explicit and scoped; do not recreate a global cache client abstraction.
|
|
||||||
- Orchestration recovery/order logic stays as-is; only the data-fetching and mutation layer changes.
|
|
||||||
@@ -7,7 +7,7 @@
|
|||||||
|
|
||||||
## Project Snapshot
|
## Project Snapshot
|
||||||
|
|
||||||
T3 Code is a minimal web GUI for using coding agents like Codex and Claude.
|
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
|
||||||
|
|
||||||
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
|
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
|
||||||
|
|
||||||
|
|||||||
@@ -1,43 +1,19 @@
|
|||||||
# T3 Code
|
# T3 Code
|
||||||
|
|
||||||
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
|
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
|
||||||
|
|
||||||
## Installation
|
## How to use
|
||||||
|
|
||||||
> [!WARNING]
|
> [!WARNING]
|
||||||
> T3 Code currently supports Codex and Claude.
|
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
|
||||||
> Install and authenticate at least one provider before use:
|
|
||||||
>
|
|
||||||
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
|
|
||||||
> - Claude: install Claude Code and run `claude auth login`
|
|
||||||
|
|
||||||
### Run without installing
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npx t3
|
npx t3
|
||||||
```
|
```
|
||||||
|
|
||||||
### Desktop app
|
You can also just install the desktop app. It's cooler.
|
||||||
|
|
||||||
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
|
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
|
||||||
|
|
||||||
#### Windows (`winget`)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
winget install T3Tools.T3Code
|
|
||||||
```
|
|
||||||
|
|
||||||
#### macOS (Homebrew)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
brew install --cask t3-code
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Arch Linux (AUR)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
yay -S t3code-bin
|
|
||||||
```
|
|
||||||
|
|
||||||
## Some notes
|
## Some notes
|
||||||
|
|
||||||
@@ -45,8 +21,6 @@ We are very very early in this project. Expect bugs.
|
|||||||
|
|
||||||
We are not accepting contributions yet.
|
We are not accepting contributions yet.
|
||||||
|
|
||||||
Observability guide: [docs/observability.md](./docs/observability.md)
|
|
||||||
|
|
||||||
## If you REALLY want to contribute still.... read this first
|
## If you REALLY want to contribute still.... read this first
|
||||||
|
|
||||||
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
|
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
|
||||||
|
|||||||
@@ -1,87 +1,65 @@
|
|||||||
# Remote Access
|
# Remote Access Setup
|
||||||
|
|
||||||
Use this when you want to connect to a T3 Code server from another device such as a phone, tablet, or separate desktop app.
|
Use this when you want to open T3 Code from another device (phone, tablet, another laptop).
|
||||||
|
|
||||||
## Recommended Setup
|
## CLI ↔ Env option map
|
||||||
|
|
||||||
Use a trusted private network that meshes your devices together, such as a tailnet.
|
The T3 Code CLI accepts the following configuration options, available either as CLI flags or environment variables:
|
||||||
|
|
||||||
That gives you:
|
| CLI flag | Env var | Notes |
|
||||||
|
| ----------------------- | --------------------- | ---------------------------------- |
|
||||||
|
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
|
||||||
|
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
|
||||||
|
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
|
||||||
|
| `--state-dir <path>` | `T3CODE_STATE_DIR` | State 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. |
|
||||||
|
|
||||||
- a stable address to connect to
|
> TIP: Use the `--help` flag to see all available options and their descriptions.
|
||||||
- transport security at the network layer
|
|
||||||
- less exposure than opening the server to the public internet
|
|
||||||
|
|
||||||
## Enabling Network Access
|
## Security First
|
||||||
|
|
||||||
There are two ways to expose your server for remote connections: from the desktop app or from the CLI.
|
- Always set `--auth-token` before exposing the server outside localhost.
|
||||||
|
- Treat the token like a password.
|
||||||
|
- Prefer binding to trusted interfaces (LAN IP or Tailnet IP) instead of opening all interfaces unless needed.
|
||||||
|
|
||||||
### Option 1: Desktop App
|
## 1) Build + run server for remote access
|
||||||
|
|
||||||
If you are already running the desktop app and want to make it reachable from other devices:
|
Remote access should use the built web app (not local Vite redirect mode).
|
||||||
|
|
||||||
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
|
```bash
|
||||||
npx t3 serve --host "$(tailscale ip -4)"
|
bun run build
|
||||||
|
TOKEN="$(openssl rand -hex 24)"
|
||||||
|
bun run --cwd apps/server start -- --host 0.0.0.0 --port 3773 --auth-token "$TOKEN" --no-browser
|
||||||
```
|
```
|
||||||
|
|
||||||
`t3 serve` starts the server without opening a browser and prints:
|
Then open on your phone:
|
||||||
|
|
||||||
- a connection string
|
`http://<your-machine-ip>:3773`
|
||||||
- a pairing token
|
|
||||||
- a pairing URL
|
|
||||||
- a QR code for the pairing URL
|
|
||||||
|
|
||||||
From there, connect from another device in either of these ways:
|
Example:
|
||||||
|
|
||||||
- scan the QR code on your phone
|
`http://192.168.1.42:3773`
|
||||||
- in the desktop app, enter the full pairing URL
|
|
||||||
- in the desktop app, enter the host and token separately
|
|
||||||
|
|
||||||
Use `t3 serve --help` for the full flag reference. It supports the same general startup options as the normal server command, including an optional `cwd` argument.
|
Notes:
|
||||||
|
|
||||||
> Note
|
- `--host 0.0.0.0` listens on all IPv4 interfaces.
|
||||||
> The GUIs do not currently support adding projects on remote environments.
|
- `--no-browser` prevents local auto-open, which is usually better for headless/remote sessions.
|
||||||
> For now, use `t3 project ...` on the server machine instead.
|
- Ensure your OS firewall allows inbound TCP on the selected port.
|
||||||
> Full GUI support for remote project management is coming soon.
|
|
||||||
|
|
||||||
## How Pairing Works
|
## 2) Tailnet / Tailscale access
|
||||||
|
|
||||||
The remote device does not need a long-lived secret up front.
|
If you use Tailscale, you can bind directly to your Tailnet address.
|
||||||
|
|
||||||
Instead:
|
```bash
|
||||||
|
TAILNET_IP="$(tailscale ip -4)"
|
||||||
|
TOKEN="$(openssl rand -hex 24)"
|
||||||
|
bun run --cwd apps/server start -- --host "$(tailscale ip -4)" --port 3773 --auth-token "$TOKEN" --no-browser
|
||||||
|
```
|
||||||
|
|
||||||
1. `t3 serve` issues a one-time owner pairing token.
|
Open from any device in your tailnet:
|
||||||
2. The remote device exchanges that token with the server.
|
|
||||||
3. The server creates an authenticated session for that device.
|
|
||||||
|
|
||||||
After pairing, future access is session-based. You do not need to keep reusing the original token unless you are pairing a new device.
|
`http://<tailnet-ip>:3773`
|
||||||
|
|
||||||
## Managing Access Later
|
You can also bind `--host 0.0.0.0` and connect through the Tailnet IP, but binding directly to the Tailnet IP limits exposure.
|
||||||
|
|
||||||
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",
|
"name": "@t3tools/desktop",
|
||||||
"version": "0.0.15",
|
"version": "0.0.10",
|
||||||
"private": true,
|
"private": true,
|
||||||
"main": "dist-electron/main.js",
|
"main": "dist-electron/main.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -24,7 +24,8 @@
|
|||||||
"@types/node": "catalog:",
|
"@types/node": "catalog:",
|
||||||
"tsdown": "catalog:",
|
"tsdown": "catalog:",
|
||||||
"typescript": "catalog:",
|
"typescript": "catalog:",
|
||||||
"vitest": "catalog:"
|
"vitest": "catalog:",
|
||||||
|
"wait-on": "^8.0.2"
|
||||||
},
|
},
|
||||||
"productName": "T3 Code (Alpha)"
|
"productName": "T3 Code (Alpha)"
|
||||||
}
|
}
|
||||||
@@ -1,39 +1,27 @@
|
|||||||
import { spawn, spawnSync } from "node:child_process";
|
import { spawn, spawnSync } from "node:child_process";
|
||||||
import { watch } from "node:fs";
|
import { watch } from "node:fs";
|
||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
|
import waitOn from "wait-on";
|
||||||
|
|
||||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||||
import { waitForResources } from "./wait-for-resources.mjs";
|
|
||||||
|
|
||||||
const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
|
|
||||||
if (!devServerUrl) {
|
|
||||||
throw new Error("VITE_DEV_SERVER_URL is required for desktop development.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const devServer = new URL(devServerUrl);
|
|
||||||
const port = Number.parseInt(devServer.port, 10);
|
|
||||||
if (!Number.isInteger(port) || port <= 0) {
|
|
||||||
throw new Error(`VITE_DEV_SERVER_URL must include an explicit port: ${devServerUrl}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
|
||||||
|
const devServerUrl = `http://localhost:${port}`;
|
||||||
const requiredFiles = [
|
const requiredFiles = [
|
||||||
"dist-electron/main.js",
|
"dist-electron/main.js",
|
||||||
"dist-electron/preload.js",
|
"dist-electron/preload.js",
|
||||||
"../server/dist/bin.mjs",
|
"../server/dist/index.mjs",
|
||||||
];
|
];
|
||||||
const watchedDirectories = [
|
const watchedDirectories = [
|
||||||
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
|
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
|
||||||
{ directory: "../server/dist", files: new Set(["bin.mjs"]) },
|
{ directory: "../server/dist", files: new Set(["index.mjs"]) },
|
||||||
];
|
];
|
||||||
const forcedShutdownTimeoutMs = 1_500;
|
const forcedShutdownTimeoutMs = 1_500;
|
||||||
const restartDebounceMs = 120;
|
const restartDebounceMs = 120;
|
||||||
const childTreeGracePeriodMs = 1_200;
|
const childTreeGracePeriodMs = 1_200;
|
||||||
|
|
||||||
await waitForResources({
|
await waitOn({
|
||||||
baseDir: desktopDir,
|
resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
|
||||||
files: requiredFiles,
|
|
||||||
tcpHost: devServer.hostname,
|
|
||||||
tcpPort: port,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const childEnv = { ...process.env };
|
const childEnv = { ...process.env };
|
||||||
@@ -72,7 +60,10 @@ function startApp() {
|
|||||||
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
|
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
|
||||||
{
|
{
|
||||||
cwd: desktopDir,
|
cwd: desktopDir,
|
||||||
env: childEnv,
|
env: {
|
||||||
|
...childEnv,
|
||||||
|
VITE_DEV_SERVER_URL: devServerUrl,
|
||||||
|
},
|
||||||
stdio: "inherit",
|
stdio: "inherit",
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import { fileURLToPath } from "node:url";
|
|||||||
|
|
||||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||||
const APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
|
const APP_BUNDLE_ID = "com.t3tools.t3code";
|
||||||
const LAUNCHER_VERSION = 1;
|
const LAUNCHER_VERSION = 1;
|
||||||
|
|
||||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||||
|
|||||||
@@ -1,119 +0,0 @@
|
|||||||
import * as FileSystem from "node:fs/promises";
|
|
||||||
import * as Net from "node:net";
|
|
||||||
import * as Path from "node:path";
|
|
||||||
import * as Timers from "node:timers/promises";
|
|
||||||
|
|
||||||
const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"];
|
|
||||||
|
|
||||||
async function fileExists(filePath) {
|
|
||||||
try {
|
|
||||||
await FileSystem.access(filePath);
|
|
||||||
return true;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) {
|
|
||||||
return new Promise((resolveReady) => {
|
|
||||||
const socket = Net.createConnection({ host, port });
|
|
||||||
let settled = false;
|
|
||||||
|
|
||||||
const finish = (ready) => {
|
|
||||||
if (settled) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
settled = true;
|
|
||||||
socket.removeAllListeners();
|
|
||||||
socket.destroy();
|
|
||||||
resolveReady(ready);
|
|
||||||
};
|
|
||||||
|
|
||||||
socket.once("connect", () => {
|
|
||||||
finish(true);
|
|
||||||
});
|
|
||||||
socket.once("timeout", () => {
|
|
||||||
finish(false);
|
|
||||||
});
|
|
||||||
socket.once("error", () => {
|
|
||||||
finish(false);
|
|
||||||
});
|
|
||||||
socket.setTimeout(connectTimeoutMs);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function resolvePendingResources({ baseDir, files, tcpPort, tcpHosts, connectTimeoutMs }) {
|
|
||||||
const pendingFiles = [];
|
|
||||||
|
|
||||||
for (const relativeFilePath of files) {
|
|
||||||
const ready = await fileExists(Path.resolve(baseDir, relativeFilePath));
|
|
||||||
if (!ready) {
|
|
||||||
pendingFiles.push(relativeFilePath);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let tcpReady = false;
|
|
||||||
for (const host of tcpHosts) {
|
|
||||||
tcpReady = await tcpPortIsReady({
|
|
||||||
host,
|
|
||||||
port: tcpPort,
|
|
||||||
connectTimeoutMs,
|
|
||||||
});
|
|
||||||
if (tcpReady) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
pendingFiles,
|
|
||||||
tcpReady,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function waitForResources({
|
|
||||||
baseDir,
|
|
||||||
files = [],
|
|
||||||
intervalMs = 100,
|
|
||||||
timeoutMs = 120_000,
|
|
||||||
tcpHost,
|
|
||||||
tcpPort,
|
|
||||||
connectTimeoutMs = 500,
|
|
||||||
}) {
|
|
||||||
if (!Number.isInteger(tcpPort) || tcpPort <= 0) {
|
|
||||||
throw new TypeError("waitForResources requires a positive integer tcpPort");
|
|
||||||
}
|
|
||||||
|
|
||||||
const startedAt = Date.now();
|
|
||||||
const tcpHosts = tcpHost ? [tcpHost] : defaultTcpHosts;
|
|
||||||
|
|
||||||
while (true) {
|
|
||||||
const { pendingFiles, tcpReady } = await resolvePendingResources({
|
|
||||||
baseDir,
|
|
||||||
files,
|
|
||||||
tcpPort,
|
|
||||||
tcpHosts,
|
|
||||||
connectTimeoutMs,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (pendingFiles.length === 0 && tcpReady) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Date.now() - startedAt >= timeoutMs) {
|
|
||||||
const pendingResources = [];
|
|
||||||
if (!tcpReady) {
|
|
||||||
pendingResources.push(tcpHost ? `tcp:${tcpHost}:${tcpPort}` : `tcp:${tcpPort}`);
|
|
||||||
}
|
|
||||||
for (const filePath of pendingFiles) {
|
|
||||||
pendingResources.push(`file:${filePath}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error(
|
|
||||||
`Timed out waiting for desktop dev resources after ${timeoutMs}ms: ${pendingResources.join(", ")}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
await Timers.setTimeout(intervalMs);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
import { describe, expect, it, vi } from "vitest";
|
|
||||||
|
|
||||||
import { resolveDesktopBackendPort } from "./backendPort";
|
|
||||||
|
|
||||||
describe("resolveDesktopBackendPort", () => {
|
|
||||||
it("returns the starting port when it is available", async () => {
|
|
||||||
const canListenOnHost = vi.fn(async (port: number) => port === 3773);
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
resolveDesktopBackendPort({
|
|
||||||
host: "127.0.0.1",
|
|
||||||
startPort: 3773,
|
|
||||||
canListenOnHost,
|
|
||||||
}),
|
|
||||||
).resolves.toBe(3773);
|
|
||||||
|
|
||||||
expect(canListenOnHost).toHaveBeenCalledTimes(1);
|
|
||||||
expect(canListenOnHost).toHaveBeenCalledWith(3773, "127.0.0.1");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("increments sequentially until it finds an available port", async () => {
|
|
||||||
const canListenOnHost = vi.fn(async (port: number) => port === 3775);
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
resolveDesktopBackendPort({
|
|
||||||
host: "127.0.0.1",
|
|
||||||
startPort: 3773,
|
|
||||||
canListenOnHost,
|
|
||||||
}),
|
|
||||||
).resolves.toBe(3775);
|
|
||||||
|
|
||||||
expect(canListenOnHost.mock.calls).toEqual([
|
|
||||||
[3773, "127.0.0.1"],
|
|
||||||
[3774, "127.0.0.1"],
|
|
||||||
[3775, "127.0.0.1"],
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("fails when the scan range is exhausted", async () => {
|
|
||||||
const canListenOnHost = vi.fn(async () => false);
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
resolveDesktopBackendPort({
|
|
||||||
host: "127.0.0.1",
|
|
||||||
startPort: 65534,
|
|
||||||
maxPort: 65535,
|
|
||||||
canListenOnHost,
|
|
||||||
}),
|
|
||||||
).rejects.toThrow("No desktop backend port is available on 127.0.0.1 between 65534 and 65535");
|
|
||||||
|
|
||||||
expect(canListenOnHost.mock.calls).toEqual([
|
|
||||||
[65534, "127.0.0.1"],
|
|
||||||
[65535, "127.0.0.1"],
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
import * as Effect from "effect/Effect";
|
|
||||||
import { NetService } from "@t3tools/shared/Net";
|
|
||||||
|
|
||||||
export const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
|
|
||||||
const MAX_TCP_PORT = 65_535;
|
|
||||||
|
|
||||||
export interface ResolveDesktopBackendPortOptions {
|
|
||||||
readonly host: string;
|
|
||||||
readonly startPort?: number;
|
|
||||||
readonly maxPort?: number;
|
|
||||||
readonly canListenOnHost?: (port: number, host: string) => Promise<boolean>;
|
|
||||||
}
|
|
||||||
|
|
||||||
const defaultCanListenOnHost = async (port: number, host: string): Promise<boolean> =>
|
|
||||||
Effect.service(NetService).pipe(
|
|
||||||
Effect.flatMap((net) => net.canListenOnHost(port, host)),
|
|
||||||
Effect.provide(NetService.layer),
|
|
||||||
Effect.runPromise,
|
|
||||||
);
|
|
||||||
|
|
||||||
const isValidPort = (port: number): boolean =>
|
|
||||||
Number.isInteger(port) && port >= 1 && port <= MAX_TCP_PORT;
|
|
||||||
|
|
||||||
export async function resolveDesktopBackendPort({
|
|
||||||
host,
|
|
||||||
startPort = DEFAULT_DESKTOP_BACKEND_PORT,
|
|
||||||
maxPort = MAX_TCP_PORT,
|
|
||||||
canListenOnHost = defaultCanListenOnHost,
|
|
||||||
}: ResolveDesktopBackendPortOptions): Promise<number> {
|
|
||||||
if (!isValidPort(startPort)) {
|
|
||||||
throw new Error(`Invalid desktop backend start port: ${startPort}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!isValidPort(maxPort)) {
|
|
||||||
throw new Error(`Invalid desktop backend max port: ${maxPort}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (maxPort < startPort) {
|
|
||||||
throw new Error(`Desktop backend max port ${maxPort} is below start port ${startPort}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Keep desktop startup predictable across app restarts by probing upward from
|
|
||||||
// the same preferred port instead of picking a fresh ephemeral port.
|
|
||||||
for (let port = startPort; port <= maxPort; port += 1) {
|
|
||||||
if (await canListenOnHost(port, host)) {
|
|
||||||
return port;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error(
|
|
||||||
`No desktop backend port is available on ${host} between ${startPort} and ${maxPort}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
import { describe, expect, it, vi } from "vitest";
|
|
||||||
|
|
||||||
import {
|
|
||||||
BackendReadinessAbortedError,
|
|
||||||
isBackendReadinessAborted,
|
|
||||||
waitForHttpReady,
|
|
||||||
} from "./backendReadiness";
|
|
||||||
|
|
||||||
describe("waitForHttpReady", () => {
|
|
||||||
it("returns once the backend reports a successful session endpoint", async () => {
|
|
||||||
const fetchImpl = vi
|
|
||||||
.fn<typeof fetch>()
|
|
||||||
.mockResolvedValueOnce(new Response(null, { status: 503 }))
|
|
||||||
.mockResolvedValueOnce(new Response(null, { status: 200 }));
|
|
||||||
|
|
||||||
await waitForHttpReady("http://127.0.0.1:3773", {
|
|
||||||
fetchImpl,
|
|
||||||
timeoutMs: 1_000,
|
|
||||||
intervalMs: 0,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("retries after a readiness request stalls past the per-request timeout", async () => {
|
|
||||||
const fetchImpl = vi
|
|
||||||
.fn<typeof fetch>()
|
|
||||||
.mockImplementationOnce(
|
|
||||||
(_input, init) =>
|
|
||||||
new Promise((_resolve, reject) => {
|
|
||||||
init?.signal?.addEventListener(
|
|
||||||
"abort",
|
|
||||||
() => {
|
|
||||||
reject(new Error("request timed out"));
|
|
||||||
},
|
|
||||||
{ once: true },
|
|
||||||
);
|
|
||||||
}) as ReturnType<typeof fetch>,
|
|
||||||
)
|
|
||||||
.mockResolvedValueOnce(new Response(null, { status: 200 }));
|
|
||||||
|
|
||||||
await waitForHttpReady("http://127.0.0.1:3773", {
|
|
||||||
fetchImpl,
|
|
||||||
timeoutMs: 100,
|
|
||||||
intervalMs: 0,
|
|
||||||
requestTimeoutMs: 1,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("aborts an in-flight readiness wait", async () => {
|
|
||||||
const controller = new AbortController();
|
|
||||||
const fetchImpl = vi.fn<typeof fetch>().mockImplementation(
|
|
||||||
() =>
|
|
||||||
new Promise((_resolve, reject) => {
|
|
||||||
controller.signal.addEventListener(
|
|
||||||
"abort",
|
|
||||||
() => {
|
|
||||||
reject(new BackendReadinessAbortedError());
|
|
||||||
},
|
|
||||||
{ once: true },
|
|
||||||
);
|
|
||||||
}) as ReturnType<typeof fetch>,
|
|
||||||
);
|
|
||||||
|
|
||||||
const waitPromise = waitForHttpReady("http://127.0.0.1:3773", {
|
|
||||||
fetchImpl,
|
|
||||||
timeoutMs: 1_000,
|
|
||||||
intervalMs: 0,
|
|
||||||
signal: controller.signal,
|
|
||||||
});
|
|
||||||
|
|
||||||
controller.abort();
|
|
||||||
|
|
||||||
await expect(waitPromise).rejects.toBeInstanceOf(BackendReadinessAbortedError);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("recognizes aborted readiness errors", () => {
|
|
||||||
expect(isBackendReadinessAborted(new BackendReadinessAbortedError())).toBe(true);
|
|
||||||
expect(isBackendReadinessAborted(new Error("nope"))).toBe(false);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,103 +0,0 @@
|
|||||||
export interface WaitForHttpReadyOptions {
|
|
||||||
readonly timeoutMs?: number;
|
|
||||||
readonly intervalMs?: number;
|
|
||||||
readonly requestTimeoutMs?: number;
|
|
||||||
readonly fetchImpl?: typeof fetch;
|
|
||||||
readonly signal?: AbortSignal;
|
|
||||||
}
|
|
||||||
|
|
||||||
const DEFAULT_TIMEOUT_MS = 10_000;
|
|
||||||
const DEFAULT_INTERVAL_MS = 100;
|
|
||||||
const DEFAULT_REQUEST_TIMEOUT_MS = 1_000;
|
|
||||||
|
|
||||||
export class BackendReadinessAbortedError extends Error {
|
|
||||||
constructor() {
|
|
||||||
super("Backend readiness wait was aborted.");
|
|
||||||
this.name = "BackendReadinessAbortedError";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function delay(ms: number, signal: AbortSignal | undefined): Promise<void> {
|
|
||||||
return new Promise<void>((resolve, reject) => {
|
|
||||||
const timer = setTimeout(() => {
|
|
||||||
cleanup();
|
|
||||||
resolve();
|
|
||||||
}, ms);
|
|
||||||
|
|
||||||
const onAbort = () => {
|
|
||||||
cleanup();
|
|
||||||
reject(new BackendReadinessAbortedError());
|
|
||||||
};
|
|
||||||
|
|
||||||
const cleanup = () => {
|
|
||||||
clearTimeout(timer);
|
|
||||||
signal?.removeEventListener("abort", onAbort);
|
|
||||||
};
|
|
||||||
|
|
||||||
if (signal?.aborted) {
|
|
||||||
cleanup();
|
|
||||||
reject(new BackendReadinessAbortedError());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
signal?.addEventListener("abort", onAbort, { once: true });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isBackendReadinessAborted(error: unknown): error is BackendReadinessAbortedError {
|
|
||||||
return error instanceof BackendReadinessAbortedError;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function waitForHttpReady(
|
|
||||||
baseUrl: string,
|
|
||||||
options?: WaitForHttpReadyOptions,
|
|
||||||
): Promise<void> {
|
|
||||||
const fetchImpl = options?.fetchImpl ?? fetch;
|
|
||||||
const signal = options?.signal;
|
|
||||||
const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
||||||
const intervalMs = options?.intervalMs ?? DEFAULT_INTERVAL_MS;
|
|
||||||
const requestTimeoutMs = options?.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
||||||
const deadline = Date.now() + timeoutMs;
|
|
||||||
|
|
||||||
for (;;) {
|
|
||||||
if (signal?.aborted) {
|
|
||||||
throw new BackendReadinessAbortedError();
|
|
||||||
}
|
|
||||||
|
|
||||||
const requestController = new AbortController();
|
|
||||||
const requestTimeout = setTimeout(() => {
|
|
||||||
requestController.abort();
|
|
||||||
}, requestTimeoutMs);
|
|
||||||
const abortRequest = () => {
|
|
||||||
requestController.abort();
|
|
||||||
};
|
|
||||||
signal?.addEventListener("abort", abortRequest, { once: true });
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await fetchImpl(`${baseUrl}/api/auth/session`, {
|
|
||||||
redirect: "manual",
|
|
||||||
signal: requestController.signal,
|
|
||||||
});
|
|
||||||
if (response.ok) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
if (isBackendReadinessAborted(error)) {
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
if (signal?.aborted) {
|
|
||||||
throw new BackendReadinessAbortedError();
|
|
||||||
}
|
|
||||||
// Retry until the backend becomes reachable or the deadline expires.
|
|
||||||
} finally {
|
|
||||||
clearTimeout(requestTimeout);
|
|
||||||
signal?.removeEventListener("abort", abortRequest);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Date.now() >= deadline) {
|
|
||||||
throw new Error(`Timed out waiting for backend readiness at ${baseUrl}.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
await delay(intervalMs, signal);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,234 +0,0 @@
|
|||||||
import * as fs from "node:fs";
|
|
||||||
import * as os from "node:os";
|
|
||||||
import * as path from "node:path";
|
|
||||||
|
|
||||||
import {
|
|
||||||
EnvironmentId,
|
|
||||||
type ClientSettings,
|
|
||||||
type PersistedSavedEnvironmentRecord,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
import { afterEach, describe, expect, it } from "vitest";
|
|
||||||
|
|
||||||
import {
|
|
||||||
readClientSettings,
|
|
||||||
readSavedEnvironmentRegistry,
|
|
||||||
readSavedEnvironmentSecret,
|
|
||||||
removeSavedEnvironmentSecret,
|
|
||||||
writeClientSettings,
|
|
||||||
writeSavedEnvironmentRegistry,
|
|
||||||
writeSavedEnvironmentSecret,
|
|
||||||
type DesktopSecretStorage,
|
|
||||||
} from "./clientPersistence";
|
|
||||||
|
|
||||||
const tempDirectories: string[] = [];
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
for (const directory of tempDirectories.splice(0)) {
|
|
||||||
fs.rmSync(directory, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
function makeTempPath(fileName: string): string {
|
|
||||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "t3-client-persistence-test-"));
|
|
||||||
tempDirectories.push(directory);
|
|
||||||
return path.join(directory, fileName);
|
|
||||||
}
|
|
||||||
|
|
||||||
function makeSecretStorage(available: boolean): DesktopSecretStorage {
|
|
||||||
return {
|
|
||||||
isEncryptionAvailable: () => available,
|
|
||||||
encryptString: (value) => Buffer.from(`enc:${value}`, "utf8"),
|
|
||||||
decryptString: (value) => {
|
|
||||||
const decoded = value.toString("utf8");
|
|
||||||
if (!decoded.startsWith("enc:")) {
|
|
||||||
throw new Error("invalid secret");
|
|
||||||
}
|
|
||||||
return decoded.slice("enc:".length);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const clientSettings: ClientSettings = {
|
|
||||||
confirmThreadArchive: true,
|
|
||||||
confirmThreadDelete: false,
|
|
||||||
diffWordWrap: true,
|
|
||||||
sidebarProjectSortOrder: "manual",
|
|
||||||
sidebarThreadSortOrder: "created_at",
|
|
||||||
timestampFormat: "24-hour",
|
|
||||||
};
|
|
||||||
|
|
||||||
const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
|
|
||||||
environmentId: EnvironmentId.makeUnsafe("environment-1"),
|
|
||||||
label: "Remote environment",
|
|
||||||
httpBaseUrl: "https://remote.example.com/",
|
|
||||||
wsBaseUrl: "wss://remote.example.com/",
|
|
||||||
createdAt: "2026-04-09T00:00:00.000Z",
|
|
||||||
lastConnectedAt: "2026-04-09T01:00:00.000Z",
|
|
||||||
};
|
|
||||||
|
|
||||||
describe("clientPersistence", () => {
|
|
||||||
it("persists and reloads client settings", () => {
|
|
||||||
const settingsPath = makeTempPath("client-settings.json");
|
|
||||||
|
|
||||||
writeClientSettings(settingsPath, clientSettings);
|
|
||||||
|
|
||||||
expect(readClientSettings(settingsPath)).toEqual(clientSettings);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("persists and reloads saved environment metadata", () => {
|
|
||||||
const registryPath = makeTempPath("saved-environments.json");
|
|
||||||
|
|
||||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
|
||||||
|
|
||||||
expect(readSavedEnvironmentRegistry(registryPath)).toEqual([savedRegistryRecord]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("persists encrypted saved environment secrets when encryption is available", () => {
|
|
||||||
const registryPath = makeTempPath("saved-environments.json");
|
|
||||||
const secretStorage = makeSecretStorage(true);
|
|
||||||
|
|
||||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
|
||||||
|
|
||||||
expect(
|
|
||||||
writeSavedEnvironmentSecret({
|
|
||||||
registryPath,
|
|
||||||
environmentId: savedRegistryRecord.environmentId,
|
|
||||||
secret: "bearer-token",
|
|
||||||
secretStorage,
|
|
||||||
}),
|
|
||||||
).toBe(true);
|
|
||||||
|
|
||||||
expect(
|
|
||||||
readSavedEnvironmentSecret({
|
|
||||||
registryPath,
|
|
||||||
environmentId: savedRegistryRecord.environmentId,
|
|
||||||
secretStorage,
|
|
||||||
}),
|
|
||||||
).toBe("bearer-token");
|
|
||||||
|
|
||||||
expect(JSON.parse(fs.readFileSync(registryPath, "utf8"))).toEqual({
|
|
||||||
records: [
|
|
||||||
{
|
|
||||||
...savedRegistryRecord,
|
|
||||||
encryptedBearerToken: Buffer.from("enc:bearer-token", "utf8").toString("base64"),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("preserves existing secrets when encryption is unavailable", () => {
|
|
||||||
const registryPath = makeTempPath("saved-environments.json");
|
|
||||||
const availableSecretStorage = makeSecretStorage(true);
|
|
||||||
|
|
||||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
|
||||||
|
|
||||||
writeSavedEnvironmentSecret({
|
|
||||||
registryPath,
|
|
||||||
environmentId: savedRegistryRecord.environmentId,
|
|
||||||
secret: "bearer-token",
|
|
||||||
secretStorage: availableSecretStorage,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(
|
|
||||||
writeSavedEnvironmentSecret({
|
|
||||||
registryPath,
|
|
||||||
environmentId: savedRegistryRecord.environmentId,
|
|
||||||
secret: "next-token",
|
|
||||||
secretStorage: makeSecretStorage(false),
|
|
||||||
}),
|
|
||||||
).toBe(false);
|
|
||||||
|
|
||||||
expect(
|
|
||||||
readSavedEnvironmentSecret({
|
|
||||||
registryPath,
|
|
||||||
environmentId: savedRegistryRecord.environmentId,
|
|
||||||
secretStorage: availableSecretStorage,
|
|
||||||
}),
|
|
||||||
).toBe("bearer-token");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("removes saved environment secrets", () => {
|
|
||||||
const registryPath = makeTempPath("saved-environments.json");
|
|
||||||
const secretStorage = makeSecretStorage(true);
|
|
||||||
|
|
||||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
|
||||||
|
|
||||||
writeSavedEnvironmentSecret({
|
|
||||||
registryPath,
|
|
||||||
environmentId: savedRegistryRecord.environmentId,
|
|
||||||
secret: "bearer-token",
|
|
||||||
secretStorage,
|
|
||||||
});
|
|
||||||
|
|
||||||
removeSavedEnvironmentSecret({
|
|
||||||
registryPath,
|
|
||||||
environmentId: savedRegistryRecord.environmentId,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(
|
|
||||||
readSavedEnvironmentSecret({
|
|
||||||
registryPath,
|
|
||||||
environmentId: savedRegistryRecord.environmentId,
|
|
||||||
secretStorage,
|
|
||||||
}),
|
|
||||||
).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("treats malformed secrets documents as empty", () => {
|
|
||||||
const registryPath = makeTempPath("saved-environments.json");
|
|
||||||
fs.writeFileSync(registryPath, "{}\n", "utf8");
|
|
||||||
|
|
||||||
expect(
|
|
||||||
readSavedEnvironmentSecret({
|
|
||||||
registryPath,
|
|
||||||
environmentId: savedRegistryRecord.environmentId,
|
|
||||||
secretStorage: makeSecretStorage(true),
|
|
||||||
}),
|
|
||||||
).toBeNull();
|
|
||||||
|
|
||||||
expect(() =>
|
|
||||||
removeSavedEnvironmentSecret({
|
|
||||||
registryPath,
|
|
||||||
environmentId: savedRegistryRecord.environmentId,
|
|
||||||
}),
|
|
||||||
).not.toThrow();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns false when writing a secret without metadata", () => {
|
|
||||||
const registryPath = makeTempPath("saved-environments.json");
|
|
||||||
|
|
||||||
expect(
|
|
||||||
writeSavedEnvironmentSecret({
|
|
||||||
registryPath,
|
|
||||||
environmentId: savedRegistryRecord.environmentId,
|
|
||||||
secret: "bearer-token",
|
|
||||||
secretStorage: makeSecretStorage(true),
|
|
||||||
}),
|
|
||||||
).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("preserves encrypted secrets when metadata is rewritten", () => {
|
|
||||||
const registryPath = makeTempPath("saved-environments.json");
|
|
||||||
const secretStorage = makeSecretStorage(true);
|
|
||||||
|
|
||||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
|
||||||
|
|
||||||
writeSavedEnvironmentSecret({
|
|
||||||
registryPath,
|
|
||||||
environmentId: savedRegistryRecord.environmentId,
|
|
||||||
secret: "bearer-token",
|
|
||||||
secretStorage,
|
|
||||||
});
|
|
||||||
|
|
||||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
|
||||||
|
|
||||||
expect(readSavedEnvironmentRegistry(registryPath)).toEqual([savedRegistryRecord]);
|
|
||||||
expect(
|
|
||||||
readSavedEnvironmentSecret({
|
|
||||||
registryPath,
|
|
||||||
environmentId: savedRegistryRecord.environmentId,
|
|
||||||
secretStorage,
|
|
||||||
}),
|
|
||||||
).toBe("bearer-token");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,216 +0,0 @@
|
|||||||
import * as FS from "node:fs";
|
|
||||||
import * as Path from "node:path";
|
|
||||||
|
|
||||||
import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
|
|
||||||
import { Predicate } from "effect";
|
|
||||||
|
|
||||||
interface ClientSettingsDocument {
|
|
||||||
readonly settings: ClientSettings;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface PersistedSavedEnvironmentStorageRecord extends PersistedSavedEnvironmentRecord {
|
|
||||||
readonly encryptedBearerToken?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface SavedEnvironmentRegistryDocument {
|
|
||||||
readonly records: readonly PersistedSavedEnvironmentStorageRecord[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DesktopSecretStorage {
|
|
||||||
readonly isEncryptionAvailable: () => boolean;
|
|
||||||
readonly encryptString: (value: string) => Buffer;
|
|
||||||
readonly decryptString: (value: Buffer) => string;
|
|
||||||
}
|
|
||||||
|
|
||||||
function readJsonFile<T>(filePath: string): T | null {
|
|
||||||
try {
|
|
||||||
if (!FS.existsSync(filePath)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return JSON.parse(FS.readFileSync(filePath, "utf8")) as T;
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function writeJsonFile(filePath: string, value: unknown): void {
|
|
||||||
const directory = Path.dirname(filePath);
|
|
||||||
const tempPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
|
|
||||||
FS.mkdirSync(directory, { recursive: true });
|
|
||||||
FS.writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, "utf8");
|
|
||||||
FS.renameSync(tempPath, filePath);
|
|
||||||
}
|
|
||||||
|
|
||||||
function isPersistedSavedEnvironmentStorageRecord(
|
|
||||||
value: unknown,
|
|
||||||
): value is PersistedSavedEnvironmentStorageRecord {
|
|
||||||
return (
|
|
||||||
Predicate.isObject(value) &&
|
|
||||||
typeof value.environmentId === "string" &&
|
|
||||||
typeof value.label === "string" &&
|
|
||||||
typeof value.httpBaseUrl === "string" &&
|
|
||||||
typeof value.wsBaseUrl === "string" &&
|
|
||||||
typeof value.createdAt === "string" &&
|
|
||||||
(value.lastConnectedAt === null || typeof value.lastConnectedAt === "string") &&
|
|
||||||
(value.encryptedBearerToken === undefined || typeof value.encryptedBearerToken === "string")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function readSavedEnvironmentRegistryDocument(filePath: string): SavedEnvironmentRegistryDocument {
|
|
||||||
const parsed = readJsonFile<SavedEnvironmentRegistryDocument>(filePath);
|
|
||||||
if (!Predicate.isObject(parsed)) {
|
|
||||||
return { records: [] };
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
records: Array.isArray(parsed.records)
|
|
||||||
? parsed.records.filter(isPersistedSavedEnvironmentStorageRecord)
|
|
||||||
: [],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function toPersistedSavedEnvironmentRecord(
|
|
||||||
record: PersistedSavedEnvironmentStorageRecord,
|
|
||||||
): PersistedSavedEnvironmentRecord {
|
|
||||||
return {
|
|
||||||
environmentId: record.environmentId,
|
|
||||||
label: record.label,
|
|
||||||
httpBaseUrl: record.httpBaseUrl,
|
|
||||||
wsBaseUrl: record.wsBaseUrl,
|
|
||||||
createdAt: record.createdAt,
|
|
||||||
lastConnectedAt: record.lastConnectedAt,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function readClientSettings(settingsPath: string): ClientSettings | null {
|
|
||||||
return readJsonFile<ClientSettingsDocument>(settingsPath)?.settings ?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function writeClientSettings(settingsPath: string, settings: ClientSettings): void {
|
|
||||||
writeJsonFile(settingsPath, { settings } satisfies ClientSettingsDocument);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function readSavedEnvironmentRegistry(
|
|
||||||
registryPath: string,
|
|
||||||
): readonly PersistedSavedEnvironmentRecord[] {
|
|
||||||
return readSavedEnvironmentRegistryDocument(registryPath).records.map((record) =>
|
|
||||||
toPersistedSavedEnvironmentRecord(record),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function writeSavedEnvironmentRegistry(
|
|
||||||
registryPath: string,
|
|
||||||
records: readonly PersistedSavedEnvironmentRecord[],
|
|
||||||
): void {
|
|
||||||
const currentDocument = readSavedEnvironmentRegistryDocument(registryPath);
|
|
||||||
const encryptedBearerTokenById = new Map(
|
|
||||||
currentDocument.records.flatMap((record) =>
|
|
||||||
record.encryptedBearerToken
|
|
||||||
? [[record.environmentId, record.encryptedBearerToken] as const]
|
|
||||||
: [],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
writeJsonFile(registryPath, {
|
|
||||||
records: records.map((record) => {
|
|
||||||
const encryptedBearerToken = encryptedBearerTokenById.get(record.environmentId);
|
|
||||||
return encryptedBearerToken
|
|
||||||
? {
|
|
||||||
environmentId: record.environmentId,
|
|
||||||
label: record.label,
|
|
||||||
httpBaseUrl: record.httpBaseUrl,
|
|
||||||
wsBaseUrl: record.wsBaseUrl,
|
|
||||||
createdAt: record.createdAt,
|
|
||||||
lastConnectedAt: record.lastConnectedAt,
|
|
||||||
encryptedBearerToken,
|
|
||||||
}
|
|
||||||
: record;
|
|
||||||
}),
|
|
||||||
} satisfies SavedEnvironmentRegistryDocument);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function readSavedEnvironmentSecret(input: {
|
|
||||||
readonly registryPath: string;
|
|
||||||
readonly environmentId: string;
|
|
||||||
readonly secretStorage: DesktopSecretStorage;
|
|
||||||
}): string | null {
|
|
||||||
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
|
|
||||||
const encoded = document.records.find(
|
|
||||||
(record) => record.environmentId === input.environmentId,
|
|
||||||
)?.encryptedBearerToken;
|
|
||||||
if (!encoded) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!input.secretStorage.isEncryptionAvailable()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
return input.secretStorage.decryptString(Buffer.from(encoded, "base64"));
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function writeSavedEnvironmentSecret(input: {
|
|
||||||
readonly registryPath: string;
|
|
||||||
readonly environmentId: string;
|
|
||||||
readonly secret: string;
|
|
||||||
readonly secretStorage: DesktopSecretStorage;
|
|
||||||
}): boolean {
|
|
||||||
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
|
|
||||||
|
|
||||||
if (!input.secretStorage.isEncryptionAvailable()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
let found = false;
|
|
||||||
|
|
||||||
writeJsonFile(input.registryPath, {
|
|
||||||
records: document.records.map((record) => {
|
|
||||||
if (record.environmentId !== input.environmentId) {
|
|
||||||
return record;
|
|
||||||
}
|
|
||||||
|
|
||||||
found = true;
|
|
||||||
const encryptedBearerToken = input.secretStorage
|
|
||||||
.encryptString(input.secret)
|
|
||||||
.toString("base64");
|
|
||||||
return {
|
|
||||||
environmentId: record.environmentId,
|
|
||||||
label: record.label,
|
|
||||||
httpBaseUrl: record.httpBaseUrl,
|
|
||||||
wsBaseUrl: record.wsBaseUrl,
|
|
||||||
createdAt: record.createdAt,
|
|
||||||
lastConnectedAt: record.lastConnectedAt,
|
|
||||||
encryptedBearerToken,
|
|
||||||
} satisfies PersistedSavedEnvironmentStorageRecord;
|
|
||||||
}),
|
|
||||||
} satisfies SavedEnvironmentRegistryDocument);
|
|
||||||
return found;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function removeSavedEnvironmentSecret(input: {
|
|
||||||
readonly registryPath: string;
|
|
||||||
readonly environmentId: string;
|
|
||||||
}): void {
|
|
||||||
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
|
|
||||||
if (
|
|
||||||
!document.records.some(
|
|
||||||
(record) =>
|
|
||||||
record.environmentId === input.environmentId && record.encryptedBearerToken !== undefined,
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
writeJsonFile(input.registryPath, {
|
|
||||||
records: document.records.map((record) => {
|
|
||||||
if (record.environmentId !== input.environmentId) {
|
|
||||||
return record;
|
|
||||||
}
|
|
||||||
|
|
||||||
return toPersistedSavedEnvironmentRecord(record);
|
|
||||||
}),
|
|
||||||
} satisfies SavedEnvironmentRegistryDocument);
|
|
||||||
}
|
|
||||||
@@ -14,7 +14,7 @@ export async function showDesktopConfirmDialog(
|
|||||||
const options = {
|
const options = {
|
||||||
type: "question" as const,
|
type: "question" as const,
|
||||||
buttons: ["No", "Yes"],
|
buttons: ["No", "Yes"],
|
||||||
defaultId: 0,
|
defaultId: CONFIRM_BUTTON_INDEX,
|
||||||
cancelId: 0,
|
cancelId: 0,
|
||||||
noLink: true,
|
noLink: true,
|
||||||
message: normalizedMessage,
|
message: normalizedMessage,
|
||||||
|
|||||||
@@ -1,64 +0,0 @@
|
|||||||
import * as fs from "node:fs";
|
|
||||||
import * as os from "node:os";
|
|
||||||
import * as path from "node:path";
|
|
||||||
|
|
||||||
import { afterEach, describe, expect, it } from "vitest";
|
|
||||||
|
|
||||||
import {
|
|
||||||
DEFAULT_DESKTOP_SETTINGS,
|
|
||||||
readDesktopSettings,
|
|
||||||
setDesktopServerExposurePreference,
|
|
||||||
writeDesktopSettings,
|
|
||||||
} from "./desktopSettings";
|
|
||||||
|
|
||||||
const tempDirectories: string[] = [];
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
for (const directory of tempDirectories.splice(0)) {
|
|
||||||
fs.rmSync(directory, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
function makeSettingsPath() {
|
|
||||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "t3-desktop-settings-test-"));
|
|
||||||
tempDirectories.push(directory);
|
|
||||||
return path.join(directory, "desktop-settings.json");
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("desktopSettings", () => {
|
|
||||||
it("returns defaults when no settings file exists", () => {
|
|
||||||
expect(readDesktopSettings(makeSettingsPath())).toEqual(DEFAULT_DESKTOP_SETTINGS);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("persists and reloads the configured server exposure mode", () => {
|
|
||||||
const settingsPath = makeSettingsPath();
|
|
||||||
|
|
||||||
writeDesktopSettings(settingsPath, {
|
|
||||||
serverExposureMode: "network-accessible",
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(readDesktopSettings(settingsPath)).toEqual({
|
|
||||||
serverExposureMode: "network-accessible",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("preserves the requested network-accessible preference across temporary fallback", () => {
|
|
||||||
expect(
|
|
||||||
setDesktopServerExposurePreference(
|
|
||||||
{
|
|
||||||
serverExposureMode: "local-only",
|
|
||||||
},
|
|
||||||
"network-accessible",
|
|
||||||
),
|
|
||||||
).toEqual({
|
|
||||||
serverExposureMode: "network-accessible",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("falls back to defaults when the settings file is malformed", () => {
|
|
||||||
const settingsPath = makeSettingsPath();
|
|
||||||
fs.writeFileSync(settingsPath, "{not-json", "utf8");
|
|
||||||
|
|
||||||
expect(readDesktopSettings(settingsPath)).toEqual(DEFAULT_DESKTOP_SETTINGS);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
import * as FS from "node:fs";
|
|
||||||
import * as Path from "node:path";
|
|
||||||
import type { DesktopServerExposureMode } from "@t3tools/contracts";
|
|
||||||
|
|
||||||
export interface DesktopSettings {
|
|
||||||
readonly serverExposureMode: DesktopServerExposureMode;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
|
||||||
serverExposureMode: "local-only",
|
|
||||||
};
|
|
||||||
|
|
||||||
export function setDesktopServerExposurePreference(
|
|
||||||
settings: DesktopSettings,
|
|
||||||
requestedMode: DesktopServerExposureMode,
|
|
||||||
): DesktopSettings {
|
|
||||||
return settings.serverExposureMode === requestedMode
|
|
||||||
? settings
|
|
||||||
: {
|
|
||||||
...settings,
|
|
||||||
serverExposureMode: requestedMode,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function readDesktopSettings(settingsPath: string): DesktopSettings {
|
|
||||||
try {
|
|
||||||
if (!FS.existsSync(settingsPath)) {
|
|
||||||
return DEFAULT_DESKTOP_SETTINGS;
|
|
||||||
}
|
|
||||||
|
|
||||||
const raw = FS.readFileSync(settingsPath, "utf8");
|
|
||||||
const parsed = JSON.parse(raw) as {
|
|
||||||
readonly serverExposureMode?: unknown;
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
|
||||||
serverExposureMode:
|
|
||||||
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
|
|
||||||
};
|
|
||||||
} catch {
|
|
||||||
return DEFAULT_DESKTOP_SETTINGS;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function writeDesktopSettings(settingsPath: string, settings: DesktopSettings): void {
|
|
||||||
const directory = Path.dirname(settingsPath);
|
|
||||||
const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`;
|
|
||||||
FS.mkdirSync(directory, { recursive: true });
|
|
||||||
FS.writeFileSync(tempPath, `${JSON.stringify(settings, null, 2)}\n`, "utf8");
|
|
||||||
FS.renameSync(tempPath, settingsPath);
|
|
||||||
}
|
|
||||||
+59
-568
@@ -7,51 +7,27 @@ import * as Path from "node:path";
|
|||||||
import {
|
import {
|
||||||
app,
|
app,
|
||||||
BrowserWindow,
|
BrowserWindow,
|
||||||
clipboard,
|
|
||||||
dialog,
|
dialog,
|
||||||
ipcMain,
|
ipcMain,
|
||||||
Menu,
|
Menu,
|
||||||
nativeImage,
|
nativeImage,
|
||||||
nativeTheme,
|
nativeTheme,
|
||||||
protocol,
|
protocol,
|
||||||
safeStorage,
|
|
||||||
shell,
|
shell,
|
||||||
} from "electron";
|
} from "electron";
|
||||||
import type { MenuItemConstructorOptions } from "electron";
|
import type { MenuItemConstructorOptions } from "electron";
|
||||||
|
import * as Effect from "effect/Effect";
|
||||||
import type {
|
import type {
|
||||||
ClientSettings,
|
|
||||||
DesktopTheme,
|
DesktopTheme,
|
||||||
DesktopServerExposureMode,
|
|
||||||
DesktopServerExposureState,
|
|
||||||
PersistedSavedEnvironmentRecord,
|
|
||||||
DesktopUpdateActionResult,
|
DesktopUpdateActionResult,
|
||||||
DesktopUpdateCheckResult,
|
|
||||||
DesktopUpdateState,
|
DesktopUpdateState,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { autoUpdater } from "electron-updater";
|
import { autoUpdater } from "electron-updater";
|
||||||
|
|
||||||
import type { ContextMenuItem } from "@t3tools/contracts";
|
import type { ContextMenuItem } from "@t3tools/contracts";
|
||||||
|
import { NetService } from "@t3tools/shared/Net";
|
||||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
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 { showDesktopConfirmDialog } from "./confirmDialog";
|
||||||
import { resolveDesktopServerExposure } from "./serverExposure";
|
|
||||||
import { syncShellEnvironment } from "./syncShellEnvironment";
|
import { syncShellEnvironment } from "./syncShellEnvironment";
|
||||||
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
|
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
|
||||||
import {
|
import {
|
||||||
@@ -80,29 +56,13 @@ const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
|||||||
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||||
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||||
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
const STATE_DIR =
|
||||||
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
|
process.env.T3CODE_STATE_DIR?.trim() || Path.join(OS.homedir(), ".t3", "userdata");
|
||||||
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 DESKTOP_SCHEME = "t3";
|
||||||
const ROOT_DIR = Path.resolve(__dirname, "../../..");
|
const ROOT_DIR = Path.resolve(__dirname, "../../..");
|
||||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||||
const APP_USER_MODEL_ID = "com.t3tools.t3code";
|
const APP_USER_MODEL_ID = "com.t3tools.t3code";
|
||||||
const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop";
|
|
||||||
const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code";
|
|
||||||
const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";
|
const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";
|
||||||
const LEGACY_USER_DATA_DIR_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
const LEGACY_USER_DATA_DIR_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||||
const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i;
|
const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i;
|
||||||
@@ -111,28 +71,18 @@ const LOG_DIR = Path.join(STATE_DIR, "logs");
|
|||||||
const LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
const LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||||
const LOG_FILE_MAX_FILES = 10;
|
const LOG_FILE_MAX_FILES = 10;
|
||||||
const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
|
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_STARTUP_DELAY_MS = 15_000;
|
||||||
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
|
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
|
||||||
const DESKTOP_UPDATE_CHANNEL = "latest";
|
const DESKTOP_UPDATE_CHANNEL = "latest";
|
||||||
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
|
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
|
||||||
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
|
|
||||||
|
|
||||||
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
|
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
|
||||||
type LinuxDesktopNamedApp = Electron.App & {
|
|
||||||
setDesktopName?: (desktopName: string) => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
let mainWindow: BrowserWindow | null = null;
|
let mainWindow: BrowserWindow | null = null;
|
||||||
let backendProcess: ChildProcess.ChildProcess | null = null;
|
let backendProcess: ChildProcess.ChildProcess | null = null;
|
||||||
let backendPort = 0;
|
let backendPort = 0;
|
||||||
let backendBindHost = DESKTOP_LOOPBACK_HOST;
|
let backendAuthToken = "";
|
||||||
let backendBootstrapToken = "";
|
|
||||||
let backendHttpUrl = "";
|
|
||||||
let backendWsUrl = "";
|
let backendWsUrl = "";
|
||||||
let backendEndpointUrl: string | null = null;
|
|
||||||
let backendAdvertisedHost: string | null = null;
|
|
||||||
let backendReadinessAbortController: AbortController | null = null;
|
|
||||||
let restartAttempt = 0;
|
let restartAttempt = 0;
|
||||||
let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
let isQuitting = false;
|
let isQuitting = false;
|
||||||
@@ -141,12 +91,8 @@ let aboutCommitHashCache: string | null | undefined;
|
|||||||
let desktopLogSink: RotatingFileSink | null = null;
|
let desktopLogSink: RotatingFileSink | null = null;
|
||||||
let backendLogSink: RotatingFileSink | null = null;
|
let backendLogSink: RotatingFileSink | null = null;
|
||||||
let restoreStdIoCapture: (() => void) | 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;
|
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
|
||||||
const expectedBackendExitChildren = new WeakSet<ChildProcess.ChildProcess>();
|
|
||||||
const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
|
const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
|
||||||
platform: process.platform,
|
platform: process.platform,
|
||||||
processArch: process.arch,
|
processArch: process.arch,
|
||||||
@@ -167,143 +113,6 @@ function sanitizeLogValue(value: string): string {
|
|||||||
return value.replace(/\s+/g, " ").trim();
|
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_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 {
|
function writeDesktopLogHeader(message: string): void {
|
||||||
if (!desktopLogSink) return;
|
if (!desktopLogSink) return;
|
||||||
desktopLogSink.write(`[${logTimestamp()}] [${logScope("desktop")}] ${message}\n`);
|
desktopLogSink.write(`[${logTimestamp()}] [${logScope("desktop")}] ${message}\n`);
|
||||||
@@ -351,27 +160,6 @@ function getSafeTheme(rawTheme: unknown): DesktopTheme | null {
|
|||||||
return 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(
|
function writeDesktopStreamChunk(
|
||||||
streamName: "stdout" | "stderr",
|
streamName: "stdout" | "stderr",
|
||||||
chunk: unknown,
|
chunk: unknown,
|
||||||
@@ -461,10 +249,6 @@ function captureBackendOutput(child: ChildProcess.ChildProcess): void {
|
|||||||
|
|
||||||
initializePackagedLogging();
|
initializePackagedLogging();
|
||||||
|
|
||||||
if (process.platform === "linux") {
|
|
||||||
app.commandLine.appendSwitch("class", LINUX_WM_CLASS);
|
|
||||||
}
|
|
||||||
|
|
||||||
function getDestructiveMenuIcon(): Electron.NativeImage | undefined {
|
function getDestructiveMenuIcon(): Electron.NativeImage | undefined {
|
||||||
if (process.platform !== "darwin") return undefined;
|
if (process.platform !== "darwin") return undefined;
|
||||||
if (destructiveMenuIconCache !== undefined) {
|
if (destructiveMenuIconCache !== undefined) {
|
||||||
@@ -491,12 +275,10 @@ let updatePollTimer: ReturnType<typeof setInterval> | null = null;
|
|||||||
let updateStartupTimer: ReturnType<typeof setTimeout> | null = null;
|
let updateStartupTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
let updateCheckInFlight = false;
|
let updateCheckInFlight = false;
|
||||||
let updateDownloadInFlight = false;
|
let updateDownloadInFlight = false;
|
||||||
let updateInstallInFlight = false;
|
|
||||||
let updaterConfigured = false;
|
let updaterConfigured = false;
|
||||||
let updateState: DesktopUpdateState = initialUpdateState();
|
let updateState: DesktopUpdateState = initialUpdateState();
|
||||||
|
|
||||||
function resolveUpdaterErrorContext(): DesktopUpdateErrorContext {
|
function resolveUpdaterErrorContext(): DesktopUpdateErrorContext {
|
||||||
if (updateInstallInFlight) return "install";
|
|
||||||
if (updateDownloadInFlight) return "download";
|
if (updateDownloadInFlight) return "download";
|
||||||
if (updateCheckInFlight) return "check";
|
if (updateCheckInFlight) return "check";
|
||||||
return updateState.errorContext;
|
return updateState.errorContext;
|
||||||
@@ -592,7 +374,7 @@ function resolveAboutCommitHash(): string | null {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function resolveBackendEntry(): string {
|
function resolveBackendEntry(): string {
|
||||||
return Path.join(resolveAppRoot(), "apps/server/dist/bin.mjs");
|
return Path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveBackendCwd(): string {
|
function resolveBackendCwd(): string {
|
||||||
@@ -716,7 +498,10 @@ function dispatchMenuAction(action: string): void {
|
|||||||
const send = () => {
|
const send = () => {
|
||||||
if (targetWindow.isDestroyed()) return;
|
if (targetWindow.isDestroyed()) return;
|
||||||
targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
|
targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
|
||||||
revealWindow(targetWindow);
|
if (!targetWindow.isVisible()) {
|
||||||
|
targetWindow.show();
|
||||||
|
}
|
||||||
|
targetWindow.focus();
|
||||||
};
|
};
|
||||||
|
|
||||||
if (targetWindow.webContents.isLoadingMainFrame()) {
|
if (targetWindow.webContents.isLoadingMainFrame()) {
|
||||||
@@ -728,15 +513,12 @@ function dispatchMenuAction(action: string): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function handleCheckForUpdatesMenuClick(): void {
|
function handleCheckForUpdatesMenuClick(): void {
|
||||||
const hasUpdateFeedConfig =
|
|
||||||
readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES);
|
|
||||||
const disabledReason = getAutoUpdateDisabledReason({
|
const disabledReason = getAutoUpdateDisabledReason({
|
||||||
isDevelopment,
|
isDevelopment,
|
||||||
isPackaged: app.isPackaged,
|
isPackaged: app.isPackaged,
|
||||||
platform: process.platform,
|
platform: process.platform,
|
||||||
appImage: process.env.APPIMAGE,
|
appImage: process.env.APPIMAGE,
|
||||||
disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
|
disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
|
||||||
hasUpdateFeedConfig,
|
|
||||||
});
|
});
|
||||||
if (disabledReason) {
|
if (disabledReason) {
|
||||||
console.info("[desktop-updater] Manual update check requested, but updates are disabled.");
|
console.info("[desktop-updater] Manual update check requested, but updates are disabled.");
|
||||||
@@ -917,10 +699,6 @@ function configureAppIdentity(): void {
|
|||||||
app.setAppUserModelId(APP_USER_MODEL_ID);
|
app.setAppUserModelId(APP_USER_MODEL_ID);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (process.platform === "linux") {
|
|
||||||
(app as LinuxDesktopNamedApp).setDesktopName?.(LINUX_DESKTOP_ENTRY_NAME);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (process.platform === "darwin" && app.dock) {
|
if (process.platform === "darwin" && app.dock) {
|
||||||
const iconPath = resolveIconPath("png");
|
const iconPath = resolveIconPath("png");
|
||||||
if (iconPath) {
|
if (iconPath) {
|
||||||
@@ -940,26 +718,6 @@ function clearUpdatePollTimer(): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function revealWindow(window: BrowserWindow): void {
|
|
||||||
if (window.isDestroyed()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (window.isMinimized()) {
|
|
||||||
window.restore();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!window.isVisible()) {
|
|
||||||
window.show();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (process.platform === "darwin") {
|
|
||||||
app.focus({ steal: true });
|
|
||||||
}
|
|
||||||
|
|
||||||
window.focus();
|
|
||||||
}
|
|
||||||
|
|
||||||
function emitUpdateState(): void {
|
function emitUpdateState(): void {
|
||||||
for (const window of BrowserWindow.getAllWindows()) {
|
for (const window of BrowserWindow.getAllWindows()) {
|
||||||
if (window.isDestroyed()) continue;
|
if (window.isDestroyed()) continue;
|
||||||
@@ -973,8 +731,6 @@ function setUpdateState(patch: Partial<DesktopUpdateState>): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function shouldEnableAutoUpdates(): boolean {
|
function shouldEnableAutoUpdates(): boolean {
|
||||||
const hasUpdateFeedConfig =
|
|
||||||
readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES);
|
|
||||||
return (
|
return (
|
||||||
getAutoUpdateDisabledReason({
|
getAutoUpdateDisabledReason({
|
||||||
isDevelopment,
|
isDevelopment,
|
||||||
@@ -982,18 +738,17 @@ function shouldEnableAutoUpdates(): boolean {
|
|||||||
platform: process.platform,
|
platform: process.platform,
|
||||||
appImage: process.env.APPIMAGE,
|
appImage: process.env.APPIMAGE,
|
||||||
disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
|
disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
|
||||||
hasUpdateFeedConfig,
|
|
||||||
}) === null
|
}) === null
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function checkForUpdates(reason: string): Promise<boolean> {
|
async function checkForUpdates(reason: string): Promise<void> {
|
||||||
if (isQuitting || !updaterConfigured || updateCheckInFlight) return false;
|
if (isQuitting || !updaterConfigured || updateCheckInFlight) return;
|
||||||
if (updateState.status === "downloading" || updateState.status === "downloaded") {
|
if (updateState.status === "downloading" || updateState.status === "downloaded") {
|
||||||
console.info(
|
console.info(
|
||||||
`[desktop-updater] Skipping update check (${reason}) while status=${updateState.status}.`,
|
`[desktop-updater] Skipping update check (${reason}) while status=${updateState.status}.`,
|
||||||
);
|
);
|
||||||
return false;
|
return;
|
||||||
}
|
}
|
||||||
updateCheckInFlight = true;
|
updateCheckInFlight = true;
|
||||||
setUpdateState(reduceDesktopUpdateStateOnCheckStart(updateState, new Date().toISOString()));
|
setUpdateState(reduceDesktopUpdateStateOnCheckStart(updateState, new Date().toISOString()));
|
||||||
@@ -1001,14 +756,12 @@ async function checkForUpdates(reason: string): Promise<boolean> {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await autoUpdater.checkForUpdates();
|
await autoUpdater.checkForUpdates();
|
||||||
return true;
|
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
const message = error instanceof Error ? error.message : String(error);
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
setUpdateState(
|
setUpdateState(
|
||||||
reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()),
|
reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()),
|
||||||
);
|
);
|
||||||
console.error(`[desktop-updater] Failed to check for updates: ${message}`);
|
console.error(`[desktop-updater] Failed to check for updates: ${message}`);
|
||||||
return true;
|
|
||||||
} finally {
|
} finally {
|
||||||
updateCheckInFlight = false;
|
updateCheckInFlight = false;
|
||||||
}
|
}
|
||||||
@@ -1042,22 +795,13 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed
|
|||||||
}
|
}
|
||||||
|
|
||||||
isQuitting = true;
|
isQuitting = true;
|
||||||
updateInstallInFlight = true;
|
|
||||||
clearUpdatePollTimer();
|
clearUpdatePollTimer();
|
||||||
try {
|
try {
|
||||||
await stopBackendAndWaitForExit();
|
await stopBackendAndWaitForExit();
|
||||||
// Destroy all windows before launching the NSIS installer to avoid the installer finding live windows it needs to close.
|
autoUpdater.quitAndInstall();
|
||||||
for (const win of BrowserWindow.getAllWindows()) {
|
return { accepted: true, completed: true };
|
||||||
win.destroy();
|
|
||||||
}
|
|
||||||
// `quitAndInstall()` only starts the handoff to the updater. The actual
|
|
||||||
// install may still fail asynchronously, so keep the action incomplete
|
|
||||||
// until we either quit or receive an updater error.
|
|
||||||
autoUpdater.quitAndInstall(true, true);
|
|
||||||
return { accepted: true, completed: false };
|
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
const message = formatErrorMessage(error);
|
const message = formatErrorMessage(error);
|
||||||
updateInstallInFlight = false;
|
|
||||||
isQuitting = false;
|
isQuitting = false;
|
||||||
setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
|
setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
|
||||||
console.error(`[desktop-updater] Failed to install update: ${message}`);
|
console.error(`[desktop-updater] Failed to install update: ${message}`);
|
||||||
@@ -1066,6 +810,17 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed
|
|||||||
}
|
}
|
||||||
|
|
||||||
function configureAutoUpdater(): void {
|
function configureAutoUpdater(): void {
|
||||||
|
const enabled = shouldEnableAutoUpdates();
|
||||||
|
setUpdateState({
|
||||||
|
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
|
||||||
|
enabled,
|
||||||
|
status: enabled ? "idle" : "disabled",
|
||||||
|
});
|
||||||
|
if (!enabled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
updaterConfigured = true;
|
||||||
|
|
||||||
const githubToken =
|
const githubToken =
|
||||||
process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || "";
|
process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || "";
|
||||||
if (githubToken) {
|
if (githubToken) {
|
||||||
@@ -1083,24 +838,6 @@ function configureAutoUpdater(): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (process.env.T3CODE_DESKTOP_MOCK_UPDATES) {
|
|
||||||
autoUpdater.setFeedURL({
|
|
||||||
provider: "generic",
|
|
||||||
url: `http://localhost:${process.env.T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT ?? 3000}`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const enabled = shouldEnableAutoUpdates();
|
|
||||||
setUpdateState({
|
|
||||||
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
|
|
||||||
enabled,
|
|
||||||
status: enabled ? "idle" : "disabled",
|
|
||||||
});
|
|
||||||
if (!enabled) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
updaterConfigured = true;
|
|
||||||
|
|
||||||
autoUpdater.autoDownload = false;
|
autoUpdater.autoDownload = false;
|
||||||
autoUpdater.autoInstallOnAppQuit = false;
|
autoUpdater.autoInstallOnAppQuit = false;
|
||||||
// Keep alpha branding, but force all installs onto the stable update track.
|
// Keep alpha branding, but force all installs onto the stable update track.
|
||||||
@@ -1137,13 +874,6 @@ function configureAutoUpdater(): void {
|
|||||||
});
|
});
|
||||||
autoUpdater.on("error", (error) => {
|
autoUpdater.on("error", (error) => {
|
||||||
const message = formatErrorMessage(error);
|
const message = formatErrorMessage(error);
|
||||||
if (updateInstallInFlight) {
|
|
||||||
updateInstallInFlight = false;
|
|
||||||
isQuitting = false;
|
|
||||||
setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
|
|
||||||
console.error(`[desktop-updater] Updater error: ${message}`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!updateCheckInFlight && !updateDownloadInFlight) {
|
if (!updateCheckInFlight && !updateDownloadInFlight) {
|
||||||
setUpdateState({
|
setUpdateState({
|
||||||
status: "error",
|
status: "error",
|
||||||
@@ -1188,6 +918,17 @@ function configureAutoUpdater(): void {
|
|||||||
}, AUTO_UPDATE_POLL_INTERVAL_MS);
|
}, AUTO_UPDATE_POLL_INTERVAL_MS);
|
||||||
updatePollTimer.unref();
|
updatePollTimer.unref();
|
||||||
}
|
}
|
||||||
|
function backendEnv(): NodeJS.ProcessEnv {
|
||||||
|
return {
|
||||||
|
...process.env,
|
||||||
|
T3CODE_MODE: "desktop",
|
||||||
|
T3CODE_NO_BROWSER: "1",
|
||||||
|
T3CODE_PORT: String(backendPort),
|
||||||
|
T3CODE_STATE_DIR: STATE_DIR,
|
||||||
|
T3CODE_AUTH_TOKEN: backendAuthToken,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function scheduleBackendRestart(reason: string): void {
|
function scheduleBackendRestart(reason: string): void {
|
||||||
if (isQuitting || restartTimer) return;
|
if (isQuitting || restartTimer) return;
|
||||||
|
|
||||||
@@ -1204,7 +945,6 @@ function scheduleBackendRestart(reason: string): void {
|
|||||||
function startBackend(): void {
|
function startBackend(): void {
|
||||||
if (isQuitting || backendProcess) return;
|
if (isQuitting || backendProcess) return;
|
||||||
|
|
||||||
backendObservabilitySettings = readPersistedBackendObservabilitySettings();
|
|
||||||
const backendEntry = resolveBackendEntry();
|
const backendEntry = resolveBackendEntry();
|
||||||
if (!FS.existsSync(backendEntry)) {
|
if (!FS.existsSync(backendEntry)) {
|
||||||
scheduleBackendRestart(`missing server entry at ${backendEntry}`);
|
scheduleBackendRestart(`missing server entry at ${backendEntry}`);
|
||||||
@@ -1212,42 +952,16 @@ function startBackend(): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const captureBackendLogs = app.isPackaged && backendLogSink !== null;
|
const captureBackendLogs = app.isPackaged && backendLogSink !== null;
|
||||||
const child = ChildProcess.spawn(process.execPath, [backendEntry, "--bootstrap-fd", "3"], {
|
const child = ChildProcess.spawn(process.execPath, [backendEntry], {
|
||||||
cwd: resolveBackendCwd(),
|
cwd: resolveBackendCwd(),
|
||||||
// In Electron main, process.execPath points to the Electron binary.
|
// In Electron main, process.execPath points to the Electron binary.
|
||||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||||
env: {
|
env: {
|
||||||
...backendChildEnv(),
|
...backendEnv(),
|
||||||
ELECTRON_RUN_AS_NODE: "1",
|
ELECTRON_RUN_AS_NODE: "1",
|
||||||
},
|
},
|
||||||
stdio: captureBackendLogs
|
stdio: captureBackendLogs ? ["ignore", "pipe", "pipe"] : "inherit",
|
||||||
? ["ignore", "pipe", "pipe", "pipe"]
|
|
||||||
: ["ignore", "inherit", "inherit", "pipe"],
|
|
||||||
});
|
});
|
||||||
const bootstrapStream = child.stdio[3];
|
|
||||||
if (bootstrapStream && "write" in bootstrapStream) {
|
|
||||||
bootstrapStream.write(
|
|
||||||
`${JSON.stringify({
|
|
||||||
mode: "desktop",
|
|
||||||
noBrowser: true,
|
|
||||||
port: backendPort,
|
|
||||||
t3Home: BASE_DIR,
|
|
||||||
host: backendBindHost,
|
|
||||||
desktopBootstrapToken: backendBootstrapToken,
|
|
||||||
...(backendObservabilitySettings.otlpTracesUrl
|
|
||||||
? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl }
|
|
||||||
: {}),
|
|
||||||
...(backendObservabilitySettings.otlpMetricsUrl
|
|
||||||
? { otlpMetricsUrl: backendObservabilitySettings.otlpMetricsUrl }
|
|
||||||
: {}),
|
|
||||||
})}\n`,
|
|
||||||
);
|
|
||||||
bootstrapStream.end();
|
|
||||||
} else {
|
|
||||||
child.kill("SIGTERM");
|
|
||||||
scheduleBackendRestart("missing desktop bootstrap pipe");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
backendProcess = child;
|
backendProcess = child;
|
||||||
let backendSessionClosed = false;
|
let backendSessionClosed = false;
|
||||||
const closeBackendSession = (details: string) => {
|
const closeBackendSession = (details: string) => {
|
||||||
@@ -1266,33 +980,27 @@ function startBackend(): void {
|
|||||||
});
|
});
|
||||||
|
|
||||||
child.on("error", (error) => {
|
child.on("error", (error) => {
|
||||||
const wasExpected = expectedBackendExitChildren.has(child);
|
|
||||||
if (backendProcess === child) {
|
if (backendProcess === child) {
|
||||||
backendProcess = null;
|
backendProcess = null;
|
||||||
}
|
}
|
||||||
closeBackendSession(`pid=${child.pid ?? "unknown"} error=${error.message}`);
|
closeBackendSession(`pid=${child.pid ?? "unknown"} error=${error.message}`);
|
||||||
if (wasExpected) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
scheduleBackendRestart(error.message);
|
scheduleBackendRestart(error.message);
|
||||||
});
|
});
|
||||||
|
|
||||||
child.on("exit", (code, signal) => {
|
child.on("exit", (code, signal) => {
|
||||||
const wasExpected = expectedBackendExitChildren.has(child);
|
|
||||||
if (backendProcess === child) {
|
if (backendProcess === child) {
|
||||||
backendProcess = null;
|
backendProcess = null;
|
||||||
}
|
}
|
||||||
closeBackendSession(
|
closeBackendSession(
|
||||||
`pid=${child.pid ?? "unknown"} code=${code ?? "null"} signal=${signal ?? "null"}`,
|
`pid=${child.pid ?? "unknown"} code=${code ?? "null"} signal=${signal ?? "null"}`,
|
||||||
);
|
);
|
||||||
if (isQuitting || wasExpected) return;
|
if (isQuitting) return;
|
||||||
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
|
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
|
||||||
scheduleBackendRestart(reason);
|
scheduleBackendRestart(reason);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function stopBackend(): void {
|
function stopBackend(): void {
|
||||||
cancelBackendReadinessWait();
|
|
||||||
if (restartTimer) {
|
if (restartTimer) {
|
||||||
clearTimeout(restartTimer);
|
clearTimeout(restartTimer);
|
||||||
restartTimer = null;
|
restartTimer = null;
|
||||||
@@ -1303,7 +1011,6 @@ function stopBackend(): void {
|
|||||||
if (!child) return;
|
if (!child) return;
|
||||||
|
|
||||||
if (child.exitCode === null && child.signalCode === null) {
|
if (child.exitCode === null && child.signalCode === null) {
|
||||||
expectedBackendExitChildren.add(child);
|
|
||||||
child.kill("SIGTERM");
|
child.kill("SIGTERM");
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
if (child.exitCode === null && child.signalCode === null) {
|
if (child.exitCode === null && child.signalCode === null) {
|
||||||
@@ -1314,7 +1021,6 @@ function stopBackend(): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
|
async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
|
||||||
cancelBackendReadinessWait();
|
|
||||||
if (restartTimer) {
|
if (restartTimer) {
|
||||||
clearTimeout(restartTimer);
|
clearTimeout(restartTimer);
|
||||||
restartTimer = null;
|
restartTimer = null;
|
||||||
@@ -1325,7 +1031,6 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
|
|||||||
if (!child) return;
|
if (!child) return;
|
||||||
const backendChild = child;
|
const backendChild = child;
|
||||||
if (backendChild.exitCode !== null || backendChild.signalCode !== null) return;
|
if (backendChild.exitCode !== null || backendChild.signalCode !== null) return;
|
||||||
expectedBackendExitChildren.add(backendChild);
|
|
||||||
|
|
||||||
await new Promise<void>((resolve) => {
|
await new Promise<void>((resolve) => {
|
||||||
let settled = false;
|
let settled = false;
|
||||||
@@ -1367,118 +1072,6 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function registerIpcHandlers(): void {
|
function registerIpcHandlers(): void {
|
||||||
ipcMain.removeAllListeners(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
|
|
||||||
ipcMain.on(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL, (event) => {
|
|
||||||
event.returnValue = {
|
|
||||||
label: "Local environment",
|
|
||||||
httpBaseUrl: backendHttpUrl || null,
|
|
||||||
wsBaseUrl: backendWsUrl || null,
|
|
||||||
bootstrapToken: backendBootstrapToken || undefined,
|
|
||||||
} as const;
|
|
||||||
});
|
|
||||||
|
|
||||||
ipcMain.removeHandler(GET_CLIENT_SETTINGS_CHANNEL);
|
|
||||||
ipcMain.handle(GET_CLIENT_SETTINGS_CHANNEL, async () => readClientSettings(CLIENT_SETTINGS_PATH));
|
|
||||||
|
|
||||||
ipcMain.removeHandler(SET_CLIENT_SETTINGS_CHANNEL);
|
|
||||||
ipcMain.handle(SET_CLIENT_SETTINGS_CHANNEL, async (_event, rawSettings: unknown) => {
|
|
||||||
if (typeof rawSettings !== "object" || rawSettings === null) {
|
|
||||||
throw new Error("Invalid client settings payload.");
|
|
||||||
}
|
|
||||||
|
|
||||||
writeClientSettings(CLIENT_SETTINGS_PATH, rawSettings as ClientSettings);
|
|
||||||
});
|
|
||||||
|
|
||||||
ipcMain.removeHandler(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL);
|
|
||||||
ipcMain.handle(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, async () =>
|
|
||||||
readSavedEnvironmentRegistry(SAVED_ENVIRONMENT_REGISTRY_PATH),
|
|
||||||
);
|
|
||||||
|
|
||||||
ipcMain.removeHandler(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL);
|
|
||||||
ipcMain.handle(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, async (_event, rawRecords: unknown) => {
|
|
||||||
if (!Array.isArray(rawRecords)) {
|
|
||||||
throw new Error("Invalid saved environment registry payload.");
|
|
||||||
}
|
|
||||||
|
|
||||||
writeSavedEnvironmentRegistry(
|
|
||||||
SAVED_ENVIRONMENT_REGISTRY_PATH,
|
|
||||||
rawRecords as readonly PersistedSavedEnvironmentRecord[],
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
ipcMain.removeHandler(GET_SAVED_ENVIRONMENT_SECRET_CHANNEL);
|
|
||||||
ipcMain.handle(
|
|
||||||
GET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
|
|
||||||
async (_event, rawEnvironmentId: unknown) => {
|
|
||||||
if (typeof rawEnvironmentId !== "string" || rawEnvironmentId.trim().length === 0) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return readSavedEnvironmentSecret({
|
|
||||||
registryPath: SAVED_ENVIRONMENT_REGISTRY_PATH,
|
|
||||||
environmentId: rawEnvironmentId,
|
|
||||||
secretStorage: getDesktopSecretStorage(),
|
|
||||||
});
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
ipcMain.removeHandler(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL);
|
|
||||||
ipcMain.handle(
|
|
||||||
SET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
|
|
||||||
async (_event, rawEnvironmentId: unknown, rawSecret: unknown) => {
|
|
||||||
if (typeof rawEnvironmentId !== "string" || rawEnvironmentId.trim().length === 0) {
|
|
||||||
throw new Error("Invalid saved environment id.");
|
|
||||||
}
|
|
||||||
if (typeof rawSecret !== "string" || rawSecret.trim().length === 0) {
|
|
||||||
throw new Error("Invalid saved environment secret.");
|
|
||||||
}
|
|
||||||
|
|
||||||
return writeSavedEnvironmentSecret({
|
|
||||||
registryPath: SAVED_ENVIRONMENT_REGISTRY_PATH,
|
|
||||||
environmentId: rawEnvironmentId,
|
|
||||||
secret: rawSecret,
|
|
||||||
secretStorage: getDesktopSecretStorage(),
|
|
||||||
});
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
ipcMain.removeHandler(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL);
|
|
||||||
ipcMain.handle(
|
|
||||||
REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL,
|
|
||||||
async (_event, rawEnvironmentId: unknown) => {
|
|
||||||
if (typeof rawEnvironmentId !== "string" || rawEnvironmentId.trim().length === 0) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
removeSavedEnvironmentSecret({
|
|
||||||
registryPath: SAVED_ENVIRONMENT_REGISTRY_PATH,
|
|
||||||
environmentId: rawEnvironmentId,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
ipcMain.removeHandler(GET_SERVER_EXPOSURE_STATE_CHANNEL);
|
|
||||||
ipcMain.handle(GET_SERVER_EXPOSURE_STATE_CHANNEL, async () => getDesktopServerExposureState());
|
|
||||||
|
|
||||||
ipcMain.removeHandler(SET_SERVER_EXPOSURE_MODE_CHANNEL);
|
|
||||||
ipcMain.handle(SET_SERVER_EXPOSURE_MODE_CHANNEL, async (_event, rawMode: unknown) => {
|
|
||||||
if (rawMode !== "local-only" && rawMode !== "network-accessible") {
|
|
||||||
throw new Error("Invalid desktop server exposure input.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const nextMode = rawMode as DesktopServerExposureMode;
|
|
||||||
if (nextMode === desktopServerExposureMode) {
|
|
||||||
return getDesktopServerExposureState();
|
|
||||||
}
|
|
||||||
|
|
||||||
const nextState = await applyDesktopServerExposureMode(nextMode, {
|
|
||||||
persist: true,
|
|
||||||
rejectIfUnavailable: true,
|
|
||||||
});
|
|
||||||
relaunchDesktopApp(`serverExposureMode=${nextMode}`);
|
|
||||||
return nextState;
|
|
||||||
});
|
|
||||||
|
|
||||||
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
|
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
|
||||||
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
|
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
|
||||||
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
|
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
|
||||||
@@ -1523,7 +1116,6 @@ function registerIpcHandlers(): void {
|
|||||||
id: item.id,
|
id: item.id,
|
||||||
label: item.label,
|
label: item.label,
|
||||||
destructive: item.destructive === true,
|
destructive: item.destructive === true,
|
||||||
disabled: item.disabled === true,
|
|
||||||
}));
|
}));
|
||||||
if (normalizedItems.length === 0) {
|
if (normalizedItems.length === 0) {
|
||||||
return null;
|
return null;
|
||||||
@@ -1554,7 +1146,6 @@ function registerIpcHandlers(): void {
|
|||||||
}
|
}
|
||||||
const itemOption: MenuItemConstructorOptions = {
|
const itemOption: MenuItemConstructorOptions = {
|
||||||
label: item.label,
|
label: item.label,
|
||||||
enabled: !item.disabled,
|
|
||||||
click: () => resolve(item.id),
|
click: () => resolve(item.id),
|
||||||
};
|
};
|
||||||
if (item.destructive) {
|
if (item.destructive) {
|
||||||
@@ -1620,21 +1211,6 @@ function registerIpcHandlers(): void {
|
|||||||
state: updateState,
|
state: updateState,
|
||||||
} satisfies DesktopUpdateActionResult;
|
} satisfies DesktopUpdateActionResult;
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcMain.removeHandler(UPDATE_CHECK_CHANNEL);
|
|
||||||
ipcMain.handle(UPDATE_CHECK_CHANNEL, async () => {
|
|
||||||
if (!updaterConfigured) {
|
|
||||||
return {
|
|
||||||
checked: false,
|
|
||||||
state: updateState,
|
|
||||||
} satisfies DesktopUpdateCheckResult;
|
|
||||||
}
|
|
||||||
const checked = await checkForUpdates("web-ui");
|
|
||||||
return {
|
|
||||||
checked,
|
|
||||||
state: updateState,
|
|
||||||
} satisfies DesktopUpdateCheckResult;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function getIconOption(): { icon: string } | Record<string, never> {
|
function getIconOption(): { icon: string } | Record<string, never> {
|
||||||
@@ -1644,19 +1220,14 @@ function getIconOption(): { icon: string } | Record<string, never> {
|
|||||||
return iconPath ? { icon: iconPath } : {};
|
return iconPath ? { icon: iconPath } : {};
|
||||||
}
|
}
|
||||||
|
|
||||||
function getInitialWindowBackgroundColor(): string {
|
|
||||||
return nativeTheme.shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
|
|
||||||
}
|
|
||||||
|
|
||||||
function createWindow(): BrowserWindow {
|
function createWindow(): BrowserWindow {
|
||||||
const window = new BrowserWindow({
|
const window = new BrowserWindow({
|
||||||
width: 1100,
|
width: 1100,
|
||||||
height: 780,
|
height: 780,
|
||||||
minWidth: 840,
|
minWidth: 840,
|
||||||
minHeight: 620,
|
minHeight: 620,
|
||||||
show: isDevelopment,
|
show: false,
|
||||||
autoHideMenuBar: true,
|
autoHideMenuBar: true,
|
||||||
backgroundColor: getInitialWindowBackgroundColor(),
|
|
||||||
...getIconOption(),
|
...getIconOption(),
|
||||||
title: APP_DISPLAY_NAME,
|
title: APP_DISPLAY_NAME,
|
||||||
titleBarStyle: "hiddenInset",
|
titleBarStyle: "hiddenInset",
|
||||||
@@ -1687,14 +1258,6 @@ function createWindow(): BrowserWindow {
|
|||||||
menuTemplate.push({ type: "separator" });
|
menuTemplate.push({ type: "separator" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const externalUrl = getSafeExternalUrl(params.linkURL);
|
|
||||||
if (externalUrl) {
|
|
||||||
menuTemplate.push(
|
|
||||||
{ label: "Copy Link", click: () => clipboard.writeText(params.linkURL) },
|
|
||||||
{ type: "separator" },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
menuTemplate.push(
|
menuTemplate.push(
|
||||||
{ role: "cut", enabled: params.editFlags.canCut },
|
{ role: "cut", enabled: params.editFlags.canCut },
|
||||||
{ role: "copy", enabled: params.editFlags.canCopy },
|
{ role: "copy", enabled: params.editFlags.canCopy },
|
||||||
@@ -1721,20 +1284,15 @@ function createWindow(): BrowserWindow {
|
|||||||
window.setTitle(APP_DISPLAY_NAME);
|
window.setTitle(APP_DISPLAY_NAME);
|
||||||
emitUpdateState();
|
emitUpdateState();
|
||||||
});
|
});
|
||||||
if (!isDevelopment) {
|
window.once("ready-to-show", () => {
|
||||||
window.once("ready-to-show", () => {
|
window.show();
|
||||||
revealWindow(window);
|
});
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isDevelopment) {
|
if (isDevelopment) {
|
||||||
void window.loadURL(resolveDesktopDevServerUrl());
|
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
|
||||||
window.webContents.openDevTools({ mode: "detach" });
|
window.webContents.openDevTools({ mode: "detach" });
|
||||||
setImmediate(() => {
|
|
||||||
revealWindow(window);
|
|
||||||
});
|
|
||||||
} else {
|
} else {
|
||||||
void window.loadURL(resolveDesktopWindowUrl());
|
void window.loadURL(`${DESKTOP_SCHEME}://app/index.html`);
|
||||||
}
|
}
|
||||||
|
|
||||||
window.on("closed", () => {
|
window.on("closed", () => {
|
||||||
@@ -1746,14 +1304,6 @@ function createWindow(): BrowserWindow {
|
|||||||
return window;
|
return window;
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveDesktopWindowUrl(): string {
|
|
||||||
if (backendHttpUrl) {
|
|
||||||
return backendHttpUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
return `${DESKTOP_SCHEME}://app`;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Override Electron's userData path before the `ready` event so that
|
// Override Electron's userData path before the `ready` event so that
|
||||||
// Chromium session data uses a filesystem-friendly directory name.
|
// Chromium session data uses a filesystem-friendly directory name.
|
||||||
// Must be called synchronously at the top level — before `app.whenReady()`.
|
// Must be called synchronously at the top level — before `app.whenReady()`.
|
||||||
@@ -1763,81 +1313,29 @@ configureAppIdentity();
|
|||||||
|
|
||||||
async function bootstrap(): Promise<void> {
|
async function bootstrap(): Promise<void> {
|
||||||
writeDesktopLogHeader("bootstrap start");
|
writeDesktopLogHeader("bootstrap start");
|
||||||
const configuredBackendPort = resolveConfiguredDesktopBackendPort(process.env.T3CODE_PORT);
|
backendPort = await Effect.service(NetService).pipe(
|
||||||
if (isDevelopment && configuredBackendPort === undefined) {
|
Effect.flatMap((net) => net.reserveLoopbackPort()),
|
||||||
throw new Error("T3CODE_PORT is required in desktop development.");
|
Effect.provide(NetService.layer),
|
||||||
}
|
Effect.runPromise,
|
||||||
|
|
||||||
backendPort =
|
|
||||||
configuredBackendPort ??
|
|
||||||
(await resolveDesktopBackendPort({
|
|
||||||
host: DESKTOP_LOOPBACK_HOST,
|
|
||||||
startPort: DEFAULT_DESKTOP_BACKEND_PORT,
|
|
||||||
}));
|
|
||||||
writeDesktopLogHeader(
|
|
||||||
configuredBackendPort === undefined
|
|
||||||
? `selected backend port via sequential scan startPort=${DEFAULT_DESKTOP_BACKEND_PORT} port=${backendPort}`
|
|
||||||
: `using configured backend port port=${backendPort}`,
|
|
||||||
);
|
);
|
||||||
backendBootstrapToken = Crypto.randomBytes(24).toString("hex");
|
writeDesktopLogHeader(`reserved backend port via NetService port=${backendPort}`);
|
||||||
if (desktopSettings.serverExposureMode !== DEFAULT_DESKTOP_SETTINGS.serverExposureMode) {
|
backendAuthToken = Crypto.randomBytes(24).toString("hex");
|
||||||
writeDesktopLogHeader(
|
backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
|
||||||
`bootstrap restoring persisted server exposure mode mode=${desktopSettings.serverExposureMode}`,
|
process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
|
||||||
);
|
writeDesktopLogHeader(`bootstrap resolved websocket url=${backendWsUrl}`);
|
||||||
}
|
|
||||||
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();
|
registerIpcHandlers();
|
||||||
writeDesktopLogHeader("bootstrap ipc handlers registered");
|
writeDesktopLogHeader("bootstrap ipc handlers registered");
|
||||||
startBackend();
|
startBackend();
|
||||||
writeDesktopLogHeader("bootstrap backend start requested");
|
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();
|
mainWindow = createWindow();
|
||||||
writeDesktopLogHeader("bootstrap main window created");
|
writeDesktopLogHeader("bootstrap main window created");
|
||||||
}
|
}
|
||||||
|
|
||||||
app.on("before-quit", () => {
|
app.on("before-quit", () => {
|
||||||
isQuitting = true;
|
isQuitting = true;
|
||||||
updateInstallInFlight = false;
|
|
||||||
writeDesktopLogHeader("before-quit received");
|
writeDesktopLogHeader("before-quit received");
|
||||||
clearUpdatePollTimer();
|
clearUpdatePollTimer();
|
||||||
cancelBackendReadinessWait();
|
|
||||||
stopBackend();
|
stopBackend();
|
||||||
restoreStdIoCapture?.();
|
restoreStdIoCapture?.();
|
||||||
});
|
});
|
||||||
@@ -1851,19 +1349,13 @@ app
|
|||||||
registerDesktopProtocol();
|
registerDesktopProtocol();
|
||||||
configureAutoUpdater();
|
configureAutoUpdater();
|
||||||
void bootstrap().catch((error) => {
|
void bootstrap().catch((error) => {
|
||||||
if (isBackendReadinessAborted(error) && isQuitting) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
handleFatalStartupError("bootstrap", error);
|
handleFatalStartupError("bootstrap", error);
|
||||||
});
|
});
|
||||||
|
|
||||||
app.on("activate", () => {
|
app.on("activate", () => {
|
||||||
const existingWindow = mainWindow ?? BrowserWindow.getAllWindows()[0];
|
if (BrowserWindow.getAllWindows().length === 0) {
|
||||||
if (existingWindow) {
|
mainWindow = createWindow();
|
||||||
revealWindow(existingWindow);
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
mainWindow = createWindow();
|
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
@@ -1871,7 +1363,7 @@ app
|
|||||||
});
|
});
|
||||||
|
|
||||||
app.on("window-all-closed", () => {
|
app.on("window-all-closed", () => {
|
||||||
if (process.platform !== "darwin" && !isQuitting) {
|
if (process.platform !== "darwin") {
|
||||||
app.quit();
|
app.quit();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -1882,7 +1374,6 @@ if (process.platform !== "win32") {
|
|||||||
isQuitting = true;
|
isQuitting = true;
|
||||||
writeDesktopLogHeader("SIGINT received");
|
writeDesktopLogHeader("SIGINT received");
|
||||||
clearUpdatePollTimer();
|
clearUpdatePollTimer();
|
||||||
cancelBackendReadinessWait();
|
|
||||||
stopBackend();
|
stopBackend();
|
||||||
restoreStdIoCapture?.();
|
restoreStdIoCapture?.();
|
||||||
app.quit();
|
app.quit();
|
||||||
|
|||||||
@@ -9,41 +9,12 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
|||||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||||
const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||||
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||||
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
|
||||||
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||||
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
|
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
||||||
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", {
|
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||||
getLocalEnvironmentBootstrap: () => {
|
getWsUrl: () => wsUrl,
|
||||||
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),
|
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
|
||||||
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
||||||
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
|
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
|
||||||
@@ -61,7 +32,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
|||||||
};
|
};
|
||||||
},
|
},
|
||||||
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
|
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
|
||||||
checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL),
|
|
||||||
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
|
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
|
||||||
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
|
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
|
||||||
onUpdateState: (listener) => {
|
onUpdateState: (listener) => {
|
||||||
|
|||||||
@@ -1,139 +0,0 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
|
||||||
|
|
||||||
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure";
|
|
||||||
|
|
||||||
describe("resolveLanAdvertisedHost", () => {
|
|
||||||
it("prefers an explicit host override", () => {
|
|
||||||
expect(
|
|
||||||
resolveLanAdvertisedHost(
|
|
||||||
{
|
|
||||||
en0: [
|
|
||||||
{
|
|
||||||
address: "192.168.1.44",
|
|
||||||
family: "IPv4",
|
|
||||||
internal: false,
|
|
||||||
netmask: "255.255.255.0",
|
|
||||||
cidr: "192.168.1.44/24",
|
|
||||||
mac: "00:00:00:00:00:00",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
"10.0.0.9",
|
|
||||||
),
|
|
||||||
).toBe("10.0.0.9");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns the first usable non-internal IPv4 address", () => {
|
|
||||||
expect(
|
|
||||||
resolveLanAdvertisedHost(
|
|
||||||
{
|
|
||||||
lo0: [
|
|
||||||
{
|
|
||||||
address: "127.0.0.1",
|
|
||||||
family: "IPv4",
|
|
||||||
internal: true,
|
|
||||||
netmask: "255.0.0.0",
|
|
||||||
cidr: "127.0.0.1/8",
|
|
||||||
mac: "00:00:00:00:00:00",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
en0: [
|
|
||||||
{
|
|
||||||
address: "192.168.1.44",
|
|
||||||
family: "IPv4",
|
|
||||||
internal: false,
|
|
||||||
netmask: "255.255.255.0",
|
|
||||||
cidr: "192.168.1.44/24",
|
|
||||||
mac: "00:00:00:00:00:00",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
undefined,
|
|
||||||
),
|
|
||||||
).toBe("192.168.1.44");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns null when no usable network address is available", () => {
|
|
||||||
expect(
|
|
||||||
resolveLanAdvertisedHost(
|
|
||||||
{
|
|
||||||
lo0: [
|
|
||||||
{
|
|
||||||
address: "127.0.0.1",
|
|
||||||
family: "IPv4",
|
|
||||||
internal: true,
|
|
||||||
netmask: "255.0.0.0",
|
|
||||||
cidr: "127.0.0.1/8",
|
|
||||||
mac: "00:00:00:00:00:00",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
undefined,
|
|
||||||
),
|
|
||||||
).toBeNull();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("resolveDesktopServerExposure", () => {
|
|
||||||
it("keeps the desktop server loopback-only when local-only mode is selected", () => {
|
|
||||||
expect(
|
|
||||||
resolveDesktopServerExposure({
|
|
||||||
mode: "local-only",
|
|
||||||
port: 3773,
|
|
||||||
networkInterfaces: {},
|
|
||||||
}),
|
|
||||||
).toEqual({
|
|
||||||
mode: "local-only",
|
|
||||||
bindHost: "127.0.0.1",
|
|
||||||
localHttpUrl: "http://127.0.0.1:3773",
|
|
||||||
localWsUrl: "ws://127.0.0.1:3773",
|
|
||||||
endpointUrl: null,
|
|
||||||
advertisedHost: null,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("binds to all interfaces in network-accessible mode", () => {
|
|
||||||
expect(
|
|
||||||
resolveDesktopServerExposure({
|
|
||||||
mode: "network-accessible",
|
|
||||||
port: 3773,
|
|
||||||
networkInterfaces: {
|
|
||||||
en0: [
|
|
||||||
{
|
|
||||||
address: "192.168.1.44",
|
|
||||||
family: "IPv4",
|
|
||||||
internal: false,
|
|
||||||
netmask: "255.255.255.0",
|
|
||||||
cidr: "192.168.1.44/24",
|
|
||||||
mac: "00:00:00:00:00:00",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
).toEqual({
|
|
||||||
mode: "network-accessible",
|
|
||||||
bindHost: "0.0.0.0",
|
|
||||||
localHttpUrl: "http://127.0.0.1:3773",
|
|
||||||
localWsUrl: "ws://127.0.0.1:3773",
|
|
||||||
endpointUrl: "http://192.168.1.44:3773",
|
|
||||||
advertisedHost: "192.168.1.44",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("stays network-accessible even when no LAN address is currently detectable", () => {
|
|
||||||
expect(
|
|
||||||
resolveDesktopServerExposure({
|
|
||||||
mode: "network-accessible",
|
|
||||||
port: 3773,
|
|
||||||
networkInterfaces: {},
|
|
||||||
}),
|
|
||||||
).toEqual({
|
|
||||||
mode: "network-accessible",
|
|
||||||
bindHost: "0.0.0.0",
|
|
||||||
localHttpUrl: "http://127.0.0.1:3773",
|
|
||||||
localWsUrl: "ws://127.0.0.1:3773",
|
|
||||||
endpointUrl: null,
|
|
||||||
advertisedHost: null,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
import type { NetworkInterfaceInfo } from "node:os";
|
|
||||||
import type { DesktopServerExposureMode } from "@t3tools/contracts";
|
|
||||||
|
|
||||||
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
|
|
||||||
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
|
|
||||||
|
|
||||||
export interface DesktopServerExposure {
|
|
||||||
readonly mode: DesktopServerExposureMode;
|
|
||||||
readonly bindHost: string;
|
|
||||||
readonly localHttpUrl: string;
|
|
||||||
readonly localWsUrl: string;
|
|
||||||
readonly endpointUrl: string | null;
|
|
||||||
readonly advertisedHost: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const normalizeOptionalHost = (value: string | undefined): string | undefined => {
|
|
||||||
const normalized = value?.trim();
|
|
||||||
return normalized && normalized.length > 0 ? normalized : undefined;
|
|
||||||
};
|
|
||||||
|
|
||||||
const isUsableLanIpv4Address = (address: string): boolean =>
|
|
||||||
!address.startsWith("127.") && !address.startsWith("169.254.");
|
|
||||||
|
|
||||||
export function resolveLanAdvertisedHost(
|
|
||||||
networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>,
|
|
||||||
explicitHost: string | undefined,
|
|
||||||
): string | null {
|
|
||||||
const normalizedExplicitHost = normalizeOptionalHost(explicitHost);
|
|
||||||
if (normalizedExplicitHost) {
|
|
||||||
return normalizedExplicitHost;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const interfaceAddresses of Object.values(networkInterfaces)) {
|
|
||||||
if (!interfaceAddresses) continue;
|
|
||||||
|
|
||||||
for (const address of interfaceAddresses) {
|
|
||||||
if (address.internal) continue;
|
|
||||||
if (address.family !== "IPv4") continue;
|
|
||||||
if (!isUsableLanIpv4Address(address.address)) continue;
|
|
||||||
return address.address;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function resolveDesktopServerExposure(input: {
|
|
||||||
readonly mode: DesktopServerExposureMode;
|
|
||||||
readonly port: number;
|
|
||||||
readonly networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>;
|
|
||||||
readonly advertisedHostOverride?: string;
|
|
||||||
}): DesktopServerExposure {
|
|
||||||
const localHttpUrl = `http://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
|
|
||||||
const localWsUrl = `ws://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
|
|
||||||
|
|
||||||
if (input.mode === "local-only") {
|
|
||||||
return {
|
|
||||||
mode: input.mode,
|
|
||||||
bindHost: DESKTOP_LOOPBACK_HOST,
|
|
||||||
localHttpUrl,
|
|
||||||
localWsUrl,
|
|
||||||
endpointUrl: null,
|
|
||||||
advertisedHost: null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const advertisedHost = resolveLanAdvertisedHost(
|
|
||||||
input.networkInterfaces,
|
|
||||||
input.advertisedHostOverride,
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
mode: input.mode,
|
|
||||||
bindHost: DESKTOP_LAN_BIND_HOST,
|
|
||||||
localHttpUrl,
|
|
||||||
localWsUrl,
|
|
||||||
endpointUrl: advertisedHost ? `http://${advertisedHost}:${input.port}` : null,
|
|
||||||
advertisedHost,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -62,13 +62,14 @@ describe("syncShellEnvironment", () => {
|
|||||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () => {
|
it("does nothing outside macOS", () => {
|
||||||
const env: NodeJS.ProcessEnv = {
|
const env: NodeJS.ProcessEnv = {
|
||||||
SHELL: "/bin/zsh",
|
SHELL: "/bin/zsh",
|
||||||
PATH: "/usr/bin",
|
PATH: "/usr/bin",
|
||||||
|
SSH_AUTH_SOCK: "/tmp/inherited.sock",
|
||||||
};
|
};
|
||||||
const readEnvironment = vi.fn(() => ({
|
const readEnvironment = vi.fn(() => ({
|
||||||
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
|
PATH: "/opt/homebrew/bin:/usr/bin",
|
||||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -77,29 +78,8 @@ describe("syncShellEnvironment", () => {
|
|||||||
readEnvironment,
|
readEnvironment,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
|
||||||
expect(env.PATH).toBe("/home/linuxbrew/.linuxbrew/bin:/usr/bin");
|
|
||||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does nothing outside macOS and linux", () => {
|
|
||||||
const env: NodeJS.ProcessEnv = {
|
|
||||||
SHELL: "C:/Program Files/Git/bin/bash.exe",
|
|
||||||
PATH: "C:\\Windows\\System32",
|
|
||||||
SSH_AUTH_SOCK: "/tmp/inherited.sock",
|
|
||||||
};
|
|
||||||
const readEnvironment = vi.fn(() => ({
|
|
||||||
PATH: "/usr/local/bin:/usr/bin",
|
|
||||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
|
||||||
}));
|
|
||||||
|
|
||||||
syncShellEnvironment(env, {
|
|
||||||
platform: "win32",
|
|
||||||
readEnvironment,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(readEnvironment).not.toHaveBeenCalled();
|
expect(readEnvironment).not.toHaveBeenCalled();
|
||||||
expect(env.PATH).toBe("C:\\Windows\\System32");
|
expect(env.PATH).toBe("/usr/bin");
|
||||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -1,8 +1,4 @@
|
|||||||
import {
|
import { readEnvironmentFromLoginShell, ShellEnvironmentReader } from "@t3tools/shared/shell";
|
||||||
readEnvironmentFromLoginShell,
|
|
||||||
resolveLoginShell,
|
|
||||||
ShellEnvironmentReader,
|
|
||||||
} from "@t3tools/shared/shell";
|
|
||||||
|
|
||||||
export function syncShellEnvironment(
|
export function syncShellEnvironment(
|
||||||
env: NodeJS.ProcessEnv = process.env,
|
env: NodeJS.ProcessEnv = process.env,
|
||||||
@@ -11,13 +7,10 @@ export function syncShellEnvironment(
|
|||||||
readEnvironment?: ShellEnvironmentReader;
|
readEnvironment?: ShellEnvironmentReader;
|
||||||
} = {},
|
} = {},
|
||||||
): void {
|
): void {
|
||||||
const platform = options.platform ?? process.platform;
|
if ((options.platform ?? process.platform) !== "darwin") return;
|
||||||
if (platform !== "darwin" && platform !== "linux") return;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const shell = resolveLoginShell(platform, env.SHELL);
|
const shell = env.SHELL ?? "/bin/zsh";
|
||||||
if (!shell) return;
|
|
||||||
|
|
||||||
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
|
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
|
||||||
"PATH",
|
"PATH",
|
||||||
"SSH_AUTH_SOCK",
|
"SSH_AUTH_SOCK",
|
||||||
|
|||||||
@@ -71,37 +71,10 @@ describe("getAutoUpdateDisabledReason", () => {
|
|||||||
platform: "darwin",
|
platform: "darwin",
|
||||||
appImage: undefined,
|
appImage: undefined,
|
||||||
disabledByEnv: false,
|
disabledByEnv: false,
|
||||||
hasUpdateFeedConfig: true,
|
|
||||||
}),
|
}),
|
||||||
).toContain("packaged production builds");
|
).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", () => {
|
it("reports env-disabled auto updates", () => {
|
||||||
expect(
|
expect(
|
||||||
getAutoUpdateDisabledReason({
|
getAutoUpdateDisabledReason({
|
||||||
@@ -110,7 +83,6 @@ describe("getAutoUpdateDisabledReason", () => {
|
|||||||
platform: "darwin",
|
platform: "darwin",
|
||||||
appImage: undefined,
|
appImage: undefined,
|
||||||
disabledByEnv: true,
|
disabledByEnv: true,
|
||||||
hasUpdateFeedConfig: true,
|
|
||||||
}),
|
}),
|
||||||
).toContain("T3CODE_DISABLE_AUTO_UPDATE");
|
).toContain("T3CODE_DISABLE_AUTO_UPDATE");
|
||||||
});
|
});
|
||||||
@@ -123,7 +95,6 @@ describe("getAutoUpdateDisabledReason", () => {
|
|||||||
platform: "linux",
|
platform: "linux",
|
||||||
appImage: undefined,
|
appImage: undefined,
|
||||||
disabledByEnv: false,
|
disabledByEnv: false,
|
||||||
hasUpdateFeedConfig: true,
|
|
||||||
}),
|
}),
|
||||||
).toContain("AppImage");
|
).toContain("AppImage");
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -34,11 +34,7 @@ export function getAutoUpdateDisabledReason(args: {
|
|||||||
platform: NodeJS.Platform;
|
platform: NodeJS.Platform;
|
||||||
appImage?: string | undefined;
|
appImage?: string | undefined;
|
||||||
disabledByEnv: boolean;
|
disabledByEnv: boolean;
|
||||||
hasUpdateFeedConfig: boolean;
|
|
||||||
}): string | null {
|
}): string | null {
|
||||||
if (!args.hasUpdateFeedConfig) {
|
|
||||||
return "Automatic updates are not available because no update feed is configured.";
|
|
||||||
}
|
|
||||||
if (args.isDevelopment || !args.isPackaged) {
|
if (args.isDevelopment || !args.isPackaged) {
|
||||||
return "Automatic updates are only available in packaged production builds.";
|
return "Automatic updates are only available in packaged production builds.";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
---
|
---
|
||||||
import Layout from "../layouts/Layout.astro";
|
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.">
|
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
|
||||||
@@ -18,11 +17,11 @@ import { RELEASES_URL } from "../lib/releases";
|
|||||||
<h2 class="platform-name">macOS</h2>
|
<h2 class="platform-name">macOS</h2>
|
||||||
</div>
|
</div>
|
||||||
<div class="download-cards">
|
<div class="download-cards">
|
||||||
<a class="download-card" data-asset="arm64.dmg" href={RELEASES_URL}>
|
<a class="download-card" data-asset="arm64.dmg" href="#">
|
||||||
<span class="card-arch">Apple Silicon (arm64)</span>
|
<span class="card-arch">Apple Silicon (arm64)</span>
|
||||||
<span class="card-format">.dmg</span>
|
<span class="card-format">.dmg</span>
|
||||||
</a>
|
</a>
|
||||||
<a class="download-card" data-asset="x64.dmg" href={RELEASES_URL}>
|
<a class="download-card" data-asset="x64.dmg" href="#">
|
||||||
<span class="card-arch">Intel (x64)</span>
|
<span class="card-arch">Intel (x64)</span>
|
||||||
<span class="card-format">.dmg</span>
|
<span class="card-format">.dmg</span>
|
||||||
</a>
|
</a>
|
||||||
@@ -36,7 +35,7 @@ import { RELEASES_URL } from "../lib/releases";
|
|||||||
<h2 class="platform-name">Windows</h2>
|
<h2 class="platform-name">Windows</h2>
|
||||||
</div>
|
</div>
|
||||||
<div class="download-cards">
|
<div class="download-cards">
|
||||||
<a class="download-card" data-asset="x64.exe" href={RELEASES_URL}>
|
<a class="download-card" data-asset="x64.exe" href="#">
|
||||||
<span class="card-arch">Windows 10, 11</span>
|
<span class="card-arch">Windows 10, 11</span>
|
||||||
<span class="card-format">.exe</span>
|
<span class="card-format">.exe</span>
|
||||||
</a>
|
</a>
|
||||||
@@ -50,7 +49,7 @@ import { RELEASES_URL } from "../lib/releases";
|
|||||||
<h2 class="platform-name">Linux</h2>
|
<h2 class="platform-name">Linux</h2>
|
||||||
</div>
|
</div>
|
||||||
<div class="download-cards">
|
<div class="download-cards">
|
||||||
<a class="download-card" data-asset="x86_64.AppImage" href={RELEASES_URL}>
|
<a class="download-card" data-asset="x86_64.AppImage" href="#">
|
||||||
<span class="card-arch">x86_64</span>
|
<span class="card-arch">x86_64</span>
|
||||||
<span class="card-format">AppImage</span>
|
<span class="card-format">AppImage</span>
|
||||||
</a>
|
</a>
|
||||||
|
|||||||
@@ -1,20 +1,20 @@
|
|||||||
|
import fs from "node:fs";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
import { execFileSync } from "node:child_process";
|
import { execFileSync } from "node:child_process";
|
||||||
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
import {
|
import {
|
||||||
ApprovalRequestId,
|
ApprovalRequestId,
|
||||||
ProviderKind,
|
|
||||||
type OrchestrationEvent,
|
type OrchestrationEvent,
|
||||||
type OrchestrationThread,
|
type OrchestrationThread,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import {
|
import {
|
||||||
Effect,
|
Effect,
|
||||||
Exit,
|
Exit,
|
||||||
FileSystem,
|
|
||||||
Layer,
|
Layer,
|
||||||
ManagedRuntime,
|
ManagedRuntime,
|
||||||
Option,
|
Option,
|
||||||
Path,
|
|
||||||
Ref,
|
Ref,
|
||||||
Schedule,
|
Schedule,
|
||||||
Schema,
|
Schema,
|
||||||
@@ -24,9 +24,7 @@ import {
|
|||||||
|
|
||||||
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
||||||
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
|
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 { 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 { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
|
||||||
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
|
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||||
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
|
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
|
||||||
@@ -39,18 +37,16 @@ import { ProjectionPendingApprovalRepository } from "../src/persistence/Services
|
|||||||
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
|
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
|
||||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
|
||||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||||
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
|
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
|
||||||
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
|
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
|
||||||
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
|
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
|
||||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||||
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.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 { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
|
||||||
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
|
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
|
||||||
import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
|
import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
|
||||||
import { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
|
import { RuntimeReceiptBusLive } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
|
||||||
import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
|
import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
|
||||||
import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
|
import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
|
||||||
import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
|
import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
|
||||||
@@ -69,9 +65,7 @@ import {
|
|||||||
makeTestProviderAdapterHarness,
|
makeTestProviderAdapterHarness,
|
||||||
type TestProviderAdapterHarness,
|
type TestProviderAdapterHarness,
|
||||||
} from "./TestProviderAdapter.integration.ts";
|
} from "./TestProviderAdapter.integration.ts";
|
||||||
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
|
import { ServerConfig } from "../src/config.ts";
|
||||||
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
|
|
||||||
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
|
|
||||||
|
|
||||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||||
return execFileSync("git", args, {
|
return execFileSync("git", args, {
|
||||||
@@ -81,16 +75,14 @@ function runGit(cwd: string, args: ReadonlyArray<string>) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const initializeGitWorkspace = Effect.fn(function* (cwd: string) {
|
function initializeGitWorkspace(cwd: string) {
|
||||||
runGit(cwd, ["init", "--initial-branch=main"]);
|
runGit(cwd, ["init", "--initial-branch=main"]);
|
||||||
runGit(cwd, ["config", "user.email", "[email protected]"]);
|
runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||||
runGit(cwd, ["config", "user.name", "Test User"]);
|
runGit(cwd, ["config", "user.name", "Test User"]);
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
fs.writeFileSync(path.join(cwd, "README.md"), "v1\n", "utf8");
|
||||||
const { join } = yield* Path.Path;
|
|
||||||
yield* fileSystem.writeFileString(join(cwd, "README.md"), "v1\n");
|
|
||||||
runGit(cwd, ["add", "."]);
|
runGit(cwd, ["add", "."]);
|
||||||
runGit(cwd, ["commit", "-m", "Initial"]);
|
runGit(cwd, ["commit", "-m", "Initial"]);
|
||||||
});
|
}
|
||||||
|
|
||||||
export function gitRefExists(cwd: string, ref: string): boolean {
|
export function gitRefExists(cwd: string, ref: string): boolean {
|
||||||
try {
|
try {
|
||||||
@@ -128,7 +120,7 @@ function waitFor<A, E>(
|
|||||||
read: Effect.Effect<A, E>,
|
read: Effect.Effect<A, E>,
|
||||||
predicate: (value: A) => boolean,
|
predicate: (value: A) => boolean,
|
||||||
description: string,
|
description: string,
|
||||||
timeoutMs = 40_000,
|
timeoutMs = 10_000,
|
||||||
): Effect.Effect<A, never> {
|
): Effect.Effect<A, never> {
|
||||||
const RETRY_SIGNAL = "wait_for_retry";
|
const RETRY_SIGNAL = "wait_for_retry";
|
||||||
const retryIntervalMs = 10;
|
const retryIntervalMs = 10;
|
||||||
@@ -213,7 +205,7 @@ export interface OrchestrationIntegrationHarness {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface MakeOrchestrationIntegrationHarnessOptions {
|
interface MakeOrchestrationIntegrationHarnessOptions {
|
||||||
readonly provider?: ProviderKind;
|
readonly provider?: "codex";
|
||||||
readonly realCodex?: boolean;
|
readonly realCodex?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -221,9 +213,7 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
options?: MakeOrchestrationIntegrationHarnessOptions,
|
options?: MakeOrchestrationIntegrationHarnessOptions,
|
||||||
) =>
|
) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const path = yield* Path.Path;
|
const sleep = (ms: number) => Effect.sleep(ms);
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
|
||||||
|
|
||||||
const provider = options?.provider ?? "codex";
|
const provider = options?.provider ?? "codex";
|
||||||
const useRealCodex = options?.realCodex === true;
|
const useRealCodex = options?.realCodex === true;
|
||||||
const adapterHarness = useRealCodex
|
const adapterHarness = useRealCodex
|
||||||
@@ -240,16 +230,13 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
listProviders: () => Effect.succeed([adapterHarness.provider]),
|
listProviders: () => Effect.succeed([adapterHarness.provider]),
|
||||||
} as typeof ProviderAdapterRegistry.Service)
|
} as typeof ProviderAdapterRegistry.Service)
|
||||||
: null;
|
: null;
|
||||||
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
|
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
|
||||||
prefix: "t3-orchestration-integration-",
|
|
||||||
});
|
|
||||||
const workspaceDir = path.join(rootDir, "workspace");
|
const workspaceDir = path.join(rootDir, "workspace");
|
||||||
const { stateDir, dbPath } = yield* deriveServerPaths(rootDir, undefined).pipe(
|
const stateDir = path.join(rootDir, "state");
|
||||||
Effect.provideService(Path.Path, path),
|
const dbPath = path.join(stateDir, "state.sqlite");
|
||||||
);
|
fs.mkdirSync(workspaceDir, { recursive: true });
|
||||||
yield* fileSystem.makeDirectory(workspaceDir, { recursive: true });
|
fs.mkdirSync(stateDir, { recursive: true });
|
||||||
yield* fileSystem.makeDirectory(stateDir, { recursive: true });
|
initializeGitWorkspace(workspaceDir);
|
||||||
yield* initializeGitWorkspace(workspaceDir);
|
|
||||||
|
|
||||||
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
||||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||||
@@ -274,7 +261,7 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
}),
|
}),
|
||||||
).pipe(
|
).pipe(
|
||||||
Layer.provide(makeCodexAdapterLive()),
|
Layer.provide(makeCodexAdapterLive()),
|
||||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||||
);
|
);
|
||||||
@@ -290,75 +277,41 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
Layer.provide(AnalyticsService.layerTest),
|
Layer.provide(AnalyticsService.layerTest),
|
||||||
);
|
);
|
||||||
|
|
||||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
|
|
||||||
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
|
|
||||||
const runtimeServicesLayer = Layer.mergeAll(
|
const runtimeServicesLayer = Layer.mergeAll(
|
||||||
projectionSnapshotQueryLayer,
|
orchestrationLayer,
|
||||||
orchestrationLayer.pipe(Layer.provide(projectionSnapshotQueryLayer)),
|
OrchestrationProjectionSnapshotQueryLive,
|
||||||
ProjectionCheckpointRepositoryLive,
|
ProjectionCheckpointRepositoryLive,
|
||||||
ProjectionPendingApprovalRepositoryLive,
|
ProjectionPendingApprovalRepositoryLive,
|
||||||
checkpointStoreLayer,
|
CheckpointStoreLive,
|
||||||
providerLayer,
|
providerLayer,
|
||||||
RuntimeReceiptBusTest,
|
RuntimeReceiptBusLive,
|
||||||
);
|
);
|
||||||
const serverSettingsLayer = ServerSettingsService.layerTest();
|
|
||||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
Layer.provideMerge(serverSettingsLayer),
|
|
||||||
);
|
);
|
||||||
const gitCoreLayer = Layer.succeed(GitCore, {
|
const gitCoreLayer = Layer.succeed(GitCore, {
|
||||||
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
|
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
|
||||||
Effect.succeed({ branch: input.newBranch }),
|
Effect.succeed({ branch: input.newBranch }),
|
||||||
} as unknown as GitCoreShape);
|
} as unknown as GitCoreShape);
|
||||||
const textGenerationLayer = Layer.succeed(TextGeneration, {
|
const textGenerationLayer = Layer.succeed(TextGeneration, {
|
||||||
generateBranchName: () => Effect.succeed({ branch: "update" }),
|
generateBranchName: () => Effect.succeed({ branch: null }),
|
||||||
generateThreadTitle: () => Effect.succeed({ title: "New thread" }),
|
|
||||||
} as unknown as TextGenerationShape);
|
} as unknown as TextGenerationShape);
|
||||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
Layer.provideMerge(gitCoreLayer),
|
Layer.provideMerge(gitCoreLayer),
|
||||||
Layer.provideMerge(textGenerationLayer),
|
Layer.provideMerge(textGenerationLayer),
|
||||||
Layer.provideMerge(serverSettingsLayer),
|
|
||||||
);
|
);
|
||||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
Layer.provideMerge(
|
|
||||||
Layer.succeed(GitStatusBroadcaster, {
|
|
||||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
|
||||||
refreshLocalStatus: () =>
|
|
||||||
Effect.succeed({
|
|
||||||
isRepo: true,
|
|
||||||
hasOriginRemote: false,
|
|
||||||
isDefaultBranch: true,
|
|
||||||
branch: "main",
|
|
||||||
hasWorkingTreeChanges: false,
|
|
||||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
|
||||||
}),
|
|
||||||
refreshStatus: () => Effect.die("refreshStatus should not be called in this test"),
|
|
||||||
streamStatus: () => Stream.empty,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
Layer.provideMerge(
|
|
||||||
WorkspaceEntriesLive.pipe(
|
|
||||||
Layer.provide(WorkspacePathsLive),
|
|
||||||
Layer.provideMerge(gitCoreLayer),
|
|
||||||
Layer.provide(NodeServices.layer),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Layer.provideMerge(WorkspacePathsLive),
|
|
||||||
);
|
);
|
||||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||||
Layer.provideMerge(runtimeIngestionLayer),
|
Layer.provideMerge(runtimeIngestionLayer),
|
||||||
Layer.provideMerge(providerCommandReactorLayer),
|
Layer.provideMerge(providerCommandReactorLayer),
|
||||||
Layer.provideMerge(checkpointReactorLayer),
|
Layer.provideMerge(checkpointReactorLayer),
|
||||||
);
|
);
|
||||||
const layer = Layer.empty.pipe(
|
const layer = orchestrationReactorLayer.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
|
||||||
Layer.provideMerge(orchestrationReactorLayer),
|
|
||||||
Layer.provide(persistenceLayer),
|
Layer.provide(persistenceLayer),
|
||||||
Layer.provideMerge(RepositoryIdentityResolverLive),
|
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
|
||||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
|
||||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -392,13 +345,13 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
|
|
||||||
const scope = yield* Scope.make("sequential");
|
const scope = yield* Scope.make("sequential");
|
||||||
yield* tryRuntimePromise("start OrchestrationReactor", () =>
|
yield* tryRuntimePromise("start OrchestrationReactor", () =>
|
||||||
runtime.runPromise(reactor.start().pipe(Scope.provide(scope))),
|
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
|
||||||
).pipe(Effect.orDie);
|
).pipe(Effect.orDie);
|
||||||
const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
|
const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
|
||||||
yield* Stream.runForEach(runtimeReceiptBus.streamEventsForTest, (receipt) =>
|
yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
|
||||||
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
|
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
|
||||||
).pipe(Effect.forkIn(scope));
|
).pipe(Effect.forkIn(scope));
|
||||||
yield* Effect.sleep(10);
|
yield* sleep(10);
|
||||||
|
|
||||||
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
|
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
|
||||||
threadId,
|
threadId,
|
||||||
@@ -515,7 +468,13 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
yield* shutdown;
|
yield* shutdown.pipe(
|
||||||
|
Effect.ensuring(
|
||||||
|
Effect.sync(() => {
|
||||||
|
fs.rmSync(rootDir, { recursive: true, force: true });
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import {
|
|||||||
ProviderTurnStartResult,
|
ProviderTurnStartResult,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
TurnId,
|
TurnId,
|
||||||
ProviderKind,
|
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { Effect, Queue, Stream } from "effect";
|
import { Effect, Queue, Stream } from "effect";
|
||||||
|
|
||||||
@@ -36,7 +35,7 @@ export interface TestTurnResponse {
|
|||||||
export type FixtureProviderRuntimeEvent = {
|
export type FixtureProviderRuntimeEvent = {
|
||||||
readonly type: string;
|
readonly type: string;
|
||||||
readonly eventId: EventId;
|
readonly eventId: EventId;
|
||||||
readonly provider: ProviderKind;
|
readonly provider: "codex";
|
||||||
readonly createdAt: string;
|
readonly createdAt: string;
|
||||||
readonly threadId: string;
|
readonly threadId: string;
|
||||||
readonly turnId?: string | undefined;
|
readonly turnId?: string | undefined;
|
||||||
@@ -178,7 +177,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
|
|||||||
|
|
||||||
export interface TestProviderAdapterHarness {
|
export interface TestProviderAdapterHarness {
|
||||||
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
||||||
readonly provider: ProviderKind;
|
readonly provider: "codex";
|
||||||
readonly queueTurnResponse: (
|
readonly queueTurnResponse: (
|
||||||
threadId: ThreadId,
|
threadId: ThreadId,
|
||||||
response: TestTurnResponse,
|
response: TestTurnResponse,
|
||||||
@@ -198,7 +197,7 @@ export interface TestProviderAdapterHarness {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface MakeTestProviderAdapterHarnessOptions {
|
interface MakeTestProviderAdapterHarnessOptions {
|
||||||
readonly provider?: ProviderKind;
|
readonly provider?: "codex";
|
||||||
}
|
}
|
||||||
|
|
||||||
function nowIso(): string {
|
function nowIso(): string {
|
||||||
@@ -206,7 +205,7 @@ function nowIso(): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function sessionNotFound(
|
function sessionNotFound(
|
||||||
provider: ProviderKind,
|
provider: "codex",
|
||||||
threadId: ThreadId,
|
threadId: ThreadId,
|
||||||
): ProviderAdapterSessionNotFoundError {
|
): ProviderAdapterSessionNotFoundError {
|
||||||
return new ProviderAdapterSessionNotFoundError({
|
return new ProviderAdapterSessionNotFoundError({
|
||||||
@@ -216,7 +215,7 @@ function sessionNotFound(
|
|||||||
}
|
}
|
||||||
|
|
||||||
function missingSessionEffect(
|
function missingSessionEffect(
|
||||||
provider: ProviderKind,
|
provider: "codex",
|
||||||
threadId: ThreadId,
|
threadId: ThreadId,
|
||||||
): Effect.Effect<never, ProviderAdapterError> {
|
): Effect.Effect<never, ProviderAdapterError> {
|
||||||
return Effect.fail(sessionNotFound(provider, threadId));
|
return Effect.fail(sessionNotFound(provider, threadId));
|
||||||
|
|||||||
@@ -5,13 +5,10 @@ import {
|
|||||||
ApprovalRequestId,
|
ApprovalRequestId,
|
||||||
CommandId,
|
CommandId,
|
||||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
DEFAULT_MODEL_BY_PROVIDER,
|
|
||||||
EventId,
|
EventId,
|
||||||
MessageId,
|
MessageId,
|
||||||
ProjectId,
|
ProjectId,
|
||||||
ProviderKind,
|
|
||||||
ThreadId,
|
ThreadId,
|
||||||
ModelSelection,
|
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { assert, it } from "@effect/vitest";
|
import { assert, it } from "@effect/vitest";
|
||||||
import { Effect, Option, Schema } from "effect";
|
import { Effect, Option, Schema } from "effect";
|
||||||
@@ -28,7 +25,6 @@ import type {
|
|||||||
CheckpointDiffFinalizedReceipt,
|
CheckpointDiffFinalizedReceipt,
|
||||||
TurnProcessingQuiescedReceipt,
|
TurnProcessingQuiescedReceipt,
|
||||||
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
|
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
|
|
||||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||||
@@ -40,7 +36,7 @@ const PROJECT_ID = asProjectId("project-1");
|
|||||||
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
|
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
|
||||||
const FIXTURE_TURN_ID = "fixture-turn";
|
const FIXTURE_TURN_ID = "fixture-turn";
|
||||||
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
|
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
|
||||||
type IntegrationProvider = ProviderKind;
|
type IntegrationProvider = "codex";
|
||||||
|
|
||||||
function nowIso() {
|
function nowIso() {
|
||||||
return new Date().toISOString();
|
return new Date().toISOString();
|
||||||
@@ -53,11 +49,13 @@ class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass<IntegrationWai
|
|||||||
},
|
},
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
const sleep = (ms: number) => Effect.sleep(ms);
|
||||||
|
|
||||||
function waitForSync<A>(
|
function waitForSync<A>(
|
||||||
read: () => A,
|
read: () => A,
|
||||||
predicate: (value: A) => boolean,
|
predicate: (value: A) => boolean,
|
||||||
description: string,
|
description: string,
|
||||||
timeoutMs = 10_000,
|
timeoutMs = 3000,
|
||||||
): Effect.Effect<A, never> {
|
): Effect.Effect<A, never> {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const deadline = Date.now() + timeoutMs;
|
const deadline = Date.now() + timeoutMs;
|
||||||
@@ -70,7 +68,7 @@ function waitForSync<A>(
|
|||||||
if (Date.now() >= deadline) {
|
if (Date.now() >= deadline) {
|
||||||
return yield* Effect.die(new IntegrationWaitTimeoutError({ description }));
|
return yield* Effect.die(new IntegrationWaitTimeoutError({ description }));
|
||||||
}
|
}
|
||||||
yield* Effect.sleep(10);
|
yield* sleep(10);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -91,7 +89,7 @@ function withHarness<A, E>(
|
|||||||
makeOrchestrationIntegrationHarness({ provider }),
|
makeOrchestrationIntegrationHarness({ provider }),
|
||||||
use,
|
use,
|
||||||
(harness) => harness.dispose,
|
(harness) => harness.dispose,
|
||||||
).pipe(Effect.provide(NodeServices.layer));
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function withRealCodexHarness<A, E>(
|
function withRealCodexHarness<A, E>(
|
||||||
@@ -101,14 +99,12 @@ function withRealCodexHarness<A, E>(
|
|||||||
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
|
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
|
||||||
use,
|
use,
|
||||||
(harness) => harness.dispose,
|
(harness) => harness.dispose,
|
||||||
).pipe(Effect.provide(NodeServices.layer));
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const createdAt = nowIso();
|
const createdAt = nowIso();
|
||||||
const provider = harness.adapterHarness?.provider ?? "codex";
|
|
||||||
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider];
|
|
||||||
|
|
||||||
yield* harness.engine.dispatch({
|
yield* harness.engine.dispatch({
|
||||||
type: "project.create",
|
type: "project.create",
|
||||||
@@ -116,10 +112,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
|||||||
projectId: PROJECT_ID,
|
projectId: PROJECT_ID,
|
||||||
title: "Integration Project",
|
title: "Integration Project",
|
||||||
workspaceRoot: harness.workspaceDir,
|
workspaceRoot: harness.workspaceDir,
|
||||||
defaultModelSelection: {
|
defaultModel: "gpt-5-codex",
|
||||||
provider,
|
|
||||||
model: defaultModel,
|
|
||||||
},
|
|
||||||
createdAt,
|
createdAt,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -129,10 +122,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
|||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
projectId: PROJECT_ID,
|
projectId: PROJECT_ID,
|
||||||
title: "Integration Thread",
|
title: "Integration Thread",
|
||||||
modelSelection: {
|
model: "gpt-5-codex",
|
||||||
provider,
|
|
||||||
model: defaultModel,
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -146,7 +136,7 @@ const startTurn = (input: {
|
|||||||
readonly commandId: string;
|
readonly commandId: string;
|
||||||
readonly messageId: string;
|
readonly messageId: string;
|
||||||
readonly text: string;
|
readonly text: string;
|
||||||
readonly modelSelection?: ModelSelection;
|
readonly provider?: IntegrationProvider;
|
||||||
}) =>
|
}) =>
|
||||||
input.harness.engine.dispatch({
|
input.harness.engine.dispatch({
|
||||||
type: "thread.turn.start",
|
type: "thread.turn.start",
|
||||||
@@ -158,11 +148,7 @@ const startTurn = (input: {
|
|||||||
text: input.text,
|
text: input.text,
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
...(input.modelSelection !== undefined
|
...(input.provider !== undefined ? { provider: input.provider } : {}),
|
||||||
? {
|
|
||||||
modelSelection: input.modelSelection,
|
|
||||||
}
|
|
||||||
: {}),
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
createdAt: nowIso(),
|
createdAt: nowIso(),
|
||||||
@@ -265,10 +251,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
|||||||
projectId: PROJECT_ID,
|
projectId: PROJECT_ID,
|
||||||
title: "Integration Project",
|
title: "Integration Project",
|
||||||
workspaceRoot: harness.workspaceDir,
|
workspaceRoot: harness.workspaceDir,
|
||||||
defaultModelSelection: {
|
defaultModel: "gpt-5.3-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5.3-codex",
|
|
||||||
},
|
|
||||||
createdAt,
|
createdAt,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -278,10 +261,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
|||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
projectId: PROJECT_ID,
|
projectId: PROJECT_ID,
|
||||||
title: "Integration Thread",
|
title: "Integration Thread",
|
||||||
modelSelection: {
|
model: "gpt-5.3-codex",
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5.3-codex",
|
|
||||||
},
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -902,435 +882,3 @@ it.live(
|
|||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.live("starts a claudeAgent session on first turn when provider is requested", () =>
|
|
||||||
withHarness(
|
|
||||||
(harness) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
yield* seedProjectAndThread(harness);
|
|
||||||
|
|
||||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
|
||||||
events: [
|
|
||||||
{
|
|
||||||
type: "turn.started",
|
|
||||||
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "message.delta",
|
|
||||||
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
delta: "Claude first turn.\n",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "turn.completed",
|
|
||||||
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
status: "completed",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* startTurn({
|
|
||||||
harness,
|
|
||||||
commandId: "cmd-turn-start-claude-initial",
|
|
||||||
messageId: "msg-user-claude-initial",
|
|
||||||
text: "Use Claude",
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const thread = yield* harness.waitForThread(
|
|
||||||
THREAD_ID,
|
|
||||||
(entry) =>
|
|
||||||
entry.session?.providerName === "claudeAgent" &&
|
|
||||||
entry.session.status === "ready" &&
|
|
||||||
entry.messages.some(
|
|
||||||
(message) => message.role === "assistant" && message.text === "Claude first turn.\n",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
assert.equal(thread.session?.providerName, "claudeAgent");
|
|
||||||
}),
|
|
||||||
"claudeAgent",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.live("recovers claudeAgent sessions after provider stopAll using persisted resume state", () =>
|
|
||||||
withHarness(
|
|
||||||
(harness) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
yield* seedProjectAndThread(harness);
|
|
||||||
|
|
||||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
|
||||||
events: [
|
|
||||||
{
|
|
||||||
type: "turn.started",
|
|
||||||
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "message.delta",
|
|
||||||
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
delta: "Turn before restart.\n",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "turn.completed",
|
|
||||||
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
status: "completed",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* startTurn({
|
|
||||||
harness,
|
|
||||||
commandId: "cmd-turn-start-claude-recover-1",
|
|
||||||
messageId: "msg-user-claude-recover-1",
|
|
||||||
text: "Before restart",
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* harness.waitForThread(
|
|
||||||
THREAD_ID,
|
|
||||||
(entry) =>
|
|
||||||
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
|
|
||||||
);
|
|
||||||
|
|
||||||
yield* harness.adapterHarness!.adapter.stopAll();
|
|
||||||
yield* waitForSync(
|
|
||||||
() => harness.adapterHarness!.listActiveSessionIds(),
|
|
||||||
(sessionIds) => sessionIds.length === 0,
|
|
||||||
"provider stopAll",
|
|
||||||
);
|
|
||||||
|
|
||||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
|
||||||
events: [
|
|
||||||
{
|
|
||||||
type: "turn.started",
|
|
||||||
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "message.delta",
|
|
||||||
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
delta: "Turn after restart.\n",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "turn.completed",
|
|
||||||
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
status: "completed",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* startTurn({
|
|
||||||
harness,
|
|
||||||
commandId: "cmd-turn-start-claude-recover-2",
|
|
||||||
messageId: "msg-user-claude-recover-2",
|
|
||||||
text: "After restart",
|
|
||||||
});
|
|
||||||
yield* waitForSync(
|
|
||||||
() => harness.adapterHarness!.getStartCount(),
|
|
||||||
(count) => count === 2,
|
|
||||||
"claude provider recovery start",
|
|
||||||
);
|
|
||||||
|
|
||||||
const recoveredThread = yield* harness.waitForThread(
|
|
||||||
THREAD_ID,
|
|
||||||
(entry) =>
|
|
||||||
entry.session?.providerName === "claudeAgent" &&
|
|
||||||
entry.messages.some(
|
|
||||||
(message) => message.role === "user" && message.text === "After restart",
|
|
||||||
) &&
|
|
||||||
!entry.activities.some((activity) => activity.kind === "provider.turn.start.failed"),
|
|
||||||
);
|
|
||||||
assert.equal(recoveredThread.session?.providerName, "claudeAgent");
|
|
||||||
assert.equal(recoveredThread.session?.threadId, "thread-1");
|
|
||||||
}),
|
|
||||||
"claudeAgent",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.live("forwards claudeAgent approval responses to the provider session", () =>
|
|
||||||
withHarness(
|
|
||||||
(harness) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
yield* seedProjectAndThread(harness);
|
|
||||||
|
|
||||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
|
||||||
events: [
|
|
||||||
{
|
|
||||||
type: "turn.started",
|
|
||||||
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "approval.requested",
|
|
||||||
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
requestId: APPROVAL_REQUEST_ID,
|
|
||||||
requestKind: "command",
|
|
||||||
detail: "Approve Claude tool call",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "turn.completed",
|
|
||||||
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
status: "completed",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* startTurn({
|
|
||||||
harness,
|
|
||||||
commandId: "cmd-turn-start-claude-approval",
|
|
||||||
messageId: "msg-user-claude-approval",
|
|
||||||
text: "Need approval",
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
|
|
||||||
entry.activities.some((activity) => activity.kind === "approval.requested"),
|
|
||||||
);
|
|
||||||
assert.equal(thread.session?.threadId, "thread-1");
|
|
||||||
|
|
||||||
yield* harness.engine.dispatch({
|
|
||||||
type: "thread.approval.respond",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
requestId: APPROVAL_REQUEST_ID,
|
|
||||||
decision: "accept",
|
|
||||||
createdAt: nowIso(),
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* harness.waitForPendingApproval(
|
|
||||||
"req-approval-1",
|
|
||||||
(row) => row.status === "resolved" && row.decision === "accept",
|
|
||||||
);
|
|
||||||
|
|
||||||
const approvalResponses = yield* waitForSync(
|
|
||||||
() => harness.adapterHarness!.getApprovalResponses(THREAD_ID),
|
|
||||||
(responses) => responses.length === 1,
|
|
||||||
"claude provider approval response",
|
|
||||||
);
|
|
||||||
assert.equal(approvalResponses[0]?.decision, "accept");
|
|
||||||
}),
|
|
||||||
"claudeAgent",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
|
|
||||||
withHarness(
|
|
||||||
(harness) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
yield* seedProjectAndThread(harness);
|
|
||||||
|
|
||||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
|
||||||
events: [
|
|
||||||
{
|
|
||||||
type: "turn.started",
|
|
||||||
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "message.delta",
|
|
||||||
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
delta: "Long running output.\n",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "turn.completed",
|
|
||||||
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
status: "completed",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* startTurn({
|
|
||||||
harness,
|
|
||||||
commandId: "cmd-turn-start-claude-interrupt",
|
|
||||||
messageId: "msg-user-claude-interrupt",
|
|
||||||
text: "Start long turn",
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const thread = yield* harness.waitForThread(
|
|
||||||
THREAD_ID,
|
|
||||||
(entry) => entry.session?.threadId === "thread-1",
|
|
||||||
);
|
|
||||||
assert.equal(thread.session?.threadId, "thread-1");
|
|
||||||
|
|
||||||
yield* harness.engine.dispatch({
|
|
||||||
type: "thread.turn.interrupt",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
createdAt: nowIso(),
|
|
||||||
});
|
|
||||||
yield* harness.waitForDomainEvent(
|
|
||||||
(event) => event.type === "thread.turn-interrupt-requested",
|
|
||||||
);
|
|
||||||
|
|
||||||
const interruptCalls = yield* waitForSync(
|
|
||||||
() => harness.adapterHarness!.getInterruptCalls(THREAD_ID),
|
|
||||||
(calls) => calls.length === 1,
|
|
||||||
"claude provider interrupt call",
|
|
||||||
);
|
|
||||||
assert.equal(interruptCalls.length, 1);
|
|
||||||
}),
|
|
||||||
"claudeAgent",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.live("reverts claudeAgent turns and rolls back provider conversation state", () =>
|
|
||||||
withHarness(
|
|
||||||
(harness) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
yield* seedProjectAndThread(harness);
|
|
||||||
|
|
||||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
|
||||||
events: [
|
|
||||||
{
|
|
||||||
type: "turn.started",
|
|
||||||
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "message.delta",
|
|
||||||
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
delta: "README -> v2\n",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "turn.completed",
|
|
||||||
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
status: "completed",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
mutateWorkspace: ({ cwd }) =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* startTurn({
|
|
||||||
harness,
|
|
||||||
commandId: "cmd-turn-start-claude-revert-1",
|
|
||||||
messageId: "msg-user-claude-revert-1",
|
|
||||||
text: "First Claude edit",
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* harness.waitForThread(
|
|
||||||
THREAD_ID,
|
|
||||||
(entry) =>
|
|
||||||
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
|
|
||||||
);
|
|
||||||
|
|
||||||
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
|
|
||||||
events: [
|
|
||||||
{
|
|
||||||
type: "turn.started",
|
|
||||||
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "message.delta",
|
|
||||||
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
delta: "README -> v3\n",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "turn.completed",
|
|
||||||
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnId: FIXTURE_TURN_ID,
|
|
||||||
status: "completed",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
mutateWorkspace: ({ cwd }) =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* startTurn({
|
|
||||||
harness,
|
|
||||||
commandId: "cmd-turn-start-claude-revert-2",
|
|
||||||
messageId: "msg-user-claude-revert-2",
|
|
||||||
text: "Second Claude edit",
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* harness.waitForThread(
|
|
||||||
THREAD_ID,
|
|
||||||
(entry) =>
|
|
||||||
entry.latestTurn?.turnId === "turn-2" &&
|
|
||||||
entry.checkpoints.length === 2 &&
|
|
||||||
entry.session?.providerName === "claudeAgent",
|
|
||||||
);
|
|
||||||
|
|
||||||
yield* harness.engine.dispatch({
|
|
||||||
type: "thread.checkpoint.revert",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
|
|
||||||
threadId: THREAD_ID,
|
|
||||||
turnCount: 1,
|
|
||||||
createdAt: nowIso(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const revertedThread = yield* harness.waitForThread(
|
|
||||||
THREAD_ID,
|
|
||||||
(entry) =>
|
|
||||||
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
|
|
||||||
);
|
|
||||||
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
|
|
||||||
assert.equal(
|
|
||||||
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
|
|
||||||
true,
|
|
||||||
);
|
|
||||||
assert.equal(
|
|
||||||
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
|
|
||||||
}),
|
|
||||||
"claudeAgent",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||||
import { ThreadId } from "@t3tools/contracts";
|
import { ThreadId } from "@t3tools/contracts";
|
||||||
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
import { it, assert } from "@effect/vitest";
|
import { it, assert } from "@effect/vitest";
|
||||||
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
|
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
|
||||||
@@ -13,7 +12,6 @@ import {
|
|||||||
ProviderService,
|
ProviderService,
|
||||||
type ProviderServiceShape,
|
type ProviderServiceShape,
|
||||||
} from "../src/provider/Services/ProviderService.ts";
|
} from "../src/provider/Services/ProviderService.ts";
|
||||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
|
||||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||||
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
|
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
|
||||||
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
|
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
|
||||||
@@ -62,7 +60,6 @@ const makeIntegrationFixture = Effect.gen(function* () {
|
|||||||
const shared = Layer.mergeAll(
|
const shared = Layer.mergeAll(
|
||||||
directoryLayer,
|
directoryLayer,
|
||||||
Layer.succeed(ProviderAdapterRegistry, registry),
|
Layer.succeed(ProviderAdapterRegistry, registry),
|
||||||
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
|
|
||||||
AnalyticsService.layerTest,
|
AnalyticsService.layerTest,
|
||||||
).pipe(Layer.provide(SqlitePersistenceMemory));
|
).pipe(Layer.provide(SqlitePersistenceMemory));
|
||||||
|
|
||||||
@@ -86,7 +83,6 @@ const collectEventsDuring = <A, E, R>(
|
|||||||
Effect.forkScoped,
|
Effect.forkScoped,
|
||||||
);
|
);
|
||||||
|
|
||||||
yield* Effect.sleep("50 millis");
|
|
||||||
yield* action;
|
yield* action;
|
||||||
|
|
||||||
return yield* Effect.forEach(
|
return yield* Effect.forEach(
|
||||||
@@ -105,6 +101,7 @@ const runTurn = (input: {
|
|||||||
}) =>
|
}) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
yield* input.harness.queueTurnResponse(input.threadId, input.response);
|
yield* input.harness.queueTurnResponse(input.threadId, input.response);
|
||||||
|
|
||||||
return yield* collectEventsDuring(
|
return yield* collectEventsDuring(
|
||||||
input.provider.streamEvents,
|
input.provider.streamEvents,
|
||||||
input.response.events.length,
|
input.response.events.length,
|
||||||
@@ -116,7 +113,7 @@ const runTurn = (input: {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it.live("replays typed runtime fixture events", () =>
|
it.effect("replays typed runtime fixture events", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const fixture = yield* makeIntegrationFixture;
|
const fixture = yield* makeIntegrationFixture;
|
||||||
|
|
||||||
@@ -149,7 +146,7 @@ it.live("replays typed runtime fixture events", () =>
|
|||||||
}).pipe(Effect.provide(NodeServices.layer)),
|
}).pipe(Effect.provide(NodeServices.layer)),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.live("replays file-changing fixture turn events", () =>
|
it.effect("replays file-changing fixture turn events", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const fixture = yield* makeIntegrationFixture;
|
const fixture = yield* makeIntegrationFixture;
|
||||||
const { join } = yield* Path.Path;
|
const { join } = yield* Path.Path;
|
||||||
@@ -188,7 +185,7 @@ it.live("replays file-changing fixture turn events", () =>
|
|||||||
}).pipe(Effect.provide(NodeServices.layer)),
|
}).pipe(Effect.provide(NodeServices.layer)),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.live("runs multi-turn tool/approval flow", () =>
|
it.effect("runs multi-turn tool/approval flow", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const fixture = yield* makeIntegrationFixture;
|
const fixture = yield* makeIntegrationFixture;
|
||||||
const { join } = yield* Path.Path;
|
const { join } = yield* Path.Path;
|
||||||
@@ -242,7 +239,7 @@ it.live("runs multi-turn tool/approval flow", () =>
|
|||||||
}).pipe(Effect.provide(NodeServices.layer)),
|
}).pipe(Effect.provide(NodeServices.layer)),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.live("rolls back provider conversation state only", () =>
|
it.effect("rolls back provider conversation state only", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const fixture = yield* makeIntegrationFixture;
|
const fixture = yield* makeIntegrationFixture;
|
||||||
const { join } = yield* Path.Path;
|
const { join } = yield* Path.Path;
|
||||||
|
|||||||
@@ -1,36 +1,34 @@
|
|||||||
{
|
{
|
||||||
"name": "t3",
|
"name": "t3",
|
||||||
"version": "0.0.15",
|
"version": "0.0.10",
|
||||||
"license": "MIT",
|
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "https://github.com/pingdotgg/t3code",
|
"url": "https://github.com/pingdotgg/t3code",
|
||||||
"directory": "apps/server"
|
"directory": "apps/server"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
"t3": "./dist/bin.mjs"
|
"t3": "./dist/index.mjs"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"dist"
|
"dist"
|
||||||
],
|
],
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "bun run src/bin.ts",
|
"dev": "bun run src/index.ts",
|
||||||
"build": "node scripts/cli.ts build",
|
"build": "node scripts/cli.ts build",
|
||||||
"start": "node dist/bin.mjs",
|
"start": "node dist/index.mjs",
|
||||||
"prepare": "effect-language-service patch",
|
"prepare": "effect-language-service patch",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
"test": "vitest run"
|
"test": "vitest run"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
|
|
||||||
"@effect/platform-bun": "catalog:",
|
|
||||||
"@effect/platform-node": "catalog:",
|
"@effect/platform-node": "catalog:",
|
||||||
"@effect/sql-sqlite-bun": "catalog:",
|
"@effect/sql-sqlite-bun": "catalog:",
|
||||||
"@pierre/diffs": "^1.1.0-beta.16",
|
"@pierre/diffs": "^1.1.0-beta.16",
|
||||||
"effect": "catalog:",
|
"effect": "catalog:",
|
||||||
"node-pty": "^1.1.0",
|
"node-pty": "^1.1.0",
|
||||||
"open": "^10.1.0"
|
"open": "^10.1.0",
|
||||||
|
"ws": "^8.18.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@effect/language-service": "catalog:",
|
"@effect/language-service": "catalog:",
|
||||||
@@ -40,6 +38,7 @@
|
|||||||
"@t3tools/web": "workspace:*",
|
"@t3tools/web": "workspace:*",
|
||||||
"@types/bun": "catalog:",
|
"@types/bun": "catalog:",
|
||||||
"@types/node": "catalog:",
|
"@types/node": "catalog:",
|
||||||
|
"@types/ws": "^8.5.13",
|
||||||
"tsdown": "catalog:",
|
"tsdown": "catalog:",
|
||||||
"typescript": "catalog:",
|
"typescript": "catalog:",
|
||||||
"vitest": "catalog:"
|
"vitest": "catalog:"
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ export function normalizeAttachmentRelativePath(rawRelativePath: string): string
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function resolveAttachmentRelativePath(input: {
|
export function resolveAttachmentRelativePath(input: {
|
||||||
readonly attachmentsDir: string;
|
readonly stateDir: string;
|
||||||
readonly relativePath: string;
|
readonly relativePath: string;
|
||||||
}): string | null {
|
}): string | null {
|
||||||
const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath);
|
const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath);
|
||||||
@@ -19,7 +19,7 @@ export function resolveAttachmentRelativePath(input: {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const attachmentsRoot = path.resolve(input.attachmentsDir);
|
const attachmentsRoot = path.resolve(path.join(input.stateDir, "attachments"));
|
||||||
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
|
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
|
||||||
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
|
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -44,32 +44,34 @@ describe("attachmentStore", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("resolves attachment path by id using the extension that exists on disk", () => {
|
it("resolves attachment path by id using the extension that exists on disk", () => {
|
||||||
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
||||||
try {
|
try {
|
||||||
const attachmentId = "thread-1-attachment";
|
const attachmentId = "thread-1-attachment";
|
||||||
|
const attachmentsDir = path.join(stateDir, "attachments");
|
||||||
|
fs.mkdirSync(attachmentsDir, { recursive: true });
|
||||||
const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
|
const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
|
||||||
fs.writeFileSync(pngPath, Buffer.from("hello"));
|
fs.writeFileSync(pngPath, Buffer.from("hello"));
|
||||||
|
|
||||||
const resolved = resolveAttachmentPathById({
|
const resolved = resolveAttachmentPathById({
|
||||||
attachmentsDir,
|
stateDir,
|
||||||
attachmentId,
|
attachmentId,
|
||||||
});
|
});
|
||||||
expect(resolved).toBe(pngPath);
|
expect(resolved).toBe(pngPath);
|
||||||
} finally {
|
} finally {
|
||||||
fs.rmSync(attachmentsDir, { recursive: true, force: true });
|
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
it("returns null when no attachment file exists for the id", () => {
|
it("returns null when no attachment file exists for the id", () => {
|
||||||
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
||||||
try {
|
try {
|
||||||
const resolved = resolveAttachmentPathById({
|
const resolved = resolveAttachmentPathById({
|
||||||
attachmentsDir,
|
stateDir,
|
||||||
attachmentId: "thread-1-missing",
|
attachmentId: "thread-1-missing",
|
||||||
});
|
});
|
||||||
expect(resolved).toBeNull();
|
expect(resolved).toBeNull();
|
||||||
} finally {
|
} finally {
|
||||||
fs.rmSync(attachmentsDir, { recursive: true, force: true });
|
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -66,17 +66,17 @@ export function attachmentRelativePath(attachment: ChatAttachment): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function resolveAttachmentPath(input: {
|
export function resolveAttachmentPath(input: {
|
||||||
readonly attachmentsDir: string;
|
readonly stateDir: string;
|
||||||
readonly attachment: ChatAttachment;
|
readonly attachment: ChatAttachment;
|
||||||
}): string | null {
|
}): string | null {
|
||||||
return resolveAttachmentRelativePath({
|
return resolveAttachmentRelativePath({
|
||||||
attachmentsDir: input.attachmentsDir,
|
stateDir: input.stateDir,
|
||||||
relativePath: attachmentRelativePath(input.attachment),
|
relativePath: attachmentRelativePath(input.attachment),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resolveAttachmentPathById(input: {
|
export function resolveAttachmentPathById(input: {
|
||||||
readonly attachmentsDir: string;
|
readonly stateDir: string;
|
||||||
readonly attachmentId: string;
|
readonly attachmentId: string;
|
||||||
}): string | null {
|
}): string | null {
|
||||||
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
|
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
|
||||||
@@ -85,7 +85,7 @@ export function resolveAttachmentPathById(input: {
|
|||||||
}
|
}
|
||||||
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
|
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
|
||||||
const maybePath = resolveAttachmentRelativePath({
|
const maybePath = resolveAttachmentRelativePath({
|
||||||
attachmentsDir: input.attachmentsDir,
|
stateDir: input.stateDir,
|
||||||
relativePath: `${normalizedId}${extension}`,
|
relativePath: `${normalizedId}${extension}`,
|
||||||
});
|
});
|
||||||
if (maybePath && existsSync(maybePath)) {
|
if (maybePath && existsSync(maybePath)) {
|
||||||
|
|||||||
@@ -1,111 +0,0 @@
|
|||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import { expect, it } from "@effect/vitest";
|
|
||||||
import { Effect, Layer } from "effect";
|
|
||||||
|
|
||||||
import { ServerConfigShape } from "../../config.ts";
|
|
||||||
import { ServerConfig } from "../../config.ts";
|
|
||||||
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
|
|
||||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
|
||||||
import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
|
|
||||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
|
||||||
import { AuthControlPlane } from "../Services/AuthControlPlane.ts";
|
|
||||||
import { makeAuthControlPlane } from "./AuthControlPlane.ts";
|
|
||||||
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
|
|
||||||
|
|
||||||
const makeServerConfigLayer = (
|
|
||||||
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
|
||||||
) =>
|
|
||||||
Layer.effect(
|
|
||||||
ServerConfig,
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const config = yield* ServerConfig;
|
|
||||||
return {
|
|
||||||
...config,
|
|
||||||
...overrides,
|
|
||||||
} satisfies ServerConfigShape;
|
|
||||||
}),
|
|
||||||
).pipe(
|
|
||||||
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-control-plane-test-" })),
|
|
||||||
);
|
|
||||||
|
|
||||||
const makeAuthControlPlaneLayer = (
|
|
||||||
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
|
||||||
) =>
|
|
||||||
Layer.effect(AuthControlPlane, makeAuthControlPlane).pipe(
|
|
||||||
Layer.provideMerge(BootstrapCredentialServiceLive),
|
|
||||||
Layer.provideMerge(SessionCredentialServiceLive),
|
|
||||||
Layer.provideMerge(ServerSecretStoreLive),
|
|
||||||
Layer.provideMerge(SqlitePersistenceMemory),
|
|
||||||
Layer.provide(makeServerConfigLayer(overrides)),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.layer(NodeServices.layer)("AuthControlPlane", (it) => {
|
|
||||||
it.effect("creates, lists, and revokes client pairing links", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const authControlPlane = yield* AuthControlPlane;
|
|
||||||
|
|
||||||
const created = yield* authControlPlane.createPairingLink({
|
|
||||||
role: "client",
|
|
||||||
subject: "one-time-token",
|
|
||||||
label: "CI phone",
|
|
||||||
});
|
|
||||||
const listedBeforeRevoke = yield* authControlPlane.listPairingLinks({ role: "client" });
|
|
||||||
const revoked = yield* authControlPlane.revokePairingLink(created.id);
|
|
||||||
const listedAfterRevoke = yield* authControlPlane.listPairingLinks({ role: "client" });
|
|
||||||
|
|
||||||
expect(created.role).toBe("client");
|
|
||||||
expect(created.credential.length).toBeGreaterThan(0);
|
|
||||||
expect(listedBeforeRevoke).toHaveLength(1);
|
|
||||||
expect(listedBeforeRevoke[0]?.id).toBe(created.id);
|
|
||||||
expect(listedBeforeRevoke[0]?.label).toBe("CI phone");
|
|
||||||
expect(listedBeforeRevoke[0]?.credential).toBe(created.credential);
|
|
||||||
expect(revoked).toBe(true);
|
|
||||||
expect(listedAfterRevoke).toHaveLength(0);
|
|
||||||
}).pipe(Effect.provide(makeAuthControlPlaneLayer())),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("issues bearer sessions and lists them without exposing raw tokens", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const authControlPlane = yield* AuthControlPlane;
|
|
||||||
const sessionCredentials = yield* SessionCredentialService;
|
|
||||||
|
|
||||||
const issued = yield* authControlPlane.issueSession({
|
|
||||||
label: "deploy-bot",
|
|
||||||
});
|
|
||||||
const verified = yield* sessionCredentials.verify(issued.token);
|
|
||||||
const listedBeforeRevoke = yield* authControlPlane.listSessions();
|
|
||||||
const revoked = yield* authControlPlane.revokeSession(issued.sessionId);
|
|
||||||
const listedAfterRevoke = yield* authControlPlane.listSessions();
|
|
||||||
|
|
||||||
expect(issued.method).toBe("bearer-session-token");
|
|
||||||
expect(issued.role).toBe("owner");
|
|
||||||
expect(issued.client.deviceType).toBe("bot");
|
|
||||||
expect(issued.client.label).toBe("deploy-bot");
|
|
||||||
expect(verified.sessionId).toBe(issued.sessionId);
|
|
||||||
expect(verified.role).toBe("owner");
|
|
||||||
expect(verified.method).toBe("bearer-session-token");
|
|
||||||
expect(listedBeforeRevoke).toHaveLength(1);
|
|
||||||
expect(listedBeforeRevoke[0]?.sessionId).toBe(issued.sessionId);
|
|
||||||
expect("token" in (listedBeforeRevoke[0] ?? {})).toBe(false);
|
|
||||||
expect(revoked).toBe(true);
|
|
||||||
expect(listedAfterRevoke).toHaveLength(0);
|
|
||||||
}).pipe(Effect.provide(makeAuthControlPlaneLayer())),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("surfaces lastConnectedAt through the listed session view", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const authControlPlane = yield* AuthControlPlane;
|
|
||||||
const sessionCredentials = yield* SessionCredentialService;
|
|
||||||
|
|
||||||
const issued = yield* authControlPlane.issueSession({
|
|
||||||
label: "remote-ipad",
|
|
||||||
});
|
|
||||||
const beforeConnect = yield* authControlPlane.listSessions();
|
|
||||||
yield* sessionCredentials.markConnected(issued.sessionId);
|
|
||||||
const afterConnect = yield* authControlPlane.listSessions();
|
|
||||||
|
|
||||||
expect(beforeConnect[0]?.lastConnectedAt).toBeNull();
|
|
||||||
expect(afterConnect[0]?.lastConnectedAt).not.toBeNull();
|
|
||||||
}).pipe(Effect.provide(makeAuthControlPlaneLayer())),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,176 +0,0 @@
|
|||||||
import type { AuthClientSession, AuthPairingLink } from "@t3tools/contracts";
|
|
||||||
import { DateTime, Effect, Layer } from "effect";
|
|
||||||
|
|
||||||
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
|
|
||||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
|
||||||
import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
|
|
||||||
import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
|
|
||||||
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
|
|
||||||
import { layerConfig as SqlitePersistenceLayerLive } from "../../persistence/Layers/Sqlite.ts";
|
|
||||||
import {
|
|
||||||
AuthControlPlane,
|
|
||||||
AuthControlPlaneError,
|
|
||||||
AuthControlPlaneShape,
|
|
||||||
DEFAULT_SESSION_SUBJECT,
|
|
||||||
IssuedBearerSession,
|
|
||||||
IssuedPairingLink,
|
|
||||||
} from "../Services/AuthControlPlane.ts";
|
|
||||||
|
|
||||||
const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {
|
|
||||||
if (left.role !== right.role) {
|
|
||||||
return left.role === "owner" ? -1 : 1;
|
|
||||||
}
|
|
||||||
if (left.connected !== right.connected) {
|
|
||||||
return left.connected ? -1 : 1;
|
|
||||||
}
|
|
||||||
return right.issuedAt.epochMilliseconds - left.issuedAt.epochMilliseconds;
|
|
||||||
};
|
|
||||||
|
|
||||||
const toAuthControlPlaneError =
|
|
||||||
(message: string) =>
|
|
||||||
(cause: unknown): AuthControlPlaneError =>
|
|
||||||
new AuthControlPlaneError({
|
|
||||||
message,
|
|
||||||
cause,
|
|
||||||
});
|
|
||||||
|
|
||||||
export const makeAuthControlPlane = Effect.gen(function* () {
|
|
||||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
|
||||||
const sessions = yield* SessionCredentialService;
|
|
||||||
|
|
||||||
const createPairingLink: AuthControlPlaneShape["createPairingLink"] = (input) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const createdAt = yield* DateTime.now;
|
|
||||||
const issued = yield* bootstrapCredentials.issueOneTimeToken({
|
|
||||||
role: input?.role ?? "client",
|
|
||||||
subject: input?.subject ?? "one-time-token",
|
|
||||||
...(input?.ttl ? { ttl: input.ttl } : {}),
|
|
||||||
...(input?.label ? { label: input.label } : {}),
|
|
||||||
});
|
|
||||||
return {
|
|
||||||
id: issued.id,
|
|
||||||
credential: issued.credential,
|
|
||||||
role: input?.role ?? "client",
|
|
||||||
subject: input?.subject ?? "one-time-token",
|
|
||||||
...(issued.label ? { label: issued.label } : {}),
|
|
||||||
createdAt: DateTime.toUtc(createdAt),
|
|
||||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
|
||||||
} satisfies IssuedPairingLink;
|
|
||||||
}).pipe(Effect.mapError(toAuthControlPlaneError("Failed to create pairing link.")));
|
|
||||||
|
|
||||||
const listPairingLinks: AuthControlPlaneShape["listPairingLinks"] = (input) =>
|
|
||||||
bootstrapCredentials.listActive().pipe(
|
|
||||||
Effect.map((pairingLinks) =>
|
|
||||||
pairingLinks
|
|
||||||
.filter((pairingLink) => (input?.role ? pairingLink.role === input.role : true))
|
|
||||||
.filter((pairingLink) => !input?.excludeSubjects?.includes(pairingLink.subject))
|
|
||||||
.map((pairingLink) =>
|
|
||||||
pairingLink.label
|
|
||||||
? ({
|
|
||||||
id: pairingLink.id,
|
|
||||||
credential: pairingLink.credential,
|
|
||||||
role: pairingLink.role,
|
|
||||||
subject: pairingLink.subject,
|
|
||||||
label: pairingLink.label,
|
|
||||||
createdAt: pairingLink.createdAt,
|
|
||||||
expiresAt: pairingLink.expiresAt,
|
|
||||||
} satisfies AuthPairingLink)
|
|
||||||
: ({
|
|
||||||
id: pairingLink.id,
|
|
||||||
credential: pairingLink.credential,
|
|
||||||
role: pairingLink.role,
|
|
||||||
subject: pairingLink.subject,
|
|
||||||
createdAt: pairingLink.createdAt,
|
|
||||||
expiresAt: pairingLink.expiresAt,
|
|
||||||
} satisfies AuthPairingLink),
|
|
||||||
)
|
|
||||||
.toSorted(
|
|
||||||
(left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Effect.mapError(toAuthControlPlaneError("Failed to list pairing links.")),
|
|
||||||
);
|
|
||||||
|
|
||||||
const revokePairingLink: AuthControlPlaneShape["revokePairingLink"] = (id) =>
|
|
||||||
bootstrapCredentials
|
|
||||||
.revoke(id)
|
|
||||||
.pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke pairing link.")));
|
|
||||||
|
|
||||||
const issueSession: AuthControlPlaneShape["issueSession"] = (input) =>
|
|
||||||
sessions
|
|
||||||
.issue({
|
|
||||||
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
|
|
||||||
method: "bearer-session-token",
|
|
||||||
role: input?.role ?? "owner",
|
|
||||||
client: {
|
|
||||||
...(input?.label ? { label: input.label } : {}),
|
|
||||||
deviceType: "bot",
|
|
||||||
},
|
|
||||||
...(input?.ttl ? { ttl: input.ttl } : {}),
|
|
||||||
})
|
|
||||||
.pipe(
|
|
||||||
Effect.flatMap((issued) => {
|
|
||||||
if (issued.method !== "bearer-session-token") {
|
|
||||||
return Effect.fail(
|
|
||||||
new AuthControlPlaneError({
|
|
||||||
message: "CLI session issuance produced an unexpected session method.",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return Effect.succeed({
|
|
||||||
sessionId: issued.sessionId,
|
|
||||||
token: issued.token,
|
|
||||||
method: "bearer-session-token" as const,
|
|
||||||
role: issued.role,
|
|
||||||
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
|
|
||||||
client: issued.client,
|
|
||||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
|
||||||
} satisfies IssuedBearerSession);
|
|
||||||
}),
|
|
||||||
Effect.mapError(toAuthControlPlaneError("Failed to issue session token.")),
|
|
||||||
);
|
|
||||||
|
|
||||||
const listSessions: AuthControlPlaneShape["listSessions"] = () =>
|
|
||||||
sessions.listActive().pipe(
|
|
||||||
Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)),
|
|
||||||
Effect.mapError(toAuthControlPlaneError("Failed to list sessions.")),
|
|
||||||
);
|
|
||||||
|
|
||||||
const revokeSession: AuthControlPlaneShape["revokeSession"] = (sessionId) =>
|
|
||||||
sessions
|
|
||||||
.revoke(sessionId)
|
|
||||||
.pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke session.")));
|
|
||||||
|
|
||||||
const revokeOtherSessionsExcept: AuthControlPlaneShape["revokeOtherSessionsExcept"] = (
|
|
||||||
sessionId,
|
|
||||||
) =>
|
|
||||||
sessions
|
|
||||||
.revokeAllExcept(sessionId)
|
|
||||||
.pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke other sessions.")));
|
|
||||||
|
|
||||||
return {
|
|
||||||
createPairingLink,
|
|
||||||
listPairingLinks,
|
|
||||||
revokePairingLink,
|
|
||||||
issueSession,
|
|
||||||
listSessions,
|
|
||||||
revokeSession,
|
|
||||||
revokeOtherSessionsExcept,
|
|
||||||
} satisfies AuthControlPlaneShape;
|
|
||||||
});
|
|
||||||
|
|
||||||
export const AuthCoreLive = Layer.mergeAll(
|
|
||||||
BootstrapCredentialServiceLive,
|
|
||||||
SessionCredentialServiceLive,
|
|
||||||
);
|
|
||||||
|
|
||||||
export const AuthStorageLive = Layer.mergeAll(ServerSecretStoreLive, SqlitePersistenceLayerLive);
|
|
||||||
|
|
||||||
export const AuthRuntimeLive = AuthCoreLive.pipe(Layer.provideMerge(AuthStorageLive));
|
|
||||||
|
|
||||||
export const AuthControlPlaneLive = Layer.effect(AuthControlPlane, makeAuthControlPlane);
|
|
||||||
|
|
||||||
export const AuthControlPlaneRuntimeLive = AuthControlPlaneLive.pipe(
|
|
||||||
Layer.provideMerge(AuthRuntimeLive),
|
|
||||||
);
|
|
||||||
@@ -1,151 +0,0 @@
|
|||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import { expect, it } from "@effect/vitest";
|
|
||||||
import { Duration, Effect, Layer } from "effect";
|
|
||||||
import { TestClock } from "effect/testing";
|
|
||||||
|
|
||||||
import type { ServerConfigShape } from "../../config.ts";
|
|
||||||
import { ServerConfig } from "../../config.ts";
|
|
||||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
|
||||||
import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
|
|
||||||
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
|
|
||||||
|
|
||||||
const makeServerConfigLayer = (
|
|
||||||
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
|
||||||
) =>
|
|
||||||
Layer.effect(
|
|
||||||
ServerConfig,
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const config = yield* ServerConfig;
|
|
||||||
return {
|
|
||||||
...config,
|
|
||||||
...overrides,
|
|
||||||
} satisfies ServerConfigShape;
|
|
||||||
}),
|
|
||||||
).pipe(
|
|
||||||
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-bootstrap-test-" })),
|
|
||||||
);
|
|
||||||
|
|
||||||
const makeBootstrapCredentialLayer = (
|
|
||||||
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
|
||||||
) =>
|
|
||||||
BootstrapCredentialServiceLive.pipe(
|
|
||||||
Layer.provide(SqlitePersistenceMemory),
|
|
||||||
Layer.provide(makeServerConfigLayer(overrides)),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.layer(NodeServices.layer)("BootstrapCredentialServiceLive", (it) => {
|
|
||||||
it.effect("issues pairing tokens in a short manual-entry format", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
|
||||||
const issued = yield* bootstrapCredentials.issueOneTimeToken();
|
|
||||||
|
|
||||||
expect(issued.credential).toMatch(/^[23456789ABCDEFGHJKLMNPQRSTUVWXYZ]{12}$/);
|
|
||||||
}).pipe(Effect.provide(makeBootstrapCredentialLayer())),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("issues one-time bootstrap tokens that can only be consumed once", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
|
||||||
const issued = yield* bootstrapCredentials.issueOneTimeToken({ label: "Julius iPhone" });
|
|
||||||
const first = yield* bootstrapCredentials.consume(issued.credential);
|
|
||||||
const second = yield* Effect.flip(bootstrapCredentials.consume(issued.credential));
|
|
||||||
|
|
||||||
expect(first.method).toBe("one-time-token");
|
|
||||||
expect(first.role).toBe("client");
|
|
||||||
expect(first.subject).toBe("one-time-token");
|
|
||||||
expect(first.label).toBe("Julius iPhone");
|
|
||||||
expect(issued.label).toBe("Julius iPhone");
|
|
||||||
expect(second._tag).toBe("BootstrapCredentialError");
|
|
||||||
expect(second.message).toContain("Unknown bootstrap credential");
|
|
||||||
}).pipe(Effect.provide(makeBootstrapCredentialLayer())),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("atomically consumes a one-time token when multiple requests race", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
|
||||||
const token = yield* bootstrapCredentials.issueOneTimeToken();
|
|
||||||
const results = yield* Effect.all(
|
|
||||||
Array.from({ length: 8 }, () =>
|
|
||||||
Effect.result(bootstrapCredentials.consume(token.credential)),
|
|
||||||
),
|
|
||||||
{
|
|
||||||
concurrency: "unbounded",
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
const successes = results.filter((result) => result._tag === "Success");
|
|
||||||
const failures = results.filter((result) => result._tag === "Failure");
|
|
||||||
|
|
||||||
expect(successes).toHaveLength(1);
|
|
||||||
expect(failures).toHaveLength(7);
|
|
||||||
for (const failure of failures) {
|
|
||||||
expect(failure.failure._tag).toBe("BootstrapCredentialError");
|
|
||||||
expect(failure.failure.message).toContain("Unknown bootstrap credential");
|
|
||||||
}
|
|
||||||
}).pipe(Effect.provide(makeBootstrapCredentialLayer())),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("seeds the desktop bootstrap credential as a one-time grant", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
|
||||||
const first = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
|
|
||||||
const second = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
|
|
||||||
|
|
||||||
expect(first.method).toBe("desktop-bootstrap");
|
|
||||||
expect(first.role).toBe("owner");
|
|
||||||
expect(first.subject).toBe("desktop-bootstrap");
|
|
||||||
expect(second._tag).toBe("BootstrapCredentialError");
|
|
||||||
expect(second.status).toBe(401);
|
|
||||||
}).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
makeBootstrapCredentialLayer({
|
|
||||||
desktopBootstrapToken: "desktop-bootstrap-token",
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("reports seeded desktop bootstrap credentials as expired after their ttl", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
|
||||||
|
|
||||||
yield* TestClock.adjust(Duration.minutes(6));
|
|
||||||
const expired = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
|
|
||||||
|
|
||||||
expect(expired._tag).toBe("BootstrapCredentialError");
|
|
||||||
expect(expired.status).toBe(401);
|
|
||||||
expect(expired.message).toContain("Bootstrap credential expired");
|
|
||||||
}).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
Layer.merge(
|
|
||||||
makeBootstrapCredentialLayer({
|
|
||||||
desktopBootstrapToken: "desktop-bootstrap-token",
|
|
||||||
}),
|
|
||||||
TestClock.layer(),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("lists and revokes active pairing links", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
|
||||||
const first = yield* bootstrapCredentials.issueOneTimeToken();
|
|
||||||
const second = yield* bootstrapCredentials.issueOneTimeToken({ role: "owner" });
|
|
||||||
|
|
||||||
const activeBeforeRevoke = yield* bootstrapCredentials.listActive();
|
|
||||||
expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(first.id);
|
|
||||||
expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(second.id);
|
|
||||||
|
|
||||||
const revoked = yield* bootstrapCredentials.revoke(first.id);
|
|
||||||
const activeAfterRevoke = yield* bootstrapCredentials.listActive();
|
|
||||||
const revokedConsume = yield* Effect.flip(bootstrapCredentials.consume(first.credential));
|
|
||||||
|
|
||||||
expect(revoked).toBe(true);
|
|
||||||
expect(activeAfterRevoke.map((entry) => entry.id)).not.toContain(first.id);
|
|
||||||
expect(activeAfterRevoke.map((entry) => entry.id)).toContain(second.id);
|
|
||||||
expect(revokedConsume.message).toContain("no longer available");
|
|
||||||
expect(revokedConsume.status).toBe(401);
|
|
||||||
}).pipe(Effect.provide(makeBootstrapCredentialLayer())),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,296 +0,0 @@
|
|||||||
import type { AuthPairingLink } from "@t3tools/contracts";
|
|
||||||
import { DateTime, Duration, Effect, Layer, PubSub, Ref, Stream } from "effect";
|
|
||||||
import { Option } from "effect";
|
|
||||||
|
|
||||||
import { ServerConfig } from "../../config.ts";
|
|
||||||
import { AuthPairingLinkRepositoryLive } from "../../persistence/Layers/AuthPairingLinks.ts";
|
|
||||||
import { AuthPairingLinkRepository } from "../../persistence/Services/AuthPairingLinks.ts";
|
|
||||||
import {
|
|
||||||
BootstrapCredentialError,
|
|
||||||
BootstrapCredentialService,
|
|
||||||
type BootstrapCredentialChange,
|
|
||||||
type BootstrapCredentialServiceShape,
|
|
||||||
type BootstrapGrant,
|
|
||||||
type IssuedBootstrapCredential,
|
|
||||||
} from "../Services/BootstrapCredentialService.ts";
|
|
||||||
|
|
||||||
interface StoredBootstrapGrant extends BootstrapGrant {
|
|
||||||
readonly remainingUses: number | "unbounded";
|
|
||||||
}
|
|
||||||
|
|
||||||
type ConsumeResult =
|
|
||||||
| {
|
|
||||||
readonly _tag: "error";
|
|
||||||
readonly reason: "not-found" | "expired";
|
|
||||||
readonly error: BootstrapCredentialError;
|
|
||||||
}
|
|
||||||
| {
|
|
||||||
readonly _tag: "success";
|
|
||||||
readonly grant: BootstrapGrant;
|
|
||||||
};
|
|
||||||
|
|
||||||
const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
|
|
||||||
const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
|
|
||||||
const PAIRING_TOKEN_LENGTH = 12;
|
|
||||||
|
|
||||||
const generatePairingToken = (): string => {
|
|
||||||
const randomBytes = crypto.getRandomValues(new Uint8Array(PAIRING_TOKEN_LENGTH));
|
|
||||||
|
|
||||||
return Array.from(randomBytes, (value) => PAIRING_TOKEN_ALPHABET[value & 31]).join("");
|
|
||||||
};
|
|
||||||
|
|
||||||
export const makeBootstrapCredentialService = Effect.gen(function* () {
|
|
||||||
const config = yield* ServerConfig;
|
|
||||||
const pairingLinks = yield* AuthPairingLinkRepository;
|
|
||||||
const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
|
|
||||||
const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();
|
|
||||||
|
|
||||||
const invalidBootstrapCredentialError = (message: string) =>
|
|
||||||
new BootstrapCredentialError({
|
|
||||||
message,
|
|
||||||
status: 401,
|
|
||||||
});
|
|
||||||
|
|
||||||
const internalBootstrapCredentialError = (message: string, cause: unknown) =>
|
|
||||||
new BootstrapCredentialError({
|
|
||||||
message,
|
|
||||||
status: 500,
|
|
||||||
cause,
|
|
||||||
});
|
|
||||||
|
|
||||||
const seedGrant = (credential: string, grant: StoredBootstrapGrant) =>
|
|
||||||
Ref.update(seededGrantsRef, (current) => {
|
|
||||||
const next = new Map(current);
|
|
||||||
next.set(credential, grant);
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
|
|
||||||
const emitUpsert = (pairingLink: AuthPairingLink) =>
|
|
||||||
PubSub.publish(changesPubSub, {
|
|
||||||
type: "pairingLinkUpserted",
|
|
||||||
pairingLink,
|
|
||||||
}).pipe(Effect.asVoid);
|
|
||||||
|
|
||||||
const emitRemoved = (id: string) =>
|
|
||||||
PubSub.publish(changesPubSub, {
|
|
||||||
type: "pairingLinkRemoved",
|
|
||||||
id,
|
|
||||||
}).pipe(Effect.asVoid);
|
|
||||||
|
|
||||||
if (config.desktopBootstrapToken) {
|
|
||||||
const now = yield* DateTime.now;
|
|
||||||
yield* seedGrant(config.desktopBootstrapToken, {
|
|
||||||
method: "desktop-bootstrap",
|
|
||||||
role: "owner",
|
|
||||||
subject: "desktop-bootstrap",
|
|
||||||
expiresAt: DateTime.add(now, {
|
|
||||||
milliseconds: Duration.toMillis(DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES),
|
|
||||||
}),
|
|
||||||
remainingUses: 1,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const toBootstrapCredentialError = (message: string) => (cause: unknown) =>
|
|
||||||
internalBootstrapCredentialError(message, cause);
|
|
||||||
|
|
||||||
const listActive: BootstrapCredentialServiceShape["listActive"] = () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const now = yield* DateTime.now;
|
|
||||||
const rows = yield* pairingLinks.listActive({ now });
|
|
||||||
|
|
||||||
return rows.map((row) =>
|
|
||||||
row.label
|
|
||||||
? ({
|
|
||||||
id: row.id,
|
|
||||||
credential: row.credential,
|
|
||||||
role: row.role,
|
|
||||||
subject: row.subject,
|
|
||||||
label: row.label,
|
|
||||||
createdAt: row.createdAt,
|
|
||||||
expiresAt: row.expiresAt,
|
|
||||||
} satisfies AuthPairingLink)
|
|
||||||
: ({
|
|
||||||
id: row.id,
|
|
||||||
credential: row.credential,
|
|
||||||
role: row.role,
|
|
||||||
subject: row.subject,
|
|
||||||
createdAt: row.createdAt,
|
|
||||||
expiresAt: row.expiresAt,
|
|
||||||
} satisfies AuthPairingLink),
|
|
||||||
);
|
|
||||||
}).pipe(Effect.mapError(toBootstrapCredentialError("Failed to load active pairing links.")));
|
|
||||||
|
|
||||||
const revoke: BootstrapCredentialServiceShape["revoke"] = (id) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const revokedAt = yield* DateTime.now;
|
|
||||||
const revoked = yield* pairingLinks.revoke({
|
|
||||||
id,
|
|
||||||
revokedAt,
|
|
||||||
});
|
|
||||||
if (revoked) {
|
|
||||||
yield* emitRemoved(id);
|
|
||||||
}
|
|
||||||
return revoked;
|
|
||||||
}).pipe(Effect.mapError(toBootstrapCredentialError("Failed to revoke pairing link.")));
|
|
||||||
|
|
||||||
const issueOneTimeToken: BootstrapCredentialServiceShape["issueOneTimeToken"] = (input) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const id = crypto.randomUUID();
|
|
||||||
const credential = generatePairingToken();
|
|
||||||
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
|
|
||||||
const now = yield* DateTime.now;
|
|
||||||
const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
|
|
||||||
const issued: IssuedBootstrapCredential = {
|
|
||||||
id,
|
|
||||||
credential,
|
|
||||||
...(input?.label ? { label: input.label } : {}),
|
|
||||||
expiresAt,
|
|
||||||
};
|
|
||||||
yield* pairingLinks.create({
|
|
||||||
id,
|
|
||||||
credential,
|
|
||||||
method: "one-time-token",
|
|
||||||
role: input?.role ?? "client",
|
|
||||||
subject: input?.subject ?? "one-time-token",
|
|
||||||
label: input?.label ?? null,
|
|
||||||
createdAt: now,
|
|
||||||
expiresAt: expiresAt,
|
|
||||||
});
|
|
||||||
yield* emitUpsert({
|
|
||||||
id,
|
|
||||||
credential,
|
|
||||||
role: input?.role ?? "client",
|
|
||||||
subject: input?.subject ?? "one-time-token",
|
|
||||||
...(input?.label ? { label: input.label } : {}),
|
|
||||||
createdAt: now,
|
|
||||||
expiresAt,
|
|
||||||
});
|
|
||||||
return issued;
|
|
||||||
}).pipe(Effect.mapError(toBootstrapCredentialError("Failed to issue pairing credential.")));
|
|
||||||
|
|
||||||
const consume: BootstrapCredentialServiceShape["consume"] = (credential) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const now = yield* DateTime.now;
|
|
||||||
const seededResult: ConsumeResult = yield* Ref.modify(
|
|
||||||
seededGrantsRef,
|
|
||||||
(current): readonly [ConsumeResult, Map<string, StoredBootstrapGrant>] => {
|
|
||||||
const grant = current.get(credential);
|
|
||||||
if (!grant) {
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
_tag: "error",
|
|
||||||
reason: "not-found",
|
|
||||||
error: invalidBootstrapCredentialError("Unknown bootstrap credential."),
|
|
||||||
},
|
|
||||||
current,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
const next = new Map(current);
|
|
||||||
if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) {
|
|
||||||
next.delete(credential);
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
_tag: "error",
|
|
||||||
reason: "expired",
|
|
||||||
error: invalidBootstrapCredentialError("Bootstrap credential expired."),
|
|
||||||
},
|
|
||||||
next,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
const remainingUses = grant.remainingUses;
|
|
||||||
if (typeof remainingUses === "number") {
|
|
||||||
if (remainingUses <= 1) {
|
|
||||||
next.delete(credential);
|
|
||||||
} else {
|
|
||||||
next.set(credential, {
|
|
||||||
...grant,
|
|
||||||
remainingUses: remainingUses - 1,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
_tag: "success",
|
|
||||||
grant: {
|
|
||||||
method: grant.method,
|
|
||||||
role: grant.role,
|
|
||||||
subject: grant.subject,
|
|
||||||
...(grant.label ? { label: grant.label } : {}),
|
|
||||||
expiresAt: grant.expiresAt,
|
|
||||||
} satisfies BootstrapGrant,
|
|
||||||
},
|
|
||||||
next,
|
|
||||||
];
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
if (seededResult._tag === "success") {
|
|
||||||
return seededResult.grant;
|
|
||||||
}
|
|
||||||
if (seededResult.reason !== "not-found") {
|
|
||||||
return yield* seededResult.error;
|
|
||||||
}
|
|
||||||
|
|
||||||
const consumed = yield* pairingLinks.consumeAvailable({
|
|
||||||
credential,
|
|
||||||
consumedAt: now,
|
|
||||||
now,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (Option.isSome(consumed)) {
|
|
||||||
yield* emitRemoved(consumed.value.id);
|
|
||||||
return {
|
|
||||||
method: consumed.value.method,
|
|
||||||
role: consumed.value.role,
|
|
||||||
subject: consumed.value.subject,
|
|
||||||
...(consumed.value.label ? { label: consumed.value.label } : {}),
|
|
||||||
expiresAt: consumed.value.expiresAt,
|
|
||||||
} satisfies BootstrapGrant;
|
|
||||||
}
|
|
||||||
|
|
||||||
const matching = yield* pairingLinks.getByCredential({ credential });
|
|
||||||
if (Option.isNone(matching)) {
|
|
||||||
return yield* invalidBootstrapCredentialError("Unknown bootstrap credential.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (matching.value.revokedAt !== null) {
|
|
||||||
return yield* invalidBootstrapCredentialError(
|
|
||||||
"Bootstrap credential is no longer available.",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (matching.value.consumedAt !== null) {
|
|
||||||
return yield* invalidBootstrapCredentialError("Unknown bootstrap credential.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {
|
|
||||||
return yield* invalidBootstrapCredentialError("Bootstrap credential expired.");
|
|
||||||
}
|
|
||||||
|
|
||||||
return yield* invalidBootstrapCredentialError("Bootstrap credential is no longer available.");
|
|
||||||
}).pipe(
|
|
||||||
Effect.mapError((cause) =>
|
|
||||||
cause instanceof BootstrapCredentialError
|
|
||||||
? cause
|
|
||||||
: internalBootstrapCredentialError("Failed to consume bootstrap credential.", cause),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
issueOneTimeToken,
|
|
||||||
listActive,
|
|
||||||
get streamChanges() {
|
|
||||||
return Stream.fromPubSub(changesPubSub);
|
|
||||||
},
|
|
||||||
revoke,
|
|
||||||
consume,
|
|
||||||
} satisfies BootstrapCredentialServiceShape;
|
|
||||||
});
|
|
||||||
|
|
||||||
export const BootstrapCredentialServiceLive = Layer.effect(
|
|
||||||
BootstrapCredentialService,
|
|
||||||
makeBootstrapCredentialService,
|
|
||||||
).pipe(Layer.provideMerge(AuthPairingLinkRepositoryLive));
|
|
||||||
@@ -1,182 +0,0 @@
|
|||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import { expect, it } from "@effect/vitest";
|
|
||||||
import { Effect, Layer } from "effect";
|
|
||||||
|
|
||||||
import type { ServerConfigShape } from "../../config.ts";
|
|
||||||
import { ServerConfig } from "../../config.ts";
|
|
||||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
|
||||||
import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts";
|
|
||||||
import { ServerAuth, type ServerAuthShape } from "../Services/ServerAuth.ts";
|
|
||||||
import { ServerAuthLive, toBootstrapExchangeAuthError } from "./ServerAuth.ts";
|
|
||||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
|
||||||
|
|
||||||
const makeServerConfigLayer = (overrides?: Partial<ServerConfigShape>) =>
|
|
||||||
Layer.effect(
|
|
||||||
ServerConfig,
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const config = yield* ServerConfig;
|
|
||||||
return {
|
|
||||||
...config,
|
|
||||||
...overrides,
|
|
||||||
} satisfies ServerConfigShape;
|
|
||||||
}),
|
|
||||||
).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-server-test-" })));
|
|
||||||
|
|
||||||
const makeServerAuthLayer = (overrides?: Partial<ServerConfigShape>) =>
|
|
||||||
ServerAuthLive.pipe(
|
|
||||||
Layer.provide(SqlitePersistenceMemory),
|
|
||||||
Layer.provide(ServerSecretStoreLive),
|
|
||||||
Layer.provide(makeServerConfigLayer(overrides)),
|
|
||||||
);
|
|
||||||
|
|
||||||
const makeCookieRequest = (
|
|
||||||
sessionToken: string,
|
|
||||||
): Parameters<ServerAuthShape["authenticateHttpRequest"]>[0] =>
|
|
||||||
({
|
|
||||||
cookies: {
|
|
||||||
t3_session: sessionToken,
|
|
||||||
},
|
|
||||||
headers: {},
|
|
||||||
}) as unknown as Parameters<ServerAuthShape["authenticateHttpRequest"]>[0];
|
|
||||||
|
|
||||||
const requestMetadata = {
|
|
||||||
deviceType: "desktop" as const,
|
|
||||||
os: "macOS",
|
|
||||||
browser: "Chrome",
|
|
||||||
ipAddress: "192.168.1.23",
|
|
||||||
};
|
|
||||||
|
|
||||||
it.layer(NodeServices.layer)("ServerAuthLive", (it) => {
|
|
||||||
it.effect("maps invalid bootstrap credential failures to 401", () =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
const error = toBootstrapExchangeAuthError(
|
|
||||||
new BootstrapCredentialError({
|
|
||||||
message: "Unknown bootstrap credential.",
|
|
||||||
status: 401,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(error.status).toBe(401);
|
|
||||||
expect(error.message).toBe("Invalid bootstrap credential.");
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("maps unexpected bootstrap failures to 500", () =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
const error = toBootstrapExchangeAuthError(
|
|
||||||
new BootstrapCredentialError({
|
|
||||||
message: "Failed to consume bootstrap credential.",
|
|
||||||
status: 500,
|
|
||||||
cause: new Error("sqlite is unavailable"),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(error.status).toBe(500);
|
|
||||||
expect(error.message).toBe("Failed to validate bootstrap credential.");
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("issues client pairing credentials by default", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const serverAuth = yield* ServerAuth;
|
|
||||||
|
|
||||||
const pairingCredential = yield* serverAuth.issuePairingCredential();
|
|
||||||
const exchanged = yield* serverAuth.exchangeBootstrapCredential(
|
|
||||||
pairingCredential.credential,
|
|
||||||
requestMetadata,
|
|
||||||
);
|
|
||||||
const verified = yield* serverAuth.authenticateHttpRequest(
|
|
||||||
makeCookieRequest(exchanged.sessionToken),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(verified.sessionId.length).toBeGreaterThan(0);
|
|
||||||
expect(verified.role).toBe("client");
|
|
||||||
expect(verified.subject).toBe("one-time-token");
|
|
||||||
}).pipe(Effect.provide(makeServerAuthLayer())),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("issues startup pairing URLs that bootstrap owner sessions", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const serverAuth = yield* ServerAuth;
|
|
||||||
|
|
||||||
const pairingUrl = yield* serverAuth.issueStartupPairingUrl("http://127.0.0.1:3773");
|
|
||||||
const token = new URLSearchParams(new URL(pairingUrl).hash.slice(1)).get("token");
|
|
||||||
const listedPairingLinks = yield* serverAuth.listPairingLinks();
|
|
||||||
expect(token).toBeTruthy();
|
|
||||||
expect(
|
|
||||||
listedPairingLinks.some((pairingLink) => pairingLink.subject === "owner-bootstrap"),
|
|
||||||
).toBe(false);
|
|
||||||
|
|
||||||
const exchanged = yield* serverAuth.exchangeBootstrapCredential(token ?? "", requestMetadata);
|
|
||||||
const verified = yield* serverAuth.authenticateHttpRequest(
|
|
||||||
makeCookieRequest(exchanged.sessionToken),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(verified.role).toBe("owner");
|
|
||||||
expect(verified.subject).toBe("owner-bootstrap");
|
|
||||||
}).pipe(Effect.provide(makeServerAuthLayer())),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("lists pairing links and revokes other client sessions while keeping the owner", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const serverAuth = yield* ServerAuth;
|
|
||||||
|
|
||||||
const ownerExchange = yield* serverAuth.exchangeBootstrapCredential(
|
|
||||||
"desktop-bootstrap-token",
|
|
||||||
requestMetadata,
|
|
||||||
);
|
|
||||||
const ownerSession = yield* serverAuth.authenticateHttpRequest(
|
|
||||||
makeCookieRequest(ownerExchange.sessionToken),
|
|
||||||
);
|
|
||||||
const pairingCredential = yield* serverAuth.issuePairingCredential({
|
|
||||||
label: "Julius iPhone",
|
|
||||||
});
|
|
||||||
const listedPairingLinks = yield* serverAuth.listPairingLinks();
|
|
||||||
const clientExchange = yield* serverAuth.exchangeBootstrapCredential(
|
|
||||||
pairingCredential.credential,
|
|
||||||
{
|
|
||||||
...requestMetadata,
|
|
||||||
deviceType: "mobile",
|
|
||||||
os: "iOS",
|
|
||||||
browser: "Safari",
|
|
||||||
ipAddress: "192.168.1.88",
|
|
||||||
},
|
|
||||||
);
|
|
||||||
const clientSession = yield* serverAuth.authenticateHttpRequest(
|
|
||||||
makeCookieRequest(clientExchange.sessionToken),
|
|
||||||
);
|
|
||||||
const clientsBeforeRevoke = yield* serverAuth.listClientSessions(ownerSession.sessionId);
|
|
||||||
const revokedCount = yield* serverAuth.revokeOtherClientSessions(ownerSession.sessionId);
|
|
||||||
const clientsAfterRevoke = yield* serverAuth.listClientSessions(ownerSession.sessionId);
|
|
||||||
|
|
||||||
expect(listedPairingLinks.map((entry) => entry.id)).toContain(pairingCredential.id);
|
|
||||||
expect(listedPairingLinks.find((entry) => entry.id === pairingCredential.id)?.label).toBe(
|
|
||||||
"Julius iPhone",
|
|
||||||
);
|
|
||||||
expect(clientsBeforeRevoke).toHaveLength(2);
|
|
||||||
expect(
|
|
||||||
clientsBeforeRevoke.find((entry) => entry.sessionId === ownerSession.sessionId)?.current,
|
|
||||||
).toBe(true);
|
|
||||||
expect(
|
|
||||||
clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.current,
|
|
||||||
).toBe(false);
|
|
||||||
expect(
|
|
||||||
clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client
|
|
||||||
.label,
|
|
||||||
).toBe("Julius iPhone");
|
|
||||||
expect(
|
|
||||||
clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client
|
|
||||||
.deviceType,
|
|
||||||
).toBe("mobile");
|
|
||||||
expect(revokedCount).toBe(1);
|
|
||||||
expect(clientsAfterRevoke).toHaveLength(1);
|
|
||||||
expect(clientsAfterRevoke[0]?.sessionId).toBe(ownerSession.sessionId);
|
|
||||||
}).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
makeServerAuthLayer({
|
|
||||||
desktopBootstrapToken: "desktop-bootstrap-token",
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,385 +0,0 @@
|
|||||||
import {
|
|
||||||
type AuthBearerBootstrapResult,
|
|
||||||
type AuthClientSession,
|
|
||||||
type AuthBootstrapResult,
|
|
||||||
type AuthPairingCredentialResult,
|
|
||||||
type AuthSessionState,
|
|
||||||
type AuthWebSocketTokenResult,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
import { DateTime, Effect, Layer, Option } from "effect";
|
|
||||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
|
||||||
|
|
||||||
import { AuthControlPlane } from "../Services/AuthControlPlane.ts";
|
|
||||||
import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts";
|
|
||||||
import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
|
|
||||||
import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts";
|
|
||||||
import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts";
|
|
||||||
import {
|
|
||||||
ServerAuth,
|
|
||||||
type AuthenticatedSession,
|
|
||||||
AuthError,
|
|
||||||
type ServerAuthShape,
|
|
||||||
} from "../Services/ServerAuth.ts";
|
|
||||||
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
|
|
||||||
import { AuthControlPlaneLive, AuthCoreLive } from "./AuthControlPlane.ts";
|
|
||||||
|
|
||||||
type BootstrapExchangeResult = {
|
|
||||||
readonly response: AuthBootstrapResult;
|
|
||||||
readonly sessionToken: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
const AUTHORIZATION_PREFIX = "Bearer ";
|
|
||||||
const WEBSOCKET_TOKEN_QUERY_PARAM = "wsToken";
|
|
||||||
|
|
||||||
export function toBootstrapExchangeAuthError(cause: BootstrapCredentialError): AuthError {
|
|
||||||
if (cause.status === 500) {
|
|
||||||
return new AuthError({
|
|
||||||
message: "Failed to validate bootstrap credential.",
|
|
||||||
status: 500,
|
|
||||||
cause,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return new AuthError({
|
|
||||||
message: "Invalid bootstrap credential.",
|
|
||||||
status: 401,
|
|
||||||
cause,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {
|
|
||||||
const header = request.headers["authorization"];
|
|
||||||
if (typeof header !== "string" || !header.startsWith(AUTHORIZATION_PREFIX)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const token = header.slice(AUTHORIZATION_PREFIX.length).trim();
|
|
||||||
return token.length > 0 ? token : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const makeServerAuth = Effect.gen(function* () {
|
|
||||||
const policy = yield* ServerAuthPolicy;
|
|
||||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
|
||||||
const authControlPlane = yield* AuthControlPlane;
|
|
||||||
const sessions = yield* SessionCredentialService;
|
|
||||||
const descriptor = yield* policy.getDescriptor();
|
|
||||||
|
|
||||||
const authenticateToken = (token: string): Effect.Effect<AuthenticatedSession, AuthError> =>
|
|
||||||
sessions.verify(token).pipe(
|
|
||||||
Effect.map((session) => ({
|
|
||||||
sessionId: session.sessionId,
|
|
||||||
subject: session.subject,
|
|
||||||
method: session.method,
|
|
||||||
role: session.role,
|
|
||||||
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
|
|
||||||
})),
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new AuthError({
|
|
||||||
message: "Unauthorized request.",
|
|
||||||
status: 401,
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const authenticateRequest = (request: HttpServerRequest.HttpServerRequest) => {
|
|
||||||
const cookieToken = request.cookies[sessions.cookieName];
|
|
||||||
const bearerToken = parseBearerToken(request);
|
|
||||||
const credential = cookieToken ?? bearerToken;
|
|
||||||
if (!credential) {
|
|
||||||
return Effect.fail(
|
|
||||||
new AuthError({
|
|
||||||
message: "Authentication required.",
|
|
||||||
status: 401,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return authenticateToken(credential);
|
|
||||||
};
|
|
||||||
|
|
||||||
const getSessionState: ServerAuthShape["getSessionState"] = (request) =>
|
|
||||||
authenticateRequest(request).pipe(
|
|
||||||
Effect.map(
|
|
||||||
(session) =>
|
|
||||||
({
|
|
||||||
authenticated: true,
|
|
||||||
auth: descriptor,
|
|
||||||
role: session.role,
|
|
||||||
sessionMethod: session.method,
|
|
||||||
...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
|
|
||||||
}) satisfies AuthSessionState,
|
|
||||||
),
|
|
||||||
Effect.catchTag("AuthError", () =>
|
|
||||||
Effect.succeed({
|
|
||||||
authenticated: false,
|
|
||||||
auth: descriptor,
|
|
||||||
} satisfies AuthSessionState),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const exchangeBootstrapCredential: ServerAuthShape["exchangeBootstrapCredential"] = (
|
|
||||||
credential,
|
|
||||||
requestMetadata,
|
|
||||||
) =>
|
|
||||||
bootstrapCredentials.consume(credential).pipe(
|
|
||||||
Effect.mapError(toBootstrapExchangeAuthError),
|
|
||||||
Effect.flatMap((grant) =>
|
|
||||||
sessions
|
|
||||||
.issue({
|
|
||||||
method: "browser-session-cookie",
|
|
||||||
subject: grant.subject,
|
|
||||||
role: grant.role,
|
|
||||||
client: {
|
|
||||||
...requestMetadata,
|
|
||||||
...(grant.label ? { label: grant.label } : {}),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
.pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new AuthError({
|
|
||||||
message: "Failed to issue authenticated session.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Effect.map(
|
|
||||||
(session) =>
|
|
||||||
({
|
|
||||||
response: {
|
|
||||||
authenticated: true,
|
|
||||||
role: session.role,
|
|
||||||
sessionMethod: session.method,
|
|
||||||
expiresAt: DateTime.toUtc(session.expiresAt),
|
|
||||||
} satisfies AuthBootstrapResult,
|
|
||||||
sessionToken: session.token,
|
|
||||||
}) satisfies BootstrapExchangeResult,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const exchangeBootstrapCredentialForBearerSession: ServerAuthShape["exchangeBootstrapCredentialForBearerSession"] =
|
|
||||||
(credential, requestMetadata) =>
|
|
||||||
bootstrapCredentials.consume(credential).pipe(
|
|
||||||
Effect.mapError(toBootstrapExchangeAuthError),
|
|
||||||
Effect.flatMap((grant) =>
|
|
||||||
sessions
|
|
||||||
.issue({
|
|
||||||
method: "bearer-session-token",
|
|
||||||
subject: grant.subject,
|
|
||||||
role: grant.role,
|
|
||||||
client: {
|
|
||||||
...requestMetadata,
|
|
||||||
...(grant.label ? { label: grant.label } : {}),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
.pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new AuthError({
|
|
||||||
message: "Failed to issue authenticated session.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Effect.map(
|
|
||||||
(session) =>
|
|
||||||
({
|
|
||||||
authenticated: true,
|
|
||||||
role: session.role,
|
|
||||||
sessionMethod: "bearer-session-token",
|
|
||||||
expiresAt: DateTime.toUtc(session.expiresAt),
|
|
||||||
sessionToken: session.token,
|
|
||||||
}) satisfies AuthBearerBootstrapResult,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const issuePairingCredential: ServerAuthShape["issuePairingCredential"] = (input) =>
|
|
||||||
authControlPlane
|
|
||||||
.createPairingLink({
|
|
||||||
role: input?.role ?? "client",
|
|
||||||
subject: input?.role === "owner" ? "owner-bootstrap" : "one-time-token",
|
|
||||||
...(input?.label ? { label: input.label } : {}),
|
|
||||||
})
|
|
||||||
.pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new AuthError({
|
|
||||||
message: "Failed to issue pairing credential.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
Effect.map(
|
|
||||||
(issued) =>
|
|
||||||
({
|
|
||||||
id: issued.id,
|
|
||||||
credential: issued.credential,
|
|
||||||
...(issued.label ? { label: issued.label } : {}),
|
|
||||||
expiresAt: issued.expiresAt,
|
|
||||||
}) satisfies AuthPairingCredentialResult,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const listPairingLinks: ServerAuthShape["listPairingLinks"] = () =>
|
|
||||||
authControlPlane
|
|
||||||
.listPairingLinks({
|
|
||||||
role: "client",
|
|
||||||
excludeSubjects: ["owner-bootstrap"],
|
|
||||||
})
|
|
||||||
.pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new AuthError({
|
|
||||||
message: "Failed to load pairing links.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const revokePairingLink: ServerAuthShape["revokePairingLink"] = (id) =>
|
|
||||||
authControlPlane.revokePairingLink(id).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new AuthError({
|
|
||||||
message: "Failed to revoke pairing link.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const listClientSessions: ServerAuthShape["listClientSessions"] = (currentSessionId) =>
|
|
||||||
authControlPlane.listSessions().pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new AuthError({
|
|
||||||
message: "Failed to load paired clients.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
Effect.map((clientSessions) =>
|
|
||||||
clientSessions.map(
|
|
||||||
(clientSession): AuthClientSession => ({
|
|
||||||
...clientSession,
|
|
||||||
current: clientSession.sessionId === currentSessionId,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const revokeClientSession: ServerAuthShape["revokeClientSession"] = (
|
|
||||||
currentSessionId,
|
|
||||||
targetSessionId,
|
|
||||||
) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
if (currentSessionId === targetSessionId) {
|
|
||||||
return yield* new AuthError({
|
|
||||||
message: "Use revoke other clients to keep the current owner session active.",
|
|
||||||
status: 403,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return yield* authControlPlane.revokeSession(targetSessionId).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new AuthError({
|
|
||||||
message: "Failed to revoke client session.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
const revokeOtherClientSessions: ServerAuthShape["revokeOtherClientSessions"] = (
|
|
||||||
currentSessionId,
|
|
||||||
) =>
|
|
||||||
authControlPlane.revokeOtherSessionsExcept(currentSessionId).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new AuthError({
|
|
||||||
message: "Failed to revoke other client sessions.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const issueStartupPairingUrl: ServerAuthShape["issueStartupPairingUrl"] = (baseUrl) =>
|
|
||||||
issuePairingCredential({ role: "owner" }).pipe(
|
|
||||||
Effect.map((issued) => {
|
|
||||||
const url = new URL(baseUrl);
|
|
||||||
url.pathname = "/pair";
|
|
||||||
url.searchParams.delete("token");
|
|
||||||
url.hash = new URLSearchParams([["token", issued.credential]]).toString();
|
|
||||||
return url.toString();
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const issueWebSocketToken: ServerAuthShape["issueWebSocketToken"] = (session) =>
|
|
||||||
sessions.issueWebSocketToken(session.sessionId).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new AuthError({
|
|
||||||
message: "Failed to issue websocket token.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
Effect.map(
|
|
||||||
(issued) =>
|
|
||||||
({
|
|
||||||
token: issued.token,
|
|
||||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
|
||||||
}) satisfies AuthWebSocketTokenResult,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const authenticateWebSocketUpgrade: ServerAuthShape["authenticateWebSocketUpgrade"] = (request) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const requestUrl = HttpServerRequest.toURL(request);
|
|
||||||
if (Option.isSome(requestUrl)) {
|
|
||||||
const websocketToken = requestUrl.value.searchParams.get(WEBSOCKET_TOKEN_QUERY_PARAM);
|
|
||||||
if (websocketToken && websocketToken.trim().length > 0) {
|
|
||||||
return yield* sessions.verifyWebSocketToken(websocketToken).pipe(
|
|
||||||
Effect.map((session) => ({
|
|
||||||
sessionId: session.sessionId,
|
|
||||||
subject: session.subject,
|
|
||||||
method: session.method,
|
|
||||||
role: session.role,
|
|
||||||
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
|
|
||||||
})),
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new AuthError({
|
|
||||||
message: "Unauthorized request.",
|
|
||||||
status: 401,
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return yield* authenticateRequest(request);
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
getDescriptor: () => Effect.succeed(descriptor),
|
|
||||||
getSessionState,
|
|
||||||
exchangeBootstrapCredential,
|
|
||||||
exchangeBootstrapCredentialForBearerSession,
|
|
||||||
issuePairingCredential,
|
|
||||||
listPairingLinks,
|
|
||||||
revokePairingLink,
|
|
||||||
listClientSessions,
|
|
||||||
revokeClientSession,
|
|
||||||
revokeOtherClientSessions,
|
|
||||||
authenticateHttpRequest: authenticateRequest,
|
|
||||||
authenticateWebSocketUpgrade,
|
|
||||||
issueWebSocketToken,
|
|
||||||
issueStartupPairingUrl,
|
|
||||||
} satisfies ServerAuthShape;
|
|
||||||
});
|
|
||||||
|
|
||||||
export const ServerAuthLive = Layer.effect(ServerAuth, makeServerAuth).pipe(
|
|
||||||
Layer.provideMerge(AuthControlPlaneLive),
|
|
||||||
Layer.provideMerge(AuthCoreLive),
|
|
||||||
Layer.provideMerge(ServerAuthPolicyLive),
|
|
||||||
);
|
|
||||||
@@ -1,111 +0,0 @@
|
|||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import { expect, it } from "@effect/vitest";
|
|
||||||
import { Effect, Layer } from "effect";
|
|
||||||
|
|
||||||
import type { ServerConfigShape } from "../../config.ts";
|
|
||||||
import { ServerConfig } from "../../config.ts";
|
|
||||||
import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts";
|
|
||||||
import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts";
|
|
||||||
|
|
||||||
const makeServerAuthPolicyLayer = (overrides?: Partial<ServerConfigShape>) =>
|
|
||||||
ServerAuthPolicyLive.pipe(
|
|
||||||
Layer.provide(
|
|
||||||
Layer.effect(
|
|
||||||
ServerConfig,
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const config = yield* ServerConfig;
|
|
||||||
return {
|
|
||||||
...config,
|
|
||||||
...overrides,
|
|
||||||
} satisfies ServerConfigShape;
|
|
||||||
}),
|
|
||||||
).pipe(
|
|
||||||
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-policy-test-" })),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {
|
|
||||||
it.effect("uses desktop-managed-local policy for desktop mode", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const policy = yield* ServerAuthPolicy;
|
|
||||||
const descriptor = yield* policy.getDescriptor();
|
|
||||||
|
|
||||||
expect(descriptor.policy).toBe("desktop-managed-local");
|
|
||||||
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]);
|
|
||||||
}).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
makeServerAuthPolicyLayer({
|
|
||||||
mode: "desktop",
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("uses remote-reachable policy for desktop mode when bound beyond loopback", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const policy = yield* ServerAuthPolicy;
|
|
||||||
const descriptor = yield* policy.getDescriptor();
|
|
||||||
|
|
||||||
expect(descriptor.policy).toBe("remote-reachable");
|
|
||||||
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap", "one-time-token"]);
|
|
||||||
}).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
makeServerAuthPolicyLayer({
|
|
||||||
mode: "desktop",
|
|
||||||
host: "0.0.0.0",
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("uses loopback-browser policy for loopback web hosts", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const policy = yield* ServerAuthPolicy;
|
|
||||||
const descriptor = yield* policy.getDescriptor();
|
|
||||||
|
|
||||||
expect(descriptor.policy).toBe("loopback-browser");
|
|
||||||
expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
|
|
||||||
}).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
makeServerAuthPolicyLayer({
|
|
||||||
mode: "web",
|
|
||||||
host: "127.0.0.1",
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("uses remote-reachable policy for wildcard web hosts", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const policy = yield* ServerAuthPolicy;
|
|
||||||
const descriptor = yield* policy.getDescriptor();
|
|
||||||
|
|
||||||
expect(descriptor.policy).toBe("remote-reachable");
|
|
||||||
expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
|
|
||||||
}).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
makeServerAuthPolicyLayer({
|
|
||||||
mode: "web",
|
|
||||||
host: "0.0.0.0",
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("uses remote-reachable policy for non-loopback web hosts", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const policy = yield* ServerAuthPolicy;
|
|
||||||
const descriptor = yield* policy.getDescriptor();
|
|
||||||
|
|
||||||
expect(descriptor.policy).toBe("remote-reachable");
|
|
||||||
}).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
makeServerAuthPolicyLayer({
|
|
||||||
mode: "web",
|
|
||||||
host: "192.168.1.50",
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
import type { ServerAuthDescriptor } from "@t3tools/contracts";
|
|
||||||
import { Effect, Layer } from "effect";
|
|
||||||
|
|
||||||
import { ServerConfig } from "../../config.ts";
|
|
||||||
import { ServerAuthPolicy, type ServerAuthPolicyShape } from "../Services/ServerAuthPolicy.ts";
|
|
||||||
import { SESSION_COOKIE_NAME } from "../utils.ts";
|
|
||||||
import { isLoopbackHost, isWildcardHost } from "../../startupAccess.ts";
|
|
||||||
|
|
||||||
export const makeServerAuthPolicy = Effect.gen(function* () {
|
|
||||||
const config = yield* ServerConfig;
|
|
||||||
const isRemoteReachable = isWildcardHost(config.host) || !isLoopbackHost(config.host);
|
|
||||||
|
|
||||||
const policy =
|
|
||||||
config.mode === "desktop"
|
|
||||||
? isRemoteReachable
|
|
||||||
? "remote-reachable"
|
|
||||||
: "desktop-managed-local"
|
|
||||||
: isRemoteReachable
|
|
||||||
? "remote-reachable"
|
|
||||||
: "loopback-browser";
|
|
||||||
|
|
||||||
const bootstrapMethods: ServerAuthDescriptor["bootstrapMethods"] =
|
|
||||||
policy === "desktop-managed-local"
|
|
||||||
? ["desktop-bootstrap"]
|
|
||||||
: config.mode === "desktop" && policy === "remote-reachable"
|
|
||||||
? ["desktop-bootstrap", "one-time-token"]
|
|
||||||
: ["one-time-token"];
|
|
||||||
|
|
||||||
const descriptor: ServerAuthDescriptor = {
|
|
||||||
policy,
|
|
||||||
bootstrapMethods,
|
|
||||||
sessionMethods: ["browser-session-cookie", "bearer-session-token"],
|
|
||||||
sessionCookieName: SESSION_COOKIE_NAME,
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
|
||||||
getDescriptor: () => Effect.succeed(descriptor),
|
|
||||||
} satisfies ServerAuthPolicyShape;
|
|
||||||
});
|
|
||||||
|
|
||||||
export const ServerAuthPolicyLive = Layer.effect(ServerAuthPolicy, makeServerAuthPolicy);
|
|
||||||
@@ -1,263 +0,0 @@
|
|||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import { expect, it } from "@effect/vitest";
|
|
||||||
import { Cause, Deferred, Effect, FileSystem, Layer, Ref } from "effect";
|
|
||||||
import * as PlatformError from "effect/PlatformError";
|
|
||||||
|
|
||||||
import { ServerConfig } from "../../config.ts";
|
|
||||||
import { SecretStoreError, ServerSecretStore } from "../Services/ServerSecretStore.ts";
|
|
||||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
|
||||||
|
|
||||||
const makeServerConfigLayer = () =>
|
|
||||||
ServerConfig.layerTest(process.cwd(), { prefix: "t3-secret-store-test-" });
|
|
||||||
|
|
||||||
const makeServerSecretStoreLayer = () =>
|
|
||||||
Layer.provide(ServerSecretStoreLive, makeServerConfigLayer());
|
|
||||||
|
|
||||||
const PermissionDeniedFileSystemLayer = Layer.effect(
|
|
||||||
FileSystem.FileSystem,
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
|
||||||
|
|
||||||
return {
|
|
||||||
...fileSystem,
|
|
||||||
readFile: (path) =>
|
|
||||||
Effect.fail(
|
|
||||||
PlatformError.systemError({
|
|
||||||
_tag: "PermissionDenied",
|
|
||||||
module: "FileSystem",
|
|
||||||
method: "readFile",
|
|
||||||
pathOrDescriptor: path,
|
|
||||||
description: "Permission denied while reading secret file.",
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
} satisfies FileSystem.FileSystem;
|
|
||||||
}),
|
|
||||||
).pipe(Layer.provide(NodeServices.layer));
|
|
||||||
|
|
||||||
const makePermissionDeniedSecretStoreLayer = () =>
|
|
||||||
ServerSecretStoreLive.pipe(
|
|
||||||
Layer.provide(makeServerConfigLayer()),
|
|
||||||
Layer.provideMerge(PermissionDeniedFileSystemLayer),
|
|
||||||
);
|
|
||||||
|
|
||||||
const RenameFailureFileSystemLayer = Layer.effect(
|
|
||||||
FileSystem.FileSystem,
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
|
||||||
|
|
||||||
return {
|
|
||||||
...fileSystem,
|
|
||||||
rename: (from, to) =>
|
|
||||||
Effect.fail(
|
|
||||||
PlatformError.systemError({
|
|
||||||
_tag: "PermissionDenied",
|
|
||||||
module: "FileSystem",
|
|
||||||
method: "rename",
|
|
||||||
pathOrDescriptor: `${String(from)} -> ${String(to)}`,
|
|
||||||
description: "Permission denied while persisting secret file.",
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
} satisfies FileSystem.FileSystem;
|
|
||||||
}),
|
|
||||||
).pipe(Layer.provide(NodeServices.layer));
|
|
||||||
|
|
||||||
const makeRenameFailureSecretStoreLayer = () =>
|
|
||||||
ServerSecretStoreLive.pipe(
|
|
||||||
Layer.provide(makeServerConfigLayer()),
|
|
||||||
Layer.provideMerge(RenameFailureFileSystemLayer),
|
|
||||||
);
|
|
||||||
|
|
||||||
const RemoveFailureFileSystemLayer = Layer.effect(
|
|
||||||
FileSystem.FileSystem,
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
|
||||||
|
|
||||||
return {
|
|
||||||
...fileSystem,
|
|
||||||
remove: (path, options) =>
|
|
||||||
Effect.fail(
|
|
||||||
PlatformError.systemError({
|
|
||||||
_tag: "PermissionDenied",
|
|
||||||
module: "FileSystem",
|
|
||||||
method: "remove",
|
|
||||||
pathOrDescriptor: String(path),
|
|
||||||
description: `Permission denied while removing secret file.${options ? " options-set" : ""}`,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
} satisfies FileSystem.FileSystem;
|
|
||||||
}),
|
|
||||||
).pipe(Layer.provide(NodeServices.layer));
|
|
||||||
|
|
||||||
const makeRemoveFailureSecretStoreLayer = () =>
|
|
||||||
ServerSecretStoreLive.pipe(
|
|
||||||
Layer.provide(makeServerConfigLayer()),
|
|
||||||
Layer.provideMerge(RemoveFailureFileSystemLayer),
|
|
||||||
);
|
|
||||||
|
|
||||||
const ConcurrentReadMissFileSystemLayer = Layer.effect(
|
|
||||||
FileSystem.FileSystem,
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
|
||||||
const readCountRef = yield* Ref.make(0);
|
|
||||||
const readBarrier = yield* Deferred.make<void>();
|
|
||||||
|
|
||||||
return {
|
|
||||||
...fileSystem,
|
|
||||||
readFile: (path) =>
|
|
||||||
String(path).endsWith("/session-signing-key.bin")
|
|
||||||
? Ref.updateAndGet(readCountRef, (count) => count + 1).pipe(
|
|
||||||
Effect.flatMap((count) => {
|
|
||||||
if (count > 2) {
|
|
||||||
return fileSystem.readFile(path);
|
|
||||||
}
|
|
||||||
return Effect.gen(function* () {
|
|
||||||
if (count === 2) {
|
|
||||||
yield* Deferred.succeed(readBarrier, void 0);
|
|
||||||
}
|
|
||||||
yield* Deferred.await(readBarrier);
|
|
||||||
return yield* Effect.failCause(
|
|
||||||
Cause.fail(
|
|
||||||
PlatformError.systemError({
|
|
||||||
_tag: "NotFound",
|
|
||||||
module: "FileSystem",
|
|
||||||
method: "readFile",
|
|
||||||
pathOrDescriptor: String(path),
|
|
||||||
description: "Secret file does not exist yet.",
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
: fileSystem.readFile(path),
|
|
||||||
} satisfies FileSystem.FileSystem;
|
|
||||||
}),
|
|
||||||
).pipe(Layer.provide(NodeServices.layer));
|
|
||||||
|
|
||||||
const makeConcurrentCreateSecretStoreLayer = () =>
|
|
||||||
ServerSecretStoreLive.pipe(
|
|
||||||
Layer.provide(makeServerConfigLayer()),
|
|
||||||
Layer.provideMerge(ConcurrentReadMissFileSystemLayer),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.layer(NodeServices.layer)("ServerSecretStoreLive", (it) => {
|
|
||||||
it.effect("returns null when a secret file does not exist", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const secretStore = yield* ServerSecretStore;
|
|
||||||
|
|
||||||
const secret = yield* secretStore.get("missing-secret");
|
|
||||||
|
|
||||||
expect(secret).toBeNull();
|
|
||||||
}).pipe(Effect.provide(makeServerSecretStoreLayer())),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("reuses an existing secret instead of regenerating it", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const secretStore = yield* ServerSecretStore;
|
|
||||||
|
|
||||||
const first = yield* secretStore.getOrCreateRandom("session-signing-key", 32);
|
|
||||||
const second = yield* secretStore.getOrCreateRandom("session-signing-key", 32);
|
|
||||||
|
|
||||||
expect(Array.from(second)).toEqual(Array.from(first));
|
|
||||||
}).pipe(Effect.provide(makeServerSecretStoreLayer())),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("returns the persisted secret when concurrent creators race", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const secretStore = yield* ServerSecretStore;
|
|
||||||
|
|
||||||
const [first, second] = yield* Effect.all(
|
|
||||||
[
|
|
||||||
secretStore.getOrCreateRandom("session-signing-key", 32),
|
|
||||||
secretStore.getOrCreateRandom("session-signing-key", 32),
|
|
||||||
],
|
|
||||||
{ concurrency: "unbounded" },
|
|
||||||
);
|
|
||||||
const persisted = yield* secretStore.get("session-signing-key");
|
|
||||||
|
|
||||||
expect(persisted).not.toBeNull();
|
|
||||||
expect(Array.from(first)).toEqual(Array.from(persisted ?? new Uint8Array()));
|
|
||||||
expect(Array.from(second)).toEqual(Array.from(persisted ?? new Uint8Array()));
|
|
||||||
}).pipe(Effect.provide(makeConcurrentCreateSecretStoreLayer())),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("uses restrictive permissions for the secret directory and files", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const chmodCalls: Array<{ readonly path: string; readonly mode: number }> = [];
|
|
||||||
const recordingFileSystemLayer = Layer.effect(
|
|
||||||
FileSystem.FileSystem,
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
|
||||||
|
|
||||||
return {
|
|
||||||
...fileSystem,
|
|
||||||
makeDirectory: () => Effect.void,
|
|
||||||
writeFile: () => Effect.void,
|
|
||||||
rename: () => Effect.void,
|
|
||||||
chmod: (path, mode) =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
chmodCalls.push({ path: String(path), mode });
|
|
||||||
}),
|
|
||||||
} satisfies FileSystem.FileSystem;
|
|
||||||
}),
|
|
||||||
).pipe(Layer.provide(NodeServices.layer));
|
|
||||||
|
|
||||||
const secretStore = yield* Effect.service(ServerSecretStore).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
ServerSecretStoreLive.pipe(
|
|
||||||
Layer.provide(makeServerConfigLayer()),
|
|
||||||
Layer.provideMerge(recordingFileSystemLayer),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
yield* secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3]));
|
|
||||||
|
|
||||||
expect(chmodCalls.some((call) => call.mode === 0o700 && call.path.endsWith("/secrets"))).toBe(
|
|
||||||
true,
|
|
||||||
);
|
|
||||||
expect(chmodCalls.filter((call) => call.mode === 0o600).length).toBeGreaterThanOrEqual(2);
|
|
||||||
}).pipe(Effect.provide(NodeServices.layer)),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("propagates read failures other than missing-file errors", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const secretStore = yield* ServerSecretStore;
|
|
||||||
|
|
||||||
const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32));
|
|
||||||
|
|
||||||
expect(error).toBeInstanceOf(SecretStoreError);
|
|
||||||
expect(error.message).toContain("Failed to read secret session-signing-key.");
|
|
||||||
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
|
|
||||||
expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
|
|
||||||
}).pipe(Effect.provide(makePermissionDeniedSecretStoreLayer())),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("propagates write failures instead of treating them as success", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const secretStore = yield* ServerSecretStore;
|
|
||||||
|
|
||||||
const error = yield* Effect.flip(
|
|
||||||
secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3])),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(error).toBeInstanceOf(SecretStoreError);
|
|
||||||
expect(error.message).toContain("Failed to persist secret session-signing-key.");
|
|
||||||
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
|
|
||||||
expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
|
|
||||||
}).pipe(Effect.provide(makeRenameFailureSecretStoreLayer())),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("propagates remove failures other than missing-file errors", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const secretStore = yield* ServerSecretStore;
|
|
||||||
|
|
||||||
const error = yield* Effect.flip(secretStore.remove("session-signing-key"));
|
|
||||||
|
|
||||||
expect(error).toBeInstanceOf(SecretStoreError);
|
|
||||||
expect(error.message).toContain("Failed to remove secret session-signing-key.");
|
|
||||||
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
|
|
||||||
expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
|
|
||||||
}).pipe(Effect.provide(makeRemoveFailureSecretStoreLayer())),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,151 +0,0 @@
|
|||||||
import * as Crypto from "node:crypto";
|
|
||||||
|
|
||||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
|
||||||
import * as PlatformError from "effect/PlatformError";
|
|
||||||
|
|
||||||
import { ServerConfig } from "../../config.ts";
|
|
||||||
import {
|
|
||||||
SecretStoreError,
|
|
||||||
ServerSecretStore,
|
|
||||||
type ServerSecretStoreShape,
|
|
||||||
} from "../Services/ServerSecretStore.ts";
|
|
||||||
|
|
||||||
export const makeServerSecretStore = Effect.gen(function* () {
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
|
||||||
const path = yield* Path.Path;
|
|
||||||
const serverConfig = yield* ServerConfig;
|
|
||||||
|
|
||||||
yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });
|
|
||||||
yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new SecretStoreError({
|
|
||||||
message: `Failed to secure secrets directory ${serverConfig.secretsDir}.`,
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
|
|
||||||
|
|
||||||
const isMissingSecretFileError = (cause: unknown): cause is PlatformError.PlatformError =>
|
|
||||||
cause instanceof PlatformError.PlatformError && cause.reason._tag === "NotFound";
|
|
||||||
|
|
||||||
const isAlreadyExistsSecretFileError = (cause: unknown): cause is PlatformError.PlatformError =>
|
|
||||||
cause instanceof PlatformError.PlatformError && cause.reason._tag === "AlreadyExists";
|
|
||||||
|
|
||||||
const get: ServerSecretStoreShape["get"] = (name) =>
|
|
||||||
fileSystem.readFile(resolveSecretPath(name)).pipe(
|
|
||||||
Effect.map((bytes) => Uint8Array.from(bytes)),
|
|
||||||
Effect.catch((cause) =>
|
|
||||||
isMissingSecretFileError(cause)
|
|
||||||
? Effect.succeed(null)
|
|
||||||
: Effect.fail(
|
|
||||||
new SecretStoreError({
|
|
||||||
message: `Failed to read secret ${name}.`,
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const set: ServerSecretStoreShape["set"] = (name, value) => {
|
|
||||||
const secretPath = resolveSecretPath(name);
|
|
||||||
const tempPath = `${secretPath}.${Crypto.randomUUID()}.tmp`;
|
|
||||||
return Effect.gen(function* () {
|
|
||||||
yield* fileSystem.writeFile(tempPath, value);
|
|
||||||
yield* fileSystem.chmod(tempPath, 0o600);
|
|
||||||
yield* fileSystem.rename(tempPath, secretPath);
|
|
||||||
yield* fileSystem.chmod(secretPath, 0o600);
|
|
||||||
}).pipe(
|
|
||||||
Effect.catch((cause) =>
|
|
||||||
fileSystem.remove(tempPath).pipe(
|
|
||||||
Effect.ignore,
|
|
||||||
Effect.flatMap(() =>
|
|
||||||
Effect.fail(
|
|
||||||
new SecretStoreError({
|
|
||||||
message: `Failed to persist secret ${name}.`,
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const create: ServerSecretStoreShape["set"] = (name, value) => {
|
|
||||||
const secretPath = resolveSecretPath(name);
|
|
||||||
return Effect.scoped(
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const file = yield* fileSystem.open(secretPath, {
|
|
||||||
flag: "wx",
|
|
||||||
mode: 0o600,
|
|
||||||
});
|
|
||||||
yield* file.writeAll(value);
|
|
||||||
yield* file.sync;
|
|
||||||
yield* fileSystem.chmod(secretPath, 0o600);
|
|
||||||
}),
|
|
||||||
).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new SecretStoreError({
|
|
||||||
message: `Failed to persist secret ${name}.`,
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const getOrCreateRandom: ServerSecretStoreShape["getOrCreateRandom"] = (name, bytes) =>
|
|
||||||
get(name).pipe(
|
|
||||||
Effect.flatMap((existing) => {
|
|
||||||
if (existing) {
|
|
||||||
return Effect.succeed(existing);
|
|
||||||
}
|
|
||||||
|
|
||||||
const generated = Crypto.randomBytes(bytes);
|
|
||||||
return create(name, generated).pipe(
|
|
||||||
Effect.as(Uint8Array.from(generated)),
|
|
||||||
Effect.catchTag("SecretStoreError", (error) =>
|
|
||||||
isAlreadyExistsSecretFileError(error.cause)
|
|
||||||
? get(name).pipe(
|
|
||||||
Effect.flatMap((created) =>
|
|
||||||
created !== null
|
|
||||||
? Effect.succeed(created)
|
|
||||||
: Effect.fail(
|
|
||||||
new SecretStoreError({
|
|
||||||
message: `Failed to read secret ${name} after concurrent creation.`,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
: Effect.fail(error),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const remove: ServerSecretStoreShape["remove"] = (name) =>
|
|
||||||
fileSystem.remove(resolveSecretPath(name)).pipe(
|
|
||||||
Effect.catch((cause) =>
|
|
||||||
isMissingSecretFileError(cause)
|
|
||||||
? Effect.void
|
|
||||||
: Effect.fail(
|
|
||||||
new SecretStoreError({
|
|
||||||
message: `Failed to remove secret ${name}.`,
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
get,
|
|
||||||
set,
|
|
||||||
getOrCreateRandom,
|
|
||||||
remove,
|
|
||||||
} satisfies ServerSecretStoreShape;
|
|
||||||
});
|
|
||||||
|
|
||||||
export const ServerSecretStoreLive = Layer.effect(ServerSecretStore, makeServerSecretStore);
|
|
||||||
@@ -1,191 +0,0 @@
|
|||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import { expect, it } from "@effect/vitest";
|
|
||||||
import { Duration, Effect, Layer } from "effect";
|
|
||||||
import { TestClock } from "effect/testing";
|
|
||||||
|
|
||||||
import type { ServerConfigShape } from "../../config.ts";
|
|
||||||
import { ServerConfig } from "../../config.ts";
|
|
||||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
|
||||||
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
|
|
||||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
|
||||||
import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
|
|
||||||
|
|
||||||
const makeServerConfigLayer = (
|
|
||||||
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
|
||||||
) =>
|
|
||||||
Layer.effect(
|
|
||||||
ServerConfig,
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const config = yield* ServerConfig;
|
|
||||||
return {
|
|
||||||
...config,
|
|
||||||
...overrides,
|
|
||||||
} satisfies ServerConfigShape;
|
|
||||||
}),
|
|
||||||
).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-session-test-" })));
|
|
||||||
|
|
||||||
const makeSessionCredentialLayer = (
|
|
||||||
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
|
||||||
) =>
|
|
||||||
SessionCredentialServiceLive.pipe(
|
|
||||||
Layer.provide(SqlitePersistenceMemory),
|
|
||||||
Layer.provide(ServerSecretStoreLive),
|
|
||||||
Layer.provide(makeServerConfigLayer(overrides)),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.layer(NodeServices.layer)("SessionCredentialServiceLive", (it) => {
|
|
||||||
it.effect("issues and verifies signed browser session tokens", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const sessions = yield* SessionCredentialService;
|
|
||||||
const issued = yield* sessions.issue({
|
|
||||||
subject: "desktop-bootstrap",
|
|
||||||
role: "owner",
|
|
||||||
client: {
|
|
||||||
label: "Desktop app",
|
|
||||||
deviceType: "desktop",
|
|
||||||
os: "macOS",
|
|
||||||
browser: "Electron",
|
|
||||||
ipAddress: "127.0.0.1",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const verified = yield* sessions.verify(issued.token);
|
|
||||||
|
|
||||||
expect(verified.method).toBe("browser-session-cookie");
|
|
||||||
expect(verified.subject).toBe("desktop-bootstrap");
|
|
||||||
expect(verified.role).toBe("owner");
|
|
||||||
expect(verified.client.label).toBe("Desktop app");
|
|
||||||
expect(verified.client.browser).toBe("Electron");
|
|
||||||
expect(verified.expiresAt?.toString()).toBe(issued.expiresAt.toString());
|
|
||||||
}).pipe(Effect.provide(makeSessionCredentialLayer())),
|
|
||||||
);
|
|
||||||
it.effect("rejects malformed session tokens", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const sessions = yield* SessionCredentialService;
|
|
||||||
const error = yield* Effect.flip(sessions.verify("not-a-session-token"));
|
|
||||||
|
|
||||||
expect(error._tag).toBe("SessionCredentialError");
|
|
||||||
expect(error.message).toContain("Malformed session token");
|
|
||||||
}).pipe(Effect.provide(makeSessionCredentialLayer())),
|
|
||||||
);
|
|
||||||
it.effect("verifies session tokens against the Effect clock", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const sessions = yield* SessionCredentialService;
|
|
||||||
const issued = yield* sessions.issue({
|
|
||||||
method: "bearer-session-token",
|
|
||||||
subject: "test-clock",
|
|
||||||
});
|
|
||||||
const verified = yield* sessions.verify(issued.token);
|
|
||||||
|
|
||||||
expect(verified.method).toBe("bearer-session-token");
|
|
||||||
expect(verified.subject).toBe("test-clock");
|
|
||||||
expect(verified.role).toBe("client");
|
|
||||||
}).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("rejects websocket tokens once the parent session has expired", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const sessions = yield* SessionCredentialService;
|
|
||||||
const issued = yield* sessions.issue({
|
|
||||||
method: "bearer-session-token",
|
|
||||||
subject: "short-lived",
|
|
||||||
ttl: Duration.seconds(1),
|
|
||||||
});
|
|
||||||
const websocket = yield* sessions.issueWebSocketToken(issued.sessionId);
|
|
||||||
|
|
||||||
yield* TestClock.adjust(Duration.seconds(2));
|
|
||||||
|
|
||||||
const error = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
|
|
||||||
expect(error.message).toContain("expired");
|
|
||||||
}).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("lists active sessions, tracks connectivity, and revokes other sessions", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const sessions = yield* SessionCredentialService;
|
|
||||||
const owner = yield* sessions.issue({
|
|
||||||
subject: "desktop-bootstrap",
|
|
||||||
role: "owner",
|
|
||||||
client: {
|
|
||||||
label: "Desktop app",
|
|
||||||
deviceType: "desktop",
|
|
||||||
os: "macOS",
|
|
||||||
browser: "Electron",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const client = yield* sessions.issue({
|
|
||||||
subject: "one-time-token",
|
|
||||||
role: "client",
|
|
||||||
client: {
|
|
||||||
label: "Julius iPhone",
|
|
||||||
deviceType: "mobile",
|
|
||||||
os: "iOS",
|
|
||||||
browser: "Safari",
|
|
||||||
ipAddress: "192.168.1.88",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
yield* sessions.markConnected(client.sessionId);
|
|
||||||
const beforeRevoke = yield* sessions.listActive();
|
|
||||||
const revokedCount = yield* sessions.revokeAllExcept(owner.sessionId);
|
|
||||||
const afterRevoke = yield* sessions.listActive();
|
|
||||||
const revokedClient = yield* Effect.flip(sessions.verify(client.token));
|
|
||||||
|
|
||||||
expect(beforeRevoke).toHaveLength(2);
|
|
||||||
expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.connected).toBe(
|
|
||||||
true,
|
|
||||||
);
|
|
||||||
expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.client.label).toBe(
|
|
||||||
"Julius iPhone",
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
beforeRevoke.find((entry) => entry.sessionId === owner.sessionId)?.client.deviceType,
|
|
||||||
).toBe("desktop");
|
|
||||||
expect(revokedCount).toBe(1);
|
|
||||||
expect(afterRevoke).toHaveLength(1);
|
|
||||||
expect(afterRevoke[0]?.sessionId).toBe(owner.sessionId);
|
|
||||||
expect(revokedClient.message).toContain("revoked");
|
|
||||||
}).pipe(Effect.provide(makeSessionCredentialLayer())),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("persists lastConnectedAt on first connect and updates it after reconnect", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const sessions = yield* SessionCredentialService;
|
|
||||||
const issued = yield* sessions.issue({
|
|
||||||
subject: "reconnect-test",
|
|
||||||
method: "bearer-session-token",
|
|
||||||
});
|
|
||||||
|
|
||||||
const beforeConnect = yield* sessions.listActive();
|
|
||||||
expect(beforeConnect[0]?.lastConnectedAt).toBeNull();
|
|
||||||
|
|
||||||
yield* TestClock.adjust(Duration.seconds(1));
|
|
||||||
yield* sessions.markConnected(issued.sessionId);
|
|
||||||
const firstConnect = yield* sessions.listActive();
|
|
||||||
const firstConnectedAt = firstConnect[0]?.lastConnectedAt;
|
|
||||||
|
|
||||||
expect(firstConnect[0]?.connected).toBe(true);
|
|
||||||
expect(firstConnectedAt).not.toBeNull();
|
|
||||||
|
|
||||||
yield* TestClock.adjust(Duration.seconds(1));
|
|
||||||
yield* sessions.markConnected(issued.sessionId);
|
|
||||||
const stillConnected = yield* sessions.listActive();
|
|
||||||
|
|
||||||
expect(stillConnected[0]?.lastConnectedAt?.toString()).toBe(firstConnectedAt?.toString());
|
|
||||||
|
|
||||||
yield* sessions.markDisconnected(issued.sessionId);
|
|
||||||
yield* sessions.markDisconnected(issued.sessionId);
|
|
||||||
const afterDisconnect = yield* sessions.listActive();
|
|
||||||
|
|
||||||
expect(afterDisconnect[0]?.connected).toBe(false);
|
|
||||||
expect(afterDisconnect[0]?.lastConnectedAt?.toString()).toBe(firstConnectedAt?.toString());
|
|
||||||
|
|
||||||
yield* TestClock.adjust(Duration.seconds(1));
|
|
||||||
yield* sessions.markConnected(issued.sessionId);
|
|
||||||
const afterReconnect = yield* sessions.listActive();
|
|
||||||
|
|
||||||
expect(afterReconnect[0]?.connected).toBe(true);
|
|
||||||
expect(afterReconnect[0]?.lastConnectedAt).not.toBeNull();
|
|
||||||
expect(afterReconnect[0]?.lastConnectedAt?.toString()).not.toBe(firstConnectedAt?.toString());
|
|
||||||
}).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,494 +0,0 @@
|
|||||||
import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "@t3tools/contracts";
|
|
||||||
import { Clock, DateTime, Duration, Effect, Layer, PubSub, Ref, Schema, Stream } from "effect";
|
|
||||||
import { Option } from "effect";
|
|
||||||
|
|
||||||
import { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts";
|
|
||||||
import { AuthSessionRepository } from "../../persistence/Services/AuthSessions.ts";
|
|
||||||
import { ServerSecretStore } from "../Services/ServerSecretStore.ts";
|
|
||||||
import { SESSION_COOKIE_NAME } from "../utils.ts";
|
|
||||||
import {
|
|
||||||
SessionCredentialError,
|
|
||||||
SessionCredentialService,
|
|
||||||
type IssuedSession,
|
|
||||||
type SessionCredentialChange,
|
|
||||||
type SessionCredentialServiceShape,
|
|
||||||
type VerifiedSession,
|
|
||||||
} from "../Services/SessionCredentialService.ts";
|
|
||||||
import {
|
|
||||||
base64UrlDecodeUtf8,
|
|
||||||
base64UrlEncode,
|
|
||||||
signPayload,
|
|
||||||
timingSafeEqualBase64Url,
|
|
||||||
} from "../utils.ts";
|
|
||||||
|
|
||||||
const SIGNING_SECRET_NAME = "server-signing-key";
|
|
||||||
const DEFAULT_SESSION_TTL = Duration.days(30);
|
|
||||||
const DEFAULT_WEBSOCKET_TOKEN_TTL = Duration.minutes(5);
|
|
||||||
|
|
||||||
const SessionClaims = Schema.Struct({
|
|
||||||
v: Schema.Literal(1),
|
|
||||||
kind: Schema.Literal("session"),
|
|
||||||
sid: AuthSessionId,
|
|
||||||
sub: Schema.String,
|
|
||||||
role: Schema.Literals(["owner", "client"]),
|
|
||||||
method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]),
|
|
||||||
iat: Schema.Number,
|
|
||||||
exp: Schema.Number,
|
|
||||||
});
|
|
||||||
type SessionClaims = typeof SessionClaims.Type;
|
|
||||||
|
|
||||||
const WebSocketClaims = Schema.Struct({
|
|
||||||
v: Schema.Literal(1),
|
|
||||||
kind: Schema.Literal("websocket"),
|
|
||||||
sid: AuthSessionId,
|
|
||||||
iat: Schema.Number,
|
|
||||||
exp: Schema.Number,
|
|
||||||
});
|
|
||||||
type WebSocketClaims = typeof WebSocketClaims.Type;
|
|
||||||
|
|
||||||
const decodeSessionClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(SessionClaims));
|
|
||||||
const decodeWebSocketClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(WebSocketClaims));
|
|
||||||
|
|
||||||
function createDefaultClientMetadata(): AuthClientMetadata {
|
|
||||||
return {
|
|
||||||
deviceType: "unknown",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function toClientMetadata(record: {
|
|
||||||
readonly label: string | null;
|
|
||||||
readonly ipAddress: string | null;
|
|
||||||
readonly userAgent: string | null;
|
|
||||||
readonly deviceType: AuthClientMetadata["deviceType"];
|
|
||||||
readonly os: string | null;
|
|
||||||
readonly browser: string | null;
|
|
||||||
}): AuthClientMetadata {
|
|
||||||
return {
|
|
||||||
...(record.label ? { label: record.label } : {}),
|
|
||||||
...(record.ipAddress ? { ipAddress: record.ipAddress } : {}),
|
|
||||||
...(record.userAgent ? { userAgent: record.userAgent } : {}),
|
|
||||||
deviceType: record.deviceType,
|
|
||||||
...(record.os ? { os: record.os } : {}),
|
|
||||||
...(record.browser ? { browser: record.browser } : {}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthClientSession {
|
|
||||||
return {
|
|
||||||
...input,
|
|
||||||
current: false,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export const makeSessionCredentialService = Effect.gen(function* () {
|
|
||||||
const secretStore = yield* ServerSecretStore;
|
|
||||||
const authSessions = yield* AuthSessionRepository;
|
|
||||||
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
|
|
||||||
const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
|
|
||||||
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
|
|
||||||
|
|
||||||
const toSessionCredentialError = (message: string) => (cause: unknown) =>
|
|
||||||
new SessionCredentialError({
|
|
||||||
message,
|
|
||||||
cause,
|
|
||||||
});
|
|
||||||
|
|
||||||
const emitUpsert = (clientSession: AuthClientSession) =>
|
|
||||||
PubSub.publish(changesPubSub, {
|
|
||||||
type: "clientUpserted",
|
|
||||||
clientSession,
|
|
||||||
}).pipe(Effect.asVoid);
|
|
||||||
|
|
||||||
const emitRemoved = (sessionId: AuthSessionId) =>
|
|
||||||
PubSub.publish(changesPubSub, {
|
|
||||||
type: "clientRemoved",
|
|
||||||
sessionId,
|
|
||||||
}).pipe(Effect.asVoid);
|
|
||||||
|
|
||||||
const loadActiveSession = (sessionId: AuthSessionId) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const row = yield* authSessions.getById({ sessionId });
|
|
||||||
if (Option.isNone(row) || row.value.revokedAt !== null) {
|
|
||||||
return Option.none<AuthClientSession>();
|
|
||||||
}
|
|
||||||
|
|
||||||
const connectedSessions = yield* Ref.get(connectedSessionsRef);
|
|
||||||
return Option.some(
|
|
||||||
toAuthClientSession({
|
|
||||||
sessionId: row.value.sessionId,
|
|
||||||
subject: row.value.subject,
|
|
||||||
role: row.value.role,
|
|
||||||
method: row.value.method,
|
|
||||||
client: toClientMetadata(row.value.client),
|
|
||||||
issuedAt: row.value.issuedAt,
|
|
||||||
expiresAt: row.value.expiresAt,
|
|
||||||
lastConnectedAt: row.value.lastConnectedAt,
|
|
||||||
connected: connectedSessions.has(row.value.sessionId),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
const markConnected: SessionCredentialServiceShape["markConnected"] = (sessionId) =>
|
|
||||||
Ref.modify(connectedSessionsRef, (current) => {
|
|
||||||
const next = new Map(current);
|
|
||||||
const wasDisconnected = !next.has(sessionId);
|
|
||||||
next.set(sessionId, (next.get(sessionId) ?? 0) + 1);
|
|
||||||
return [wasDisconnected, next] as const;
|
|
||||||
}).pipe(
|
|
||||||
Effect.flatMap((wasDisconnected) =>
|
|
||||||
wasDisconnected
|
|
||||||
? DateTime.now.pipe(
|
|
||||||
Effect.flatMap((lastConnectedAt) =>
|
|
||||||
authSessions.setLastConnectedAt({
|
|
||||||
sessionId,
|
|
||||||
lastConnectedAt,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
: Effect.void,
|
|
||||||
),
|
|
||||||
Effect.flatMap(() => loadActiveSession(sessionId)),
|
|
||||||
Effect.flatMap((session) =>
|
|
||||||
Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
|
|
||||||
),
|
|
||||||
Effect.catchCause((cause) =>
|
|
||||||
Effect.logError("Failed to publish connected-session auth update.").pipe(
|
|
||||||
Effect.annotateLogs({
|
|
||||||
sessionId,
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const markDisconnected: SessionCredentialServiceShape["markDisconnected"] = (sessionId) =>
|
|
||||||
Ref.update(connectedSessionsRef, (current) => {
|
|
||||||
const next = new Map(current);
|
|
||||||
const remaining = (next.get(sessionId) ?? 0) - 1;
|
|
||||||
if (remaining > 0) {
|
|
||||||
next.set(sessionId, remaining);
|
|
||||||
} else {
|
|
||||||
next.delete(sessionId);
|
|
||||||
}
|
|
||||||
return next;
|
|
||||||
}).pipe(
|
|
||||||
Effect.flatMap(() => loadActiveSession(sessionId)),
|
|
||||||
Effect.flatMap((session) =>
|
|
||||||
Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
|
|
||||||
),
|
|
||||||
Effect.catchCause((cause) =>
|
|
||||||
Effect.logError("Failed to publish disconnected-session auth update.").pipe(
|
|
||||||
Effect.annotateLogs({
|
|
||||||
sessionId,
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const issue: SessionCredentialServiceShape["issue"] = (input) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const sessionId = AuthSessionId.makeUnsafe(crypto.randomUUID());
|
|
||||||
const issuedAt = yield* DateTime.now;
|
|
||||||
const expiresAt = DateTime.add(issuedAt, {
|
|
||||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
|
|
||||||
});
|
|
||||||
const claims: SessionClaims = {
|
|
||||||
v: 1,
|
|
||||||
kind: "session",
|
|
||||||
sid: sessionId,
|
|
||||||
sub: input?.subject ?? "browser",
|
|
||||||
role: input?.role ?? "client",
|
|
||||||
method: input?.method ?? "browser-session-cookie",
|
|
||||||
iat: issuedAt.epochMilliseconds,
|
|
||||||
exp: expiresAt.epochMilliseconds,
|
|
||||||
};
|
|
||||||
const encodedPayload = base64UrlEncode(JSON.stringify(claims));
|
|
||||||
const signature = signPayload(encodedPayload, signingSecret);
|
|
||||||
const client = input?.client ?? createDefaultClientMetadata();
|
|
||||||
yield* authSessions.create({
|
|
||||||
sessionId,
|
|
||||||
subject: claims.sub,
|
|
||||||
role: claims.role,
|
|
||||||
method: claims.method,
|
|
||||||
client: {
|
|
||||||
label: client.label ?? null,
|
|
||||||
ipAddress: client.ipAddress ?? null,
|
|
||||||
userAgent: client.userAgent ?? null,
|
|
||||||
deviceType: client.deviceType,
|
|
||||||
os: client.os ?? null,
|
|
||||||
browser: client.browser ?? null,
|
|
||||||
},
|
|
||||||
issuedAt,
|
|
||||||
expiresAt,
|
|
||||||
});
|
|
||||||
yield* emitUpsert(
|
|
||||||
toAuthClientSession({
|
|
||||||
sessionId,
|
|
||||||
subject: claims.sub,
|
|
||||||
role: claims.role,
|
|
||||||
method: claims.method,
|
|
||||||
client,
|
|
||||||
issuedAt,
|
|
||||||
expiresAt,
|
|
||||||
lastConnectedAt: null,
|
|
||||||
connected: false,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
sessionId,
|
|
||||||
token: `${encodedPayload}.${signature}`,
|
|
||||||
method: claims.method,
|
|
||||||
client,
|
|
||||||
expiresAt: expiresAt,
|
|
||||||
role: claims.role,
|
|
||||||
} satisfies IssuedSession;
|
|
||||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to issue session credential.")));
|
|
||||||
|
|
||||||
const verify: SessionCredentialServiceShape["verify"] = (token) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const [encodedPayload, signature] = token.split(".");
|
|
||||||
if (!encodedPayload || !signature) {
|
|
||||||
return yield* new SessionCredentialError({
|
|
||||||
message: "Malformed session token.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const expectedSignature = signPayload(encodedPayload, signingSecret);
|
|
||||||
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
|
|
||||||
return yield* new SessionCredentialError({
|
|
||||||
message: "Invalid session token signature.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new SessionCredentialError({
|
|
||||||
message: "Invalid session token payload.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const now = yield* Clock.currentTimeMillis;
|
|
||||||
if (claims.exp <= now) {
|
|
||||||
return yield* new SessionCredentialError({
|
|
||||||
message: "Session token expired.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const row = yield* authSessions.getById({ sessionId: claims.sid });
|
|
||||||
if (Option.isNone(row)) {
|
|
||||||
return yield* new SessionCredentialError({
|
|
||||||
message: "Unknown session token.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if (row.value.revokedAt !== null) {
|
|
||||||
return yield* new SessionCredentialError({
|
|
||||||
message: "Session token revoked.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
sessionId: claims.sid,
|
|
||||||
token,
|
|
||||||
method: claims.method,
|
|
||||||
client: toClientMetadata(row.value.client),
|
|
||||||
expiresAt: DateTime.makeUnsafe(claims.exp),
|
|
||||||
subject: claims.sub,
|
|
||||||
role: claims.role,
|
|
||||||
} satisfies VerifiedSession;
|
|
||||||
}).pipe(
|
|
||||||
Effect.mapError((cause) =>
|
|
||||||
cause instanceof SessionCredentialError
|
|
||||||
? cause
|
|
||||||
: new SessionCredentialError({
|
|
||||||
message: "Failed to verify session credential.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const issueWebSocketToken: SessionCredentialServiceShape["issueWebSocketToken"] = (
|
|
||||||
sessionId,
|
|
||||||
input,
|
|
||||||
) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const issuedAt = yield* DateTime.now;
|
|
||||||
const expiresAt = DateTime.add(issuedAt, {
|
|
||||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
|
|
||||||
});
|
|
||||||
const claims: WebSocketClaims = {
|
|
||||||
v: 1,
|
|
||||||
kind: "websocket",
|
|
||||||
sid: sessionId,
|
|
||||||
iat: issuedAt.epochMilliseconds,
|
|
||||||
exp: expiresAt.epochMilliseconds,
|
|
||||||
};
|
|
||||||
const encodedPayload = base64UrlEncode(JSON.stringify(claims));
|
|
||||||
const signature = signPayload(encodedPayload, signingSecret);
|
|
||||||
return {
|
|
||||||
token: `${encodedPayload}.${signature}`,
|
|
||||||
expiresAt,
|
|
||||||
};
|
|
||||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to issue websocket token.")));
|
|
||||||
|
|
||||||
const verifyWebSocketToken: SessionCredentialServiceShape["verifyWebSocketToken"] = (token) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const [encodedPayload, signature] = token.split(".");
|
|
||||||
if (!encodedPayload || !signature) {
|
|
||||||
return yield* new SessionCredentialError({
|
|
||||||
message: "Malformed websocket token.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const expectedSignature = signPayload(encodedPayload, signingSecret);
|
|
||||||
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
|
|
||||||
return yield* new SessionCredentialError({
|
|
||||||
message: "Invalid websocket token signature.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new SessionCredentialError({
|
|
||||||
message: "Invalid websocket token payload.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const now = yield* Clock.currentTimeMillis;
|
|
||||||
if (claims.exp <= now) {
|
|
||||||
return yield* new SessionCredentialError({
|
|
||||||
message: "Websocket token expired.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const row = yield* authSessions.getById({ sessionId: claims.sid });
|
|
||||||
if (Option.isNone(row)) {
|
|
||||||
return yield* new SessionCredentialError({
|
|
||||||
message: "Unknown websocket session.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if (row.value.expiresAt.epochMilliseconds <= now) {
|
|
||||||
return yield* new SessionCredentialError({
|
|
||||||
message: "Websocket session expired.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if (row.value.revokedAt !== null) {
|
|
||||||
return yield* new SessionCredentialError({
|
|
||||||
message: "Websocket session revoked.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
sessionId: row.value.sessionId,
|
|
||||||
token,
|
|
||||||
method: row.value.method,
|
|
||||||
client: toClientMetadata(row.value.client),
|
|
||||||
expiresAt: row.value.expiresAt,
|
|
||||||
subject: row.value.subject,
|
|
||||||
role: row.value.role,
|
|
||||||
} satisfies VerifiedSession;
|
|
||||||
}).pipe(
|
|
||||||
Effect.mapError((cause) =>
|
|
||||||
cause instanceof SessionCredentialError
|
|
||||||
? cause
|
|
||||||
: new SessionCredentialError({
|
|
||||||
message: "Failed to verify websocket token.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const listActive: SessionCredentialServiceShape["listActive"] = () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const now = yield* DateTime.now;
|
|
||||||
const connectedSessions = yield* Ref.get(connectedSessionsRef);
|
|
||||||
const rows = yield* authSessions.listActive({ now });
|
|
||||||
|
|
||||||
return rows.map((row) =>
|
|
||||||
toAuthClientSession({
|
|
||||||
sessionId: row.sessionId,
|
|
||||||
subject: row.subject,
|
|
||||||
role: row.role,
|
|
||||||
method: row.method,
|
|
||||||
client: toClientMetadata(row.client),
|
|
||||||
issuedAt: row.issuedAt,
|
|
||||||
expiresAt: row.expiresAt,
|
|
||||||
lastConnectedAt: row.lastConnectedAt,
|
|
||||||
connected: connectedSessions.has(row.sessionId),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to list active sessions.")));
|
|
||||||
|
|
||||||
const revoke: SessionCredentialServiceShape["revoke"] = (sessionId) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const revokedAt = yield* DateTime.now;
|
|
||||||
const revoked = yield* authSessions.revoke({
|
|
||||||
sessionId,
|
|
||||||
revokedAt,
|
|
||||||
});
|
|
||||||
if (revoked) {
|
|
||||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
|
||||||
const next = new Map(current);
|
|
||||||
next.delete(sessionId);
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
yield* emitRemoved(sessionId);
|
|
||||||
}
|
|
||||||
return revoked;
|
|
||||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke session.")));
|
|
||||||
|
|
||||||
const revokeAllExcept: SessionCredentialServiceShape["revokeAllExcept"] = (sessionId) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const revokedAt = yield* DateTime.now;
|
|
||||||
const revokedSessionIds = yield* authSessions.revokeAllExcept({
|
|
||||||
currentSessionId: sessionId,
|
|
||||||
revokedAt,
|
|
||||||
});
|
|
||||||
if (revokedSessionIds.length > 0) {
|
|
||||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
|
||||||
const next = new Map(current);
|
|
||||||
for (const revokedSessionId of revokedSessionIds) {
|
|
||||||
next.delete(revokedSessionId);
|
|
||||||
}
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
yield* Effect.forEach(
|
|
||||||
revokedSessionIds,
|
|
||||||
(revokedSessionId) => emitRemoved(revokedSessionId),
|
|
||||||
{
|
|
||||||
concurrency: "unbounded",
|
|
||||||
discard: true,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return revokedSessionIds.length;
|
|
||||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke other sessions.")));
|
|
||||||
|
|
||||||
return {
|
|
||||||
cookieName: SESSION_COOKIE_NAME,
|
|
||||||
issue,
|
|
||||||
verify,
|
|
||||||
issueWebSocketToken,
|
|
||||||
verifyWebSocketToken,
|
|
||||||
listActive,
|
|
||||||
get streamChanges() {
|
|
||||||
return Stream.fromPubSub(changesPubSub);
|
|
||||||
},
|
|
||||||
revoke,
|
|
||||||
revokeAllExcept,
|
|
||||||
markConnected,
|
|
||||||
markDisconnected,
|
|
||||||
} satisfies SessionCredentialServiceShape;
|
|
||||||
});
|
|
||||||
|
|
||||||
export const SessionCredentialServiceLive = Layer.effect(
|
|
||||||
SessionCredentialService,
|
|
||||||
makeSessionCredentialService,
|
|
||||||
).pipe(Layer.provideMerge(AuthSessionRepositoryLive));
|
|
||||||
@@ -1,69 +0,0 @@
|
|||||||
import type {
|
|
||||||
AuthClientMetadata,
|
|
||||||
AuthClientSession,
|
|
||||||
AuthPairingLink,
|
|
||||||
AuthSessionId,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
import { Data, DateTime, Duration, Effect, ServiceMap } from "effect";
|
|
||||||
import { SessionRole } from "./SessionCredentialService";
|
|
||||||
|
|
||||||
export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
|
|
||||||
|
|
||||||
export interface IssuedPairingLink {
|
|
||||||
readonly id: string;
|
|
||||||
readonly credential: string;
|
|
||||||
readonly role: SessionRole;
|
|
||||||
readonly subject: string;
|
|
||||||
readonly label?: string;
|
|
||||||
readonly createdAt: DateTime.Utc;
|
|
||||||
readonly expiresAt: DateTime.Utc;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IssuedBearerSession {
|
|
||||||
readonly sessionId: AuthSessionId;
|
|
||||||
readonly token: string;
|
|
||||||
readonly method: "bearer-session-token";
|
|
||||||
readonly role: SessionRole;
|
|
||||||
readonly subject: string;
|
|
||||||
readonly client: AuthClientMetadata;
|
|
||||||
readonly expiresAt: DateTime.Utc;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class AuthControlPlaneError extends Data.TaggedError("AuthControlPlaneError")<{
|
|
||||||
readonly message: string;
|
|
||||||
readonly cause?: unknown;
|
|
||||||
}> {}
|
|
||||||
|
|
||||||
export interface AuthControlPlaneShape {
|
|
||||||
readonly createPairingLink: (input?: {
|
|
||||||
readonly ttl?: Duration.Duration;
|
|
||||||
readonly label?: string;
|
|
||||||
readonly role?: SessionRole;
|
|
||||||
readonly subject?: string;
|
|
||||||
}) => Effect.Effect<IssuedPairingLink, AuthControlPlaneError>;
|
|
||||||
readonly listPairingLinks: (input?: {
|
|
||||||
readonly role?: SessionRole;
|
|
||||||
readonly excludeSubjects?: ReadonlyArray<string>;
|
|
||||||
}) => Effect.Effect<ReadonlyArray<AuthPairingLink>, AuthControlPlaneError>;
|
|
||||||
readonly revokePairingLink: (id: string) => Effect.Effect<boolean, AuthControlPlaneError>;
|
|
||||||
readonly issueSession: (input?: {
|
|
||||||
readonly ttl?: Duration.Duration;
|
|
||||||
readonly subject?: string;
|
|
||||||
readonly role?: SessionRole;
|
|
||||||
readonly label?: string;
|
|
||||||
}) => Effect.Effect<IssuedBearerSession, AuthControlPlaneError>;
|
|
||||||
readonly listSessions: () => Effect.Effect<
|
|
||||||
ReadonlyArray<AuthClientSession>,
|
|
||||||
AuthControlPlaneError
|
|
||||||
>;
|
|
||||||
readonly revokeSession: (
|
|
||||||
sessionId: AuthSessionId,
|
|
||||||
) => Effect.Effect<boolean, AuthControlPlaneError>;
|
|
||||||
readonly revokeOtherSessionsExcept: (
|
|
||||||
sessionId: AuthSessionId,
|
|
||||||
) => Effect.Effect<number, AuthControlPlaneError>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class AuthControlPlane extends ServiceMap.Service<AuthControlPlane, AuthControlPlaneShape>()(
|
|
||||||
"t3/AuthControlPlane",
|
|
||||||
) {}
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
import type { AuthPairingLink, ServerAuthBootstrapMethod } from "@t3tools/contracts";
|
|
||||||
import { Data, DateTime, Duration, ServiceMap } from "effect";
|
|
||||||
import type { Effect, Stream } from "effect";
|
|
||||||
|
|
||||||
export type BootstrapCredentialRole = "owner" | "client";
|
|
||||||
|
|
||||||
export interface BootstrapGrant {
|
|
||||||
readonly method: ServerAuthBootstrapMethod;
|
|
||||||
readonly role: BootstrapCredentialRole;
|
|
||||||
readonly subject: string;
|
|
||||||
readonly label?: string;
|
|
||||||
readonly expiresAt: DateTime.DateTime;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class BootstrapCredentialError extends Data.TaggedError("BootstrapCredentialError")<{
|
|
||||||
readonly message: string;
|
|
||||||
readonly status?: 401 | 500;
|
|
||||||
readonly cause?: unknown;
|
|
||||||
}> {}
|
|
||||||
|
|
||||||
export interface IssuedBootstrapCredential {
|
|
||||||
readonly id: string;
|
|
||||||
readonly credential: string;
|
|
||||||
readonly label?: string;
|
|
||||||
readonly expiresAt: DateTime.Utc;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type BootstrapCredentialChange =
|
|
||||||
| {
|
|
||||||
readonly type: "pairingLinkUpserted";
|
|
||||||
readonly pairingLink: AuthPairingLink;
|
|
||||||
}
|
|
||||||
| {
|
|
||||||
readonly type: "pairingLinkRemoved";
|
|
||||||
readonly id: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export interface BootstrapCredentialServiceShape {
|
|
||||||
readonly issueOneTimeToken: (input?: {
|
|
||||||
readonly ttl?: Duration.Duration;
|
|
||||||
readonly role?: BootstrapCredentialRole;
|
|
||||||
readonly subject?: string;
|
|
||||||
readonly label?: string;
|
|
||||||
}) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialError>;
|
|
||||||
readonly listActive: () => Effect.Effect<
|
|
||||||
ReadonlyArray<AuthPairingLink>,
|
|
||||||
BootstrapCredentialError
|
|
||||||
>;
|
|
||||||
readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;
|
|
||||||
readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialError>;
|
|
||||||
readonly consume: (credential: string) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class BootstrapCredentialService extends ServiceMap.Service<
|
|
||||||
BootstrapCredentialService,
|
|
||||||
BootstrapCredentialServiceShape
|
|
||||||
>()("t3/auth/Services/BootstrapCredentialService") {}
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
import type {
|
|
||||||
AuthBearerBootstrapResult,
|
|
||||||
AuthBootstrapResult,
|
|
||||||
AuthClientMetadata,
|
|
||||||
AuthClientSession,
|
|
||||||
AuthCreatePairingCredentialInput,
|
|
||||||
AuthPairingLink,
|
|
||||||
AuthPairingCredentialResult,
|
|
||||||
AuthSessionId,
|
|
||||||
AuthSessionState,
|
|
||||||
ServerAuthDescriptor,
|
|
||||||
ServerAuthSessionMethod,
|
|
||||||
AuthWebSocketTokenResult,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
import { Data, DateTime, ServiceMap } from "effect";
|
|
||||||
import type { Effect } from "effect";
|
|
||||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
|
||||||
import type { SessionRole } from "./SessionCredentialService.ts";
|
|
||||||
|
|
||||||
export interface AuthenticatedSession {
|
|
||||||
readonly sessionId: AuthSessionId;
|
|
||||||
readonly subject: string;
|
|
||||||
readonly method: ServerAuthSessionMethod;
|
|
||||||
readonly role: SessionRole;
|
|
||||||
readonly expiresAt?: DateTime.DateTime;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class AuthError extends Data.TaggedError("AuthError")<{
|
|
||||||
readonly message: string;
|
|
||||||
readonly status?: 400 | 401 | 403 | 500;
|
|
||||||
readonly cause?: unknown;
|
|
||||||
}> {}
|
|
||||||
|
|
||||||
export interface ServerAuthShape {
|
|
||||||
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
|
|
||||||
readonly getSessionState: (
|
|
||||||
request: HttpServerRequest.HttpServerRequest,
|
|
||||||
) => Effect.Effect<AuthSessionState, never>;
|
|
||||||
readonly exchangeBootstrapCredential: (
|
|
||||||
credential: string,
|
|
||||||
requestMetadata: AuthClientMetadata,
|
|
||||||
) => Effect.Effect<
|
|
||||||
{
|
|
||||||
readonly response: AuthBootstrapResult;
|
|
||||||
readonly sessionToken: string;
|
|
||||||
},
|
|
||||||
AuthError
|
|
||||||
>;
|
|
||||||
readonly exchangeBootstrapCredentialForBearerSession: (
|
|
||||||
credential: string,
|
|
||||||
requestMetadata: AuthClientMetadata,
|
|
||||||
) => Effect.Effect<AuthBearerBootstrapResult, AuthError>;
|
|
||||||
readonly issuePairingCredential: (
|
|
||||||
input?: AuthCreatePairingCredentialInput & {
|
|
||||||
readonly role?: SessionRole;
|
|
||||||
},
|
|
||||||
) => Effect.Effect<AuthPairingCredentialResult, AuthError>;
|
|
||||||
readonly listPairingLinks: () => Effect.Effect<ReadonlyArray<AuthPairingLink>, AuthError>;
|
|
||||||
readonly revokePairingLink: (id: string) => Effect.Effect<boolean, AuthError>;
|
|
||||||
readonly listClientSessions: (
|
|
||||||
currentSessionId: AuthSessionId,
|
|
||||||
) => Effect.Effect<ReadonlyArray<AuthClientSession>, AuthError>;
|
|
||||||
readonly revokeClientSession: (
|
|
||||||
currentSessionId: AuthSessionId,
|
|
||||||
targetSessionId: AuthSessionId,
|
|
||||||
) => Effect.Effect<boolean, AuthError>;
|
|
||||||
readonly revokeOtherClientSessions: (
|
|
||||||
currentSessionId: AuthSessionId,
|
|
||||||
) => Effect.Effect<number, AuthError>;
|
|
||||||
readonly authenticateHttpRequest: (
|
|
||||||
request: HttpServerRequest.HttpServerRequest,
|
|
||||||
) => Effect.Effect<AuthenticatedSession, AuthError>;
|
|
||||||
readonly authenticateWebSocketUpgrade: (
|
|
||||||
request: HttpServerRequest.HttpServerRequest,
|
|
||||||
) => Effect.Effect<AuthenticatedSession, AuthError>;
|
|
||||||
readonly issueWebSocketToken: (
|
|
||||||
session: AuthenticatedSession,
|
|
||||||
) => Effect.Effect<AuthWebSocketTokenResult, AuthError>;
|
|
||||||
readonly issueStartupPairingUrl: (baseUrl: string) => Effect.Effect<string, AuthError>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class ServerAuth extends ServiceMap.Service<ServerAuth, ServerAuthShape>()(
|
|
||||||
"t3/auth/Services/ServerAuth",
|
|
||||||
) {}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
import type { ServerAuthDescriptor } from "@t3tools/contracts";
|
|
||||||
import { ServiceMap } from "effect";
|
|
||||||
import type { Effect } from "effect";
|
|
||||||
|
|
||||||
export interface ServerAuthPolicyShape {
|
|
||||||
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class ServerAuthPolicy extends ServiceMap.Service<ServerAuthPolicy, ServerAuthPolicyShape>()(
|
|
||||||
"t3/auth/Services/ServerAuthPolicy",
|
|
||||||
) {}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
import { Data, ServiceMap } from "effect";
|
|
||||||
import type { Effect } from "effect";
|
|
||||||
|
|
||||||
export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{
|
|
||||||
readonly message: string;
|
|
||||||
readonly cause?: unknown;
|
|
||||||
}> {}
|
|
||||||
|
|
||||||
export interface ServerSecretStoreShape {
|
|
||||||
readonly get: (name: string) => Effect.Effect<Uint8Array | null, SecretStoreError>;
|
|
||||||
readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
|
|
||||||
readonly getOrCreateRandom: (
|
|
||||||
name: string,
|
|
||||||
bytes: number,
|
|
||||||
) => Effect.Effect<Uint8Array, SecretStoreError>;
|
|
||||||
readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class ServerSecretStore extends ServiceMap.Service<
|
|
||||||
ServerSecretStore,
|
|
||||||
ServerSecretStoreShape
|
|
||||||
>()("t3/auth/Services/ServerSecretStore") {}
|
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
import type {
|
|
||||||
AuthClientMetadata,
|
|
||||||
AuthClientSession,
|
|
||||||
AuthSessionId,
|
|
||||||
ServerAuthSessionMethod,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
import { Data, DateTime, Duration, ServiceMap } from "effect";
|
|
||||||
import type { Effect, Stream } from "effect";
|
|
||||||
|
|
||||||
export type SessionRole = "owner" | "client";
|
|
||||||
|
|
||||||
export interface IssuedSession {
|
|
||||||
readonly sessionId: AuthSessionId;
|
|
||||||
readonly token: string;
|
|
||||||
readonly method: ServerAuthSessionMethod;
|
|
||||||
readonly client: AuthClientMetadata;
|
|
||||||
readonly expiresAt: DateTime.DateTime;
|
|
||||||
readonly role: SessionRole;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface VerifiedSession {
|
|
||||||
readonly sessionId: AuthSessionId;
|
|
||||||
readonly token: string;
|
|
||||||
readonly method: ServerAuthSessionMethod;
|
|
||||||
readonly client: AuthClientMetadata;
|
|
||||||
readonly expiresAt?: DateTime.DateTime;
|
|
||||||
readonly subject: string;
|
|
||||||
readonly role: SessionRole;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type SessionCredentialChange =
|
|
||||||
| {
|
|
||||||
readonly type: "clientUpserted";
|
|
||||||
readonly clientSession: AuthClientSession;
|
|
||||||
}
|
|
||||||
| {
|
|
||||||
readonly type: "clientRemoved";
|
|
||||||
readonly sessionId: AuthSessionId;
|
|
||||||
};
|
|
||||||
|
|
||||||
export class SessionCredentialError extends Data.TaggedError("SessionCredentialError")<{
|
|
||||||
readonly message: string;
|
|
||||||
readonly cause?: unknown;
|
|
||||||
}> {}
|
|
||||||
|
|
||||||
export interface SessionCredentialServiceShape {
|
|
||||||
readonly cookieName: string;
|
|
||||||
readonly issue: (input?: {
|
|
||||||
readonly ttl?: Duration.Duration;
|
|
||||||
readonly subject?: string;
|
|
||||||
readonly method?: ServerAuthSessionMethod;
|
|
||||||
readonly role?: SessionRole;
|
|
||||||
readonly client?: AuthClientMetadata;
|
|
||||||
}) => Effect.Effect<IssuedSession, SessionCredentialError>;
|
|
||||||
readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;
|
|
||||||
readonly issueWebSocketToken: (
|
|
||||||
sessionId: AuthSessionId,
|
|
||||||
input?: {
|
|
||||||
readonly ttl?: Duration.Duration;
|
|
||||||
},
|
|
||||||
) => Effect.Effect<
|
|
||||||
{
|
|
||||||
readonly token: string;
|
|
||||||
readonly expiresAt: DateTime.DateTime;
|
|
||||||
},
|
|
||||||
SessionCredentialError
|
|
||||||
>;
|
|
||||||
readonly verifyWebSocketToken: (
|
|
||||||
token: string,
|
|
||||||
) => Effect.Effect<VerifiedSession, SessionCredentialError>;
|
|
||||||
readonly listActive: () => Effect.Effect<
|
|
||||||
ReadonlyArray<AuthClientSession>,
|
|
||||||
SessionCredentialError
|
|
||||||
>;
|
|
||||||
readonly streamChanges: Stream.Stream<SessionCredentialChange>;
|
|
||||||
readonly revoke: (sessionId: AuthSessionId) => Effect.Effect<boolean, SessionCredentialError>;
|
|
||||||
readonly revokeAllExcept: (
|
|
||||||
sessionId: AuthSessionId,
|
|
||||||
) => Effect.Effect<number, SessionCredentialError>;
|
|
||||||
readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
|
|
||||||
readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class SessionCredentialService extends ServiceMap.Service<
|
|
||||||
SessionCredentialService,
|
|
||||||
SessionCredentialServiceShape
|
|
||||||
>()("t3/auth/Services/SessionCredentialService") {}
|
|
||||||
@@ -1,254 +0,0 @@
|
|||||||
import {
|
|
||||||
type AuthBearerBootstrapResult,
|
|
||||||
AuthBootstrapInput,
|
|
||||||
AuthCreatePairingCredentialInput,
|
|
||||||
AuthRevokeClientSessionInput,
|
|
||||||
AuthRevokePairingLinkInput,
|
|
||||||
type AuthWebSocketTokenResult,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
import { DateTime, Effect, Schema } from "effect";
|
|
||||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
|
||||||
|
|
||||||
import { AuthError, ServerAuth } from "./Services/ServerAuth.ts";
|
|
||||||
import { SessionCredentialService } from "./Services/SessionCredentialService.ts";
|
|
||||||
import { deriveAuthClientMetadata } from "./utils.ts";
|
|
||||||
|
|
||||||
export const respondToAuthError = (error: AuthError) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
if ((error.status ?? 500) >= 500) {
|
|
||||||
yield* Effect.logError("auth route failed", {
|
|
||||||
message: error.message,
|
|
||||||
cause: error.cause,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return HttpServerResponse.jsonUnsafe(
|
|
||||||
{
|
|
||||||
error: error.message,
|
|
||||||
},
|
|
||||||
{ status: error.status ?? 500 },
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
export const authSessionRouteLayer = HttpRouter.add(
|
|
||||||
"GET",
|
|
||||||
"/api/auth/session",
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
||||||
const serverAuth = yield* ServerAuth;
|
|
||||||
const session = yield* serverAuth.getSessionState(request);
|
|
||||||
return HttpServerResponse.jsonUnsafe(session, { status: 200 });
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const PairingCredentialRequestHeaders = Schema.Struct({
|
|
||||||
"content-length": Schema.optionalKey(Schema.String),
|
|
||||||
"content-type": Schema.optionalKey(Schema.String),
|
|
||||||
"transfer-encoding": Schema.optionalKey(Schema.String),
|
|
||||||
});
|
|
||||||
|
|
||||||
function hasRequestBody(headers: typeof PairingCredentialRequestHeaders.Type) {
|
|
||||||
const contentLengthHeader = headers["content-length"];
|
|
||||||
if (typeof contentLengthHeader === "string") {
|
|
||||||
const contentLength = Number.parseInt(contentLengthHeader, 10);
|
|
||||||
if (Number.isFinite(contentLength)) {
|
|
||||||
return contentLength > 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return typeof headers["transfer-encoding"] === "string";
|
|
||||||
}
|
|
||||||
|
|
||||||
export const authBootstrapRouteLayer = HttpRouter.add(
|
|
||||||
"POST",
|
|
||||||
"/api/auth/bootstrap",
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
||||||
const serverAuth = yield* ServerAuth;
|
|
||||||
const sessions = yield* SessionCredentialService;
|
|
||||||
const payload = yield* HttpServerRequest.schemaBodyJson(AuthBootstrapInput).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new AuthError({
|
|
||||||
message: "Invalid bootstrap payload.",
|
|
||||||
status: 400,
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
const result = yield* serverAuth.exchangeBootstrapCredential(
|
|
||||||
payload.credential,
|
|
||||||
deriveAuthClientMetadata({ request }),
|
|
||||||
);
|
|
||||||
|
|
||||||
return yield* HttpServerResponse.jsonUnsafe(result.response, { status: 200 }).pipe(
|
|
||||||
HttpServerResponse.setCookie(sessions.cookieName, result.sessionToken, {
|
|
||||||
expires: DateTime.toDate(result.response.expiresAt),
|
|
||||||
httpOnly: true,
|
|
||||||
path: "/",
|
|
||||||
sameSite: "lax",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
|
||||||
);
|
|
||||||
|
|
||||||
export const authBearerBootstrapRouteLayer = HttpRouter.add(
|
|
||||||
"POST",
|
|
||||||
"/api/auth/bootstrap/bearer",
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
||||||
const serverAuth = yield* ServerAuth;
|
|
||||||
const payload = yield* HttpServerRequest.schemaBodyJson(AuthBootstrapInput).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new AuthError({
|
|
||||||
message: "Invalid bootstrap payload.",
|
|
||||||
status: 400,
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
const result = yield* serverAuth.exchangeBootstrapCredentialForBearerSession(
|
|
||||||
payload.credential,
|
|
||||||
deriveAuthClientMetadata({ request }),
|
|
||||||
);
|
|
||||||
return HttpServerResponse.jsonUnsafe(result satisfies AuthBearerBootstrapResult, {
|
|
||||||
status: 200,
|
|
||||||
});
|
|
||||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
|
||||||
);
|
|
||||||
|
|
||||||
export const authWebSocketTokenRouteLayer = HttpRouter.add(
|
|
||||||
"POST",
|
|
||||||
"/api/auth/ws-token",
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
||||||
const serverAuth = yield* ServerAuth;
|
|
||||||
const session = yield* serverAuth.authenticateHttpRequest(request);
|
|
||||||
const result = yield* serverAuth.issueWebSocketToken(session);
|
|
||||||
return HttpServerResponse.jsonUnsafe(result satisfies AuthWebSocketTokenResult, {
|
|
||||||
status: 200,
|
|
||||||
});
|
|
||||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
|
||||||
);
|
|
||||||
|
|
||||||
export const authPairingCredentialRouteLayer = HttpRouter.add(
|
|
||||||
"POST",
|
|
||||||
"/api/auth/pairing-token",
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const serverAuth = yield* ServerAuth;
|
|
||||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
||||||
const session = yield* serverAuth.authenticateHttpRequest(request);
|
|
||||||
if (session.role !== "owner") {
|
|
||||||
return yield* new AuthError({
|
|
||||||
message: "Only owner sessions can create pairing credentials.",
|
|
||||||
status: 403,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const headers = yield* HttpServerRequest.schemaHeaders(PairingCredentialRequestHeaders).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new AuthError({
|
|
||||||
message: "Invalid pairing credential request headers.",
|
|
||||||
status: 400,
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
const payload = hasRequestBody(headers)
|
|
||||||
? yield* HttpServerRequest.schemaBodyJson(AuthCreatePairingCredentialInput).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new AuthError({
|
|
||||||
message: "Invalid pairing credential payload.",
|
|
||||||
status: 400,
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
: {};
|
|
||||||
const result = yield* serverAuth.issuePairingCredential(payload);
|
|
||||||
return HttpServerResponse.jsonUnsafe(result, { status: 200 });
|
|
||||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
|
||||||
);
|
|
||||||
|
|
||||||
const authenticateOwnerSession = Effect.gen(function* () {
|
|
||||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
||||||
const serverAuth = yield* ServerAuth;
|
|
||||||
const session = yield* serverAuth.authenticateHttpRequest(request);
|
|
||||||
if (session.role !== "owner") {
|
|
||||||
return yield* new AuthError({
|
|
||||||
message: "Only owner sessions can manage network access.",
|
|
||||||
status: 403,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return { serverAuth, session } as const;
|
|
||||||
});
|
|
||||||
|
|
||||||
export const authPairingLinksRouteLayer = HttpRouter.add(
|
|
||||||
"GET",
|
|
||||||
"/api/auth/pairing-links",
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const { serverAuth } = yield* authenticateOwnerSession;
|
|
||||||
const pairingLinks = yield* serverAuth.listPairingLinks();
|
|
||||||
return HttpServerResponse.jsonUnsafe(pairingLinks, { status: 200 });
|
|
||||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
|
||||||
);
|
|
||||||
|
|
||||||
export const authPairingLinksRevokeRouteLayer = HttpRouter.add(
|
|
||||||
"POST",
|
|
||||||
"/api/auth/pairing-links/revoke",
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const { serverAuth } = yield* authenticateOwnerSession;
|
|
||||||
const payload = yield* HttpServerRequest.schemaBodyJson(AuthRevokePairingLinkInput).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new AuthError({
|
|
||||||
message: "Invalid revoke pairing link payload.",
|
|
||||||
status: 400,
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
const revoked = yield* serverAuth.revokePairingLink(payload.id);
|
|
||||||
return HttpServerResponse.jsonUnsafe({ revoked }, { status: 200 });
|
|
||||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
|
||||||
);
|
|
||||||
|
|
||||||
export const authClientsRouteLayer = HttpRouter.add(
|
|
||||||
"GET",
|
|
||||||
"/api/auth/clients",
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const { serverAuth, session } = yield* authenticateOwnerSession;
|
|
||||||
const clients = yield* serverAuth.listClientSessions(session.sessionId);
|
|
||||||
return HttpServerResponse.jsonUnsafe(clients, { status: 200 });
|
|
||||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
|
||||||
);
|
|
||||||
|
|
||||||
export const authClientsRevokeRouteLayer = HttpRouter.add(
|
|
||||||
"POST",
|
|
||||||
"/api/auth/clients/revoke",
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const { serverAuth, session } = yield* authenticateOwnerSession;
|
|
||||||
const payload = yield* HttpServerRequest.schemaBodyJson(AuthRevokeClientSessionInput).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new AuthError({
|
|
||||||
message: "Invalid revoke client payload.",
|
|
||||||
status: 400,
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
const revoked = yield* serverAuth.revokeClientSession(session.sessionId, payload.sessionId);
|
|
||||||
return HttpServerResponse.jsonUnsafe({ revoked }, { status: 200 });
|
|
||||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
|
||||||
);
|
|
||||||
|
|
||||||
export const authClientsRevokeOthersRouteLayer = HttpRouter.add(
|
|
||||||
"POST",
|
|
||||||
"/api/auth/clients/revoke-others",
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const { serverAuth, session } = yield* authenticateOwnerSession;
|
|
||||||
const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);
|
|
||||||
return HttpServerResponse.jsonUnsafe({ revokedCount }, { status: 200 });
|
|
||||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
|
||||||
);
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
|
||||||
|
|
||||||
import { deriveAuthClientMetadata } from "./utils";
|
|
||||||
|
|
||||||
describe("deriveAuthClientMetadata", () => {
|
|
||||||
it("labels Electron user agents as Electron instead of Chrome", () => {
|
|
||||||
const metadata = deriveAuthClientMetadata({
|
|
||||||
request: {
|
|
||||||
headers: {
|
|
||||||
"user-agent":
|
|
||||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) t3code/0.0.15 Chrome/136.0.7103.93 Electron/36.3.2 Safari/537.36",
|
|
||||||
},
|
|
||||||
source: {
|
|
||||||
remoteAddress: "::ffff:127.0.0.1",
|
|
||||||
},
|
|
||||||
} as never,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(metadata).toMatchObject({
|
|
||||||
browser: "Electron",
|
|
||||||
deviceType: "desktop",
|
|
||||||
ipAddress: "127.0.0.1",
|
|
||||||
os: "macOS",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,121 +0,0 @@
|
|||||||
import type { AuthClientMetadata, AuthClientMetadataDeviceType } from "@t3tools/contracts";
|
|
||||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
|
||||||
import * as Crypto from "node:crypto";
|
|
||||||
|
|
||||||
export const SESSION_COOKIE_NAME = "t3_session";
|
|
||||||
|
|
||||||
export function base64UrlEncode(input: string | Uint8Array): string {
|
|
||||||
const buffer = typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.from(input);
|
|
||||||
return buffer.toString("base64url");
|
|
||||||
}
|
|
||||||
|
|
||||||
export function base64UrlDecodeUtf8(input: string): string {
|
|
||||||
return Buffer.from(input, "base64url").toString("utf8");
|
|
||||||
}
|
|
||||||
|
|
||||||
export function signPayload(payload: string, secret: Uint8Array): string {
|
|
||||||
return Crypto.createHmac("sha256", Buffer.from(secret)).update(payload).digest("base64url");
|
|
||||||
}
|
|
||||||
|
|
||||||
export function timingSafeEqualBase64Url(left: string, right: string): boolean {
|
|
||||||
const leftBuffer = Buffer.from(left, "base64url");
|
|
||||||
const rightBuffer = Buffer.from(right, "base64url");
|
|
||||||
if (leftBuffer.length !== rightBuffer.length) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return Crypto.timingSafeEqual(leftBuffer, rightBuffer);
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeNonEmptyString(value: string | null | undefined): string | undefined {
|
|
||||||
if (typeof value !== "string") {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
const trimmed = value.trim();
|
|
||||||
return trimmed.length > 0 ? trimmed : undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeIpAddress(value: string | null | undefined): string | undefined {
|
|
||||||
const normalized = normalizeNonEmptyString(value);
|
|
||||||
if (!normalized) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
return normalized.startsWith("::ffff:") ? normalized.slice("::ffff:".length) : normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
function inferDeviceType(userAgent: string | undefined): AuthClientMetadataDeviceType {
|
|
||||||
if (!userAgent) {
|
|
||||||
return "unknown";
|
|
||||||
}
|
|
||||||
|
|
||||||
const normalized = userAgent.toLowerCase();
|
|
||||||
if (/bot|crawler|spider|slurp|curl|wget/.test(normalized)) {
|
|
||||||
return "bot";
|
|
||||||
}
|
|
||||||
if (/ipad|tablet/.test(normalized)) {
|
|
||||||
return "tablet";
|
|
||||||
}
|
|
||||||
if (/iphone|android.+mobile|mobile/.test(normalized)) {
|
|
||||||
return "mobile";
|
|
||||||
}
|
|
||||||
return "desktop";
|
|
||||||
}
|
|
||||||
|
|
||||||
function inferBrowser(userAgent: string | undefined): string | undefined {
|
|
||||||
if (!userAgent) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
const normalized = userAgent.toLowerCase();
|
|
||||||
if (/edg\//.test(normalized)) return "Edge";
|
|
||||||
if (/opr\//.test(normalized)) return "Opera";
|
|
||||||
if (/firefox\//.test(normalized)) return "Firefox";
|
|
||||||
if (/electron\//.test(normalized)) return "Electron";
|
|
||||||
if (/chrome\//.test(normalized) || /crios\//.test(normalized)) return "Chrome";
|
|
||||||
if (/safari\//.test(normalized) && !/chrome\//.test(normalized)) return "Safari";
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
function inferOs(userAgent: string | undefined): string | undefined {
|
|
||||||
if (!userAgent) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
const normalized = userAgent.toLowerCase();
|
|
||||||
if (/iphone|ipad|ipod/.test(normalized)) return "iOS";
|
|
||||||
if (/android/.test(normalized)) return "Android";
|
|
||||||
if (/mac os x|macintosh/.test(normalized)) return "macOS";
|
|
||||||
if (/windows nt/.test(normalized)) return "Windows";
|
|
||||||
if (/linux/.test(normalized)) return "Linux";
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
function readRemoteAddressFromSource(source: unknown): string | undefined {
|
|
||||||
if (!source || typeof source !== "object") {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
const candidate = source as {
|
|
||||||
readonly remoteAddress?: string | null;
|
|
||||||
readonly socket?: {
|
|
||||||
readonly remoteAddress?: string | null;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
return normalizeIpAddress(candidate.socket?.remoteAddress ?? candidate.remoteAddress);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function deriveAuthClientMetadata(input: {
|
|
||||||
readonly request: HttpServerRequest.HttpServerRequest;
|
|
||||||
readonly label?: string;
|
|
||||||
}): AuthClientMetadata {
|
|
||||||
const userAgent = normalizeNonEmptyString(input.request.headers["user-agent"]);
|
|
||||||
const ipAddress = readRemoteAddressFromSource(input.request.source);
|
|
||||||
const os = inferOs(userAgent);
|
|
||||||
const browser = inferBrowser(userAgent);
|
|
||||||
return {
|
|
||||||
...(input.label ? { label: input.label } : {}),
|
|
||||||
...(ipAddress ? { ipAddress } : {}),
|
|
||||||
...(userAgent ? { userAgent } : {}),
|
|
||||||
deviceType: inferDeviceType(userAgent),
|
|
||||||
...(os ? { os } : {}),
|
|
||||||
...(browser ? { browser } : {}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import * as Effect from "effect/Effect";
|
|
||||||
import * as Layer from "effect/Layer";
|
|
||||||
import { Command } from "effect/unstable/cli";
|
|
||||||
|
|
||||||
import { NetService } from "@t3tools/shared/Net";
|
|
||||||
import { cli } from "./cli";
|
|
||||||
import { version } from "../package.json" with { type: "json" };
|
|
||||||
|
|
||||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
|
||||||
|
|
||||||
Command.run(cli, { version }).pipe(
|
|
||||||
Effect.scoped,
|
|
||||||
Effect.provide(CliRuntimeLayer),
|
|
||||||
NodeRuntime.runMain,
|
|
||||||
);
|
|
||||||
@@ -1,149 +0,0 @@
|
|||||||
import * as NFS from "node:fs";
|
|
||||||
import * as path from "node:path";
|
|
||||||
import { execFileSync, spawn } from "node:child_process";
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import { assert, it } from "@effect/vitest";
|
|
||||||
import { FileSystem, Schema } from "effect";
|
|
||||||
import * as Duration from "effect/Duration";
|
|
||||||
import * as Effect from "effect/Effect";
|
|
||||||
import * as Fiber from "effect/Fiber";
|
|
||||||
import { TestClock } from "effect/testing";
|
|
||||||
import { vi } from "vitest";
|
|
||||||
|
|
||||||
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap";
|
|
||||||
import { assertNone, assertSome } from "@effect/vitest/utils";
|
|
||||||
|
|
||||||
const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null }));
|
|
||||||
|
|
||||||
vi.mock("node:fs", async (importOriginal) => {
|
|
||||||
const actual = await importOriginal<typeof import("node:fs")>();
|
|
||||||
return {
|
|
||||||
...actual,
|
|
||||||
openSync: (...args: Parameters<typeof actual.openSync>) => {
|
|
||||||
const [filePath, flags] = args;
|
|
||||||
if (
|
|
||||||
typeof filePath === "string" &&
|
|
||||||
filePath === openSyncInterceptor.failPath &&
|
|
||||||
flags === "r"
|
|
||||||
) {
|
|
||||||
const error = new Error("no such device or address");
|
|
||||||
Object.assign(error, { code: "ENXIO" });
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
return (actual.openSync as (...a: typeof args) => number)(...args);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const TestEnvelopeSchema = Schema.Struct({ mode: Schema.String });
|
|
||||||
|
|
||||||
it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
|
|
||||||
it.effect("uses platform-specific fd paths", () =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
assert.equal(resolveFdPath(3, "linux"), "/proc/self/fd/3");
|
|
||||||
assert.equal(resolveFdPath(3, "darwin"), "/dev/fd/3");
|
|
||||||
assert.equal(resolveFdPath(3, "win32"), undefined);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("reads a bootstrap envelope from a provided fd", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fs = yield* FileSystem.FileSystem;
|
|
||||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
|
||||||
|
|
||||||
yield* fs.writeFileString(
|
|
||||||
filePath,
|
|
||||||
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
|
|
||||||
mode: "desktop",
|
|
||||||
})}\n`,
|
|
||||||
);
|
|
||||||
|
|
||||||
const fd = yield* Effect.acquireRelease(
|
|
||||||
Effect.sync(() => NFS.openSync(filePath, "r")),
|
|
||||||
(fd) => Effect.sync(() => NFS.closeSync(fd)),
|
|
||||||
);
|
|
||||||
|
|
||||||
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
|
|
||||||
assertSome(payload, {
|
|
||||||
mode: "desktop",
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("falls back to reading the inherited fd when path duplication fails", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fs = yield* FileSystem.FileSystem;
|
|
||||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
|
||||||
|
|
||||||
yield* fs.writeFileString(
|
|
||||||
filePath,
|
|
||||||
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
|
|
||||||
mode: "desktop",
|
|
||||||
})}\n`,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Open without acquireRelease: the direct-stream fallback uses autoClose: true,
|
|
||||||
// so the stream owns the fd lifecycle and closes it asynchronously on end.
|
|
||||||
// Attempting to also close it synchronously in a finalizer races with the
|
|
||||||
// stream's async close and produces an uncaught EBADF.
|
|
||||||
const fd = NFS.openSync(filePath, "r");
|
|
||||||
|
|
||||||
openSyncInterceptor.failPath = `/proc/self/fd/${fd}`;
|
|
||||||
try {
|
|
||||||
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
|
|
||||||
assertSome(payload, {
|
|
||||||
mode: "desktop",
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
openSyncInterceptor.failPath = null;
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("returns none when the fd is unavailable", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fd = NFS.openSync("/dev/null", "r");
|
|
||||||
NFS.closeSync(fd);
|
|
||||||
|
|
||||||
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
|
|
||||||
assertNone(payload);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("returns none when the bootstrap read times out before any value arrives", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fs = yield* FileSystem.FileSystem;
|
|
||||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-bootstrap-" });
|
|
||||||
const fifoPath = path.join(tempDir, "bootstrap.pipe");
|
|
||||||
|
|
||||||
yield* Effect.sync(() => execFileSync("mkfifo", [fifoPath]));
|
|
||||||
|
|
||||||
const _writer = yield* Effect.acquireRelease(
|
|
||||||
Effect.sync(() =>
|
|
||||||
spawn("sh", ["-c", 'exec 3>"$1"; sleep 60', "sh", fifoPath], {
|
|
||||||
stdio: ["ignore", "ignore", "ignore"],
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
(writer) =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
writer.kill("SIGKILL");
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const fd = yield* Effect.acquireRelease(
|
|
||||||
Effect.sync(() => NFS.openSync(fifoPath, "r")),
|
|
||||||
(fd) => Effect.sync(() => NFS.closeSync(fd)),
|
|
||||||
);
|
|
||||||
|
|
||||||
const fiber = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
|
|
||||||
timeoutMs: 100,
|
|
||||||
}).pipe(Effect.forkScoped);
|
|
||||||
|
|
||||||
yield* Effect.yieldNow;
|
|
||||||
yield* TestClock.adjust(Duration.millis(100));
|
|
||||||
|
|
||||||
const payload = yield* Fiber.join(fiber);
|
|
||||||
assertNone(payload);
|
|
||||||
}).pipe(Effect.provide(TestClock.layer())),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,173 +0,0 @@
|
|||||||
import * as NFS from "node:fs";
|
|
||||||
import * as Net from "node:net";
|
|
||||||
import * as readline from "node:readline";
|
|
||||||
import type { Readable } from "node:stream";
|
|
||||||
|
|
||||||
import { Data, Effect, Option, Predicate, Result, Schema } from "effect";
|
|
||||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
|
||||||
|
|
||||||
class BootstrapError extends Data.TaggedError("BootstrapError")<{
|
|
||||||
readonly message: string;
|
|
||||||
readonly cause?: unknown;
|
|
||||||
}> {}
|
|
||||||
|
|
||||||
export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function* <A, I>(
|
|
||||||
schema: Schema.Codec<A, I>,
|
|
||||||
fd: number,
|
|
||||||
options?: {
|
|
||||||
timeoutMs?: number;
|
|
||||||
},
|
|
||||||
): Effect.fn.Return<Option.Option<A>, BootstrapError> {
|
|
||||||
const fdReady = yield* isFdReady(fd);
|
|
||||||
if (!fdReady) return Option.none();
|
|
||||||
|
|
||||||
const stream = yield* makeBootstrapInputStream(fd);
|
|
||||||
|
|
||||||
const timeoutMs = options?.timeoutMs ?? 1000;
|
|
||||||
|
|
||||||
return yield* Effect.callback<Option.Option<A>, BootstrapError>((resume) => {
|
|
||||||
const input = readline.createInterface({
|
|
||||||
input: stream,
|
|
||||||
crlfDelay: Infinity,
|
|
||||||
});
|
|
||||||
|
|
||||||
const cleanup = () => {
|
|
||||||
stream.removeListener("error", handleError);
|
|
||||||
input.removeListener("line", handleLine);
|
|
||||||
input.removeListener("close", handleClose);
|
|
||||||
input.close();
|
|
||||||
stream.destroy();
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleError = (error: Error) => {
|
|
||||||
if (isUnavailableBootstrapFdError(error)) {
|
|
||||||
resume(Effect.succeedNone);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
resume(
|
|
||||||
Effect.fail(
|
|
||||||
new BootstrapError({
|
|
||||||
message: "Failed to read bootstrap envelope.",
|
|
||||||
cause: error,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleLine = (line: string) => {
|
|
||||||
const parsed = decodeJsonResult(schema)(line);
|
|
||||||
if (Result.isSuccess(parsed)) {
|
|
||||||
resume(Effect.succeedSome(parsed.success));
|
|
||||||
} else {
|
|
||||||
resume(
|
|
||||||
Effect.fail(
|
|
||||||
new BootstrapError({
|
|
||||||
message: "Failed to decode bootstrap envelope.",
|
|
||||||
cause: parsed.failure,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleClose = () => {
|
|
||||||
resume(Effect.succeedNone);
|
|
||||||
};
|
|
||||||
|
|
||||||
stream.once("error", handleError);
|
|
||||||
input.once("line", handleLine);
|
|
||||||
input.once("close", handleClose);
|
|
||||||
|
|
||||||
return Effect.sync(cleanup);
|
|
||||||
}).pipe(Effect.timeoutOption(timeoutMs), Effect.map(Option.flatten));
|
|
||||||
});
|
|
||||||
|
|
||||||
const isUnavailableBootstrapFdError = Predicate.compose(
|
|
||||||
Predicate.hasProperty("code"),
|
|
||||||
(_) => _.code === "EBADF" || _.code === "ENOENT",
|
|
||||||
);
|
|
||||||
|
|
||||||
const isFdReady = (fd: number) =>
|
|
||||||
Effect.try({
|
|
||||||
try: () => NFS.fstatSync(fd),
|
|
||||||
catch: (error) =>
|
|
||||||
new BootstrapError({
|
|
||||||
message: "Failed to stat bootstrap fd.",
|
|
||||||
cause: error,
|
|
||||||
}),
|
|
||||||
}).pipe(
|
|
||||||
Effect.as(true),
|
|
||||||
Effect.catchIf(
|
|
||||||
(error) => isUnavailableBootstrapFdError(error.cause),
|
|
||||||
() => Effect.succeed(false),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const makeBootstrapInputStream = (fd: number) =>
|
|
||||||
Effect.try<Readable, BootstrapError>({
|
|
||||||
try: () => {
|
|
||||||
const fdPath = resolveFdPath(fd);
|
|
||||||
if (fdPath === undefined) {
|
|
||||||
return makeDirectBootstrapStream(fd);
|
|
||||||
}
|
|
||||||
|
|
||||||
let streamFd: number | undefined;
|
|
||||||
try {
|
|
||||||
streamFd = NFS.openSync(fdPath, "r");
|
|
||||||
return NFS.createReadStream("", {
|
|
||||||
fd: streamFd,
|
|
||||||
encoding: "utf8",
|
|
||||||
autoClose: true,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
if (isBootstrapFdPathDuplicationError(error)) {
|
|
||||||
if (streamFd !== undefined) {
|
|
||||||
NFS.closeSync(streamFd);
|
|
||||||
}
|
|
||||||
return makeDirectBootstrapStream(fd);
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
catch: (error) =>
|
|
||||||
new BootstrapError({
|
|
||||||
message: "Failed to duplicate bootstrap fd.",
|
|
||||||
cause: error,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const makeDirectBootstrapStream = (fd: number): Readable => {
|
|
||||||
try {
|
|
||||||
return NFS.createReadStream("", {
|
|
||||||
fd,
|
|
||||||
encoding: "utf8",
|
|
||||||
autoClose: true,
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
const stream = new Net.Socket({
|
|
||||||
fd,
|
|
||||||
readable: true,
|
|
||||||
writable: false,
|
|
||||||
});
|
|
||||||
stream.setEncoding("utf8");
|
|
||||||
return stream;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const isBootstrapFdPathDuplicationError = Predicate.compose(
|
|
||||||
Predicate.hasProperty("code"),
|
|
||||||
(_) => _.code === "ENXIO" || _.code === "EINVAL" || _.code === "EPERM",
|
|
||||||
);
|
|
||||||
|
|
||||||
export function resolveFdPath(
|
|
||||||
fd: number,
|
|
||||||
platform: NodeJS.Platform = process.platform,
|
|
||||||
): string | undefined {
|
|
||||||
if (platform === "linux") {
|
|
||||||
return `/proc/self/fd/${fd}`;
|
|
||||||
}
|
|
||||||
if (platform === "win32") {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
return `/dev/fd/${fd}`;
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Schema } from "effect";
|
import { Schema } from "effect";
|
||||||
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
|
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
|
||||||
import { GitCommandError } from "@t3tools/contracts";
|
import { GitCommandError } from "../git/Errors.ts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* CheckpointUnavailableError - Expected checkpoint does not exist.
|
* CheckpointUnavailableError - Expected checkpoint does not exist.
|
||||||
|
|||||||
@@ -1,38 +1,79 @@
|
|||||||
import { CheckpointRef, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
import {
|
||||||
import { Effect, Layer, Option } from "effect";
|
CheckpointRef,
|
||||||
|
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
|
ProjectId,
|
||||||
|
ThreadId,
|
||||||
|
TurnId,
|
||||||
|
type OrchestrationReadModel,
|
||||||
|
} from "@t3tools/contracts";
|
||||||
|
import { Effect, Layer } from "effect";
|
||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import {
|
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||||
ProjectionSnapshotQuery,
|
|
||||||
type ProjectionThreadCheckpointContext,
|
|
||||||
} from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
|
||||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||||
import { CheckpointDiffQueryLive } from "./CheckpointDiffQuery.ts";
|
import { CheckpointDiffQueryLive } from "./CheckpointDiffQuery.ts";
|
||||||
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
||||||
import { CheckpointDiffQuery } from "../Services/CheckpointDiffQuery.ts";
|
import { CheckpointDiffQuery } from "../Services/CheckpointDiffQuery.ts";
|
||||||
|
|
||||||
function makeThreadCheckpointContext(input: {
|
function makeSnapshot(input: {
|
||||||
readonly projectId: ProjectId;
|
readonly projectId: ProjectId;
|
||||||
readonly threadId: ThreadId;
|
readonly threadId: ThreadId;
|
||||||
readonly workspaceRoot: string;
|
readonly workspaceRoot: string;
|
||||||
readonly worktreePath: string | null;
|
readonly worktreePath: string | null;
|
||||||
readonly checkpointTurnCount: number;
|
readonly checkpointTurnCount: number;
|
||||||
readonly checkpointRef: CheckpointRef;
|
readonly checkpointRef: CheckpointRef;
|
||||||
}): ProjectionThreadCheckpointContext {
|
}): OrchestrationReadModel {
|
||||||
return {
|
return {
|
||||||
threadId: input.threadId,
|
snapshotSequence: 0,
|
||||||
projectId: input.projectId,
|
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||||
workspaceRoot: input.workspaceRoot,
|
projects: [
|
||||||
worktreePath: input.worktreePath,
|
|
||||||
checkpoints: [
|
|
||||||
{
|
{
|
||||||
turnId: TurnId.makeUnsafe("turn-1"),
|
id: input.projectId,
|
||||||
checkpointTurnCount: input.checkpointTurnCount,
|
title: "Project",
|
||||||
checkpointRef: input.checkpointRef,
|
workspaceRoot: input.workspaceRoot,
|
||||||
status: "ready",
|
defaultModel: null,
|
||||||
files: [],
|
scripts: [],
|
||||||
assistantMessageId: null,
|
createdAt: "2026-01-01T00:00:00.000Z",
|
||||||
completedAt: "2026-01-01T00:00:00.000Z",
|
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||||
|
deletedAt: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
threads: [
|
||||||
|
{
|
||||||
|
id: input.threadId,
|
||||||
|
projectId: input.projectId,
|
||||||
|
title: "Thread",
|
||||||
|
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",
|
||||||
|
deletedAt: null,
|
||||||
|
messages: [],
|
||||||
|
activities: [],
|
||||||
|
proposedPlans: [],
|
||||||
|
checkpoints: [
|
||||||
|
{
|
||||||
|
turnId: TurnId.makeUnsafe("turn-1"),
|
||||||
|
checkpointTurnCount: input.checkpointTurnCount,
|
||||||
|
checkpointRef: input.checkpointRef,
|
||||||
|
status: "ready",
|
||||||
|
files: [],
|
||||||
|
assistantMessageId: null,
|
||||||
|
completedAt: "2026-01-01T00:00:00.000Z",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
session: null,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
@@ -50,7 +91,7 @@ describe("CheckpointDiffQueryLive", () => {
|
|||||||
readonly cwd: string;
|
readonly cwd: string;
|
||||||
}> = [];
|
}> = [];
|
||||||
|
|
||||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
const snapshot = makeSnapshot({
|
||||||
projectId,
|
projectId,
|
||||||
threadId,
|
threadId,
|
||||||
workspaceRoot: "/tmp/workspace",
|
workspaceRoot: "/tmp/workspace",
|
||||||
@@ -80,12 +121,7 @@ describe("CheckpointDiffQueryLive", () => {
|
|||||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||||
Layer.provideMerge(
|
Layer.provideMerge(
|
||||||
Layer.succeed(ProjectionSnapshotQuery, {
|
Layer.succeed(ProjectionSnapshotQuery, {
|
||||||
getSnapshot: () =>
|
getSnapshot: () => Effect.succeed(snapshot),
|
||||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
|
||||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
|
||||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
|
||||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
|
||||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -135,11 +171,12 @@ describe("CheckpointDiffQueryLive", () => {
|
|||||||
Layer.provideMerge(
|
Layer.provideMerge(
|
||||||
Layer.succeed(ProjectionSnapshotQuery, {
|
Layer.succeed(ProjectionSnapshotQuery, {
|
||||||
getSnapshot: () =>
|
getSnapshot: () =>
|
||||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
Effect.succeed({
|
||||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
snapshotSequence: 0,
|
||||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
projects: [],
|
||||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
threads: [],
|
||||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||||
|
} satisfies OrchestrationReadModel),
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -4,11 +4,11 @@ import {
|
|||||||
type OrchestrationGetFullThreadDiffResult,
|
type OrchestrationGetFullThreadDiffResult,
|
||||||
type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
|
type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { Effect, Layer, Option, Schema } from "effect";
|
import { Effect, Layer, Schema } from "effect";
|
||||||
|
|
||||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||||
import { CheckpointInvariantError, CheckpointUnavailableError } from "../Errors.ts";
|
import { CheckpointInvariantError, CheckpointUnavailableError } from "../Errors.ts";
|
||||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
import { checkpointRefForThreadTurn, resolveThreadWorkspaceCwd } from "../Utils.ts";
|
||||||
import { CheckpointStore } from "../Services/CheckpointStore.ts";
|
import { CheckpointStore } from "../Services/CheckpointStore.ts";
|
||||||
import {
|
import {
|
||||||
CheckpointDiffQuery,
|
CheckpointDiffQuery,
|
||||||
@@ -21,8 +21,8 @@ const make = Effect.gen(function* () {
|
|||||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||||
const checkpointStore = yield* CheckpointStore;
|
const checkpointStore = yield* CheckpointStore;
|
||||||
|
|
||||||
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
|
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = (input) =>
|
||||||
function* (input) {
|
Effect.gen(function* () {
|
||||||
const operation = "CheckpointDiffQuery.getTurnDiff";
|
const operation = "CheckpointDiffQuery.getTurnDiff";
|
||||||
|
|
||||||
if (input.fromTurnCount === input.toTurnCount) {
|
if (input.fromTurnCount === input.toTurnCount) {
|
||||||
@@ -41,17 +41,16 @@ const make = Effect.gen(function* () {
|
|||||||
return emptyDiff;
|
return emptyDiff;
|
||||||
}
|
}
|
||||||
|
|
||||||
const threadContext = yield* projectionSnapshotQuery.getThreadCheckpointContext(
|
const snapshot = yield* projectionSnapshotQuery.getSnapshot();
|
||||||
input.threadId,
|
const thread = snapshot.threads.find((entry) => entry.id === input.threadId);
|
||||||
);
|
if (!thread) {
|
||||||
if (Option.isNone(threadContext)) {
|
|
||||||
return yield* new CheckpointInvariantError({
|
return yield* new CheckpointInvariantError({
|
||||||
operation,
|
operation,
|
||||||
detail: `Thread '${input.threadId}' not found.`,
|
detail: `Thread '${input.threadId}' not found.`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const maxTurnCount = threadContext.value.checkpoints.reduce(
|
const maxTurnCount = thread.checkpoints.reduce(
|
||||||
(max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),
|
(max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),
|
||||||
0,
|
0,
|
||||||
);
|
);
|
||||||
@@ -63,7 +62,10 @@ const make = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
|
const workspaceCwd = resolveThreadWorkspaceCwd({
|
||||||
|
thread,
|
||||||
|
projects: snapshot.projects,
|
||||||
|
});
|
||||||
if (!workspaceCwd) {
|
if (!workspaceCwd) {
|
||||||
return yield* new CheckpointInvariantError({
|
return yield* new CheckpointInvariantError({
|
||||||
operation,
|
operation,
|
||||||
@@ -74,7 +76,7 @@ const make = Effect.gen(function* () {
|
|||||||
const fromCheckpointRef =
|
const fromCheckpointRef =
|
||||||
input.fromTurnCount === 0
|
input.fromTurnCount === 0
|
||||||
? checkpointRefForThreadTurn(input.threadId, 0)
|
? checkpointRefForThreadTurn(input.threadId, 0)
|
||||||
: threadContext.value.checkpoints.find(
|
: thread.checkpoints.find(
|
||||||
(checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,
|
(checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,
|
||||||
)?.checkpointRef;
|
)?.checkpointRef;
|
||||||
if (!fromCheckpointRef) {
|
if (!fromCheckpointRef) {
|
||||||
@@ -85,7 +87,7 @@ const make = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const toCheckpointRef = threadContext.value.checkpoints.find(
|
const toCheckpointRef = thread.checkpoints.find(
|
||||||
(checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,
|
(checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,
|
||||||
)?.checkpointRef;
|
)?.checkpointRef;
|
||||||
if (!toCheckpointRef) {
|
if (!toCheckpointRef) {
|
||||||
@@ -147,8 +149,7 @@ const make = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return turnDiff;
|
return turnDiff;
|
||||||
},
|
});
|
||||||
);
|
|
||||||
|
|
||||||
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
|
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
|
||||||
input: OrchestrationGetFullThreadDiffInput,
|
input: OrchestrationGetFullThreadDiffInput,
|
||||||
|
|||||||
@@ -1,122 +0,0 @@
|
|||||||
import path from "node:path";
|
|
||||||
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import { it } from "@effect/vitest";
|
|
||||||
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
|
||||||
import { describe, expect } from "vitest";
|
|
||||||
|
|
||||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
|
||||||
import { CheckpointStoreLive } from "./CheckpointStore.ts";
|
|
||||||
import { CheckpointStore } from "../Services/CheckpointStore.ts";
|
|
||||||
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
|
||||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
|
||||||
import { GitCommandError } from "@t3tools/contracts";
|
|
||||||
import { ServerConfig } from "../../config.ts";
|
|
||||||
import { ThreadId } from "@t3tools/contracts";
|
|
||||||
|
|
||||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
|
||||||
prefix: "t3-checkpoint-store-test-",
|
|
||||||
});
|
|
||||||
const GitCoreTestLayer = GitCoreLive.pipe(
|
|
||||||
Layer.provide(ServerConfigLayer),
|
|
||||||
Layer.provide(NodeServices.layer),
|
|
||||||
);
|
|
||||||
const CheckpointStoreTestLayer = CheckpointStoreLive.pipe(
|
|
||||||
Layer.provide(GitCoreTestLayer),
|
|
||||||
Layer.provide(NodeServices.layer),
|
|
||||||
);
|
|
||||||
const TestLayer = Layer.mergeAll(NodeServices.layer, GitCoreTestLayer, CheckpointStoreTestLayer);
|
|
||||||
|
|
||||||
function makeTmpDir(
|
|
||||||
prefix = "checkpoint-store-test-",
|
|
||||||
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> {
|
|
||||||
return Effect.gen(function* () {
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
|
||||||
return yield* fileSystem.makeTempDirectoryScoped({ prefix });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function writeTextFile(
|
|
||||||
filePath: string,
|
|
||||||
contents: string,
|
|
||||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
|
||||||
return Effect.gen(function* () {
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
|
||||||
yield* fileSystem.writeFileString(filePath, contents);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function git(
|
|
||||||
cwd: string,
|
|
||||||
args: ReadonlyArray<string>,
|
|
||||||
): Effect.Effect<string, GitCommandError, GitCore> {
|
|
||||||
return Effect.gen(function* () {
|
|
||||||
const gitCore = yield* GitCore;
|
|
||||||
const result = yield* gitCore.execute({
|
|
||||||
operation: "CheckpointStore.test.git",
|
|
||||||
cwd,
|
|
||||||
args,
|
|
||||||
timeoutMs: 10_000,
|
|
||||||
});
|
|
||||||
return result.stdout.trim();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function initRepoWithCommit(
|
|
||||||
cwd: string,
|
|
||||||
): Effect.Effect<
|
|
||||||
void,
|
|
||||||
GitCommandError | PlatformError.PlatformError,
|
|
||||||
GitCore | FileSystem.FileSystem
|
|
||||||
> {
|
|
||||||
return Effect.gen(function* () {
|
|
||||||
const core = yield* GitCore;
|
|
||||||
yield* core.initRepo({ cwd });
|
|
||||||
yield* git(cwd, ["config", "user.email", "[email protected]"]);
|
|
||||||
yield* git(cwd, ["config", "user.name", "Test"]);
|
|
||||||
yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
|
|
||||||
yield* git(cwd, ["add", "."]);
|
|
||||||
yield* git(cwd, ["commit", "-m", "initial commit"]);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildLargeText(lineCount = 5_000): string {
|
|
||||||
return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`)
|
|
||||||
.join("\n")
|
|
||||||
.concat("\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
it.layer(TestLayer)("CheckpointStoreLive", (it) => {
|
|
||||||
describe("diffCheckpoints", () => {
|
|
||||||
it.effect("returns full oversized checkpoint diffs without truncation", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const tmp = yield* makeTmpDir();
|
|
||||||
yield* initRepoWithCommit(tmp);
|
|
||||||
const checkpointStore = yield* CheckpointStore;
|
|
||||||
const threadId = ThreadId.makeUnsafe("thread-checkpoint-store");
|
|
||||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
|
||||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
|
||||||
|
|
||||||
yield* checkpointStore.captureCheckpoint({
|
|
||||||
cwd: tmp,
|
|
||||||
checkpointRef: fromCheckpointRef,
|
|
||||||
});
|
|
||||||
yield* writeTextFile(path.join(tmp, "README.md"), buildLargeText());
|
|
||||||
yield* checkpointStore.captureCheckpoint({
|
|
||||||
cwd: tmp,
|
|
||||||
checkpointRef: toCheckpointRef,
|
|
||||||
});
|
|
||||||
|
|
||||||
const diff = yield* checkpointStore.diffCheckpoints({
|
|
||||||
cwd: tmp,
|
|
||||||
fromCheckpointRef,
|
|
||||||
toCheckpointRef,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(diff).toContain("diff --git");
|
|
||||||
expect(diff).not.toContain("[truncated]");
|
|
||||||
expect(diff).toContain("+line 04999");
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -14,15 +14,16 @@ import { randomUUID } from "node:crypto";
|
|||||||
import { Effect, Layer, FileSystem, Path } from "effect";
|
import { Effect, Layer, FileSystem, Path } from "effect";
|
||||||
|
|
||||||
import { CheckpointInvariantError } from "../Errors.ts";
|
import { CheckpointInvariantError } from "../Errors.ts";
|
||||||
import { GitCommandError } from "@t3tools/contracts";
|
import { GitCommandError } from "../../git/Errors.ts";
|
||||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
import { GitServiceLive } from "../../git/Layers/GitService.ts";
|
||||||
|
import { GitService } from "../../git/Services/GitService.ts";
|
||||||
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
||||||
import { CheckpointRef } from "@t3tools/contracts";
|
import { CheckpointRef } from "@t3tools/contracts";
|
||||||
|
|
||||||
const makeCheckpointStore = Effect.gen(function* () {
|
const makeCheckpointStore = Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
const git = yield* GitCore;
|
const git = yield* GitService;
|
||||||
|
|
||||||
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
|
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
|
||||||
git
|
git
|
||||||
@@ -86,140 +87,139 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
Effect.catch(() => Effect.succeed(false)),
|
Effect.catch(() => Effect.succeed(false)),
|
||||||
);
|
);
|
||||||
|
|
||||||
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
|
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = (input) =>
|
||||||
"captureCheckpoint",
|
Effect.gen(function* () {
|
||||||
)(function* (input) {
|
const operation = "CheckpointStore.captureCheckpoint";
|
||||||
const operation = "CheckpointStore.captureCheckpoint";
|
|
||||||
|
|
||||||
yield* Effect.acquireUseRelease(
|
yield* Effect.acquireUseRelease(
|
||||||
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
|
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
|
||||||
Effect.fn("captureCheckpoint.withTempDirectory")(function* (tempDir) {
|
(tempDir) =>
|
||||||
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
|
Effect.gen(function* () {
|
||||||
const commitEnv: NodeJS.ProcessEnv = {
|
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
|
||||||
...process.env,
|
const commitEnv: NodeJS.ProcessEnv = {
|
||||||
GIT_INDEX_FILE: tempIndexPath,
|
...process.env,
|
||||||
GIT_AUTHOR_NAME: "T3 Code",
|
GIT_INDEX_FILE: tempIndexPath,
|
||||||
GIT_AUTHOR_EMAIL: "[email protected]",
|
GIT_AUTHOR_NAME: "T3 Code",
|
||||||
GIT_COMMITTER_NAME: "T3 Code",
|
GIT_AUTHOR_EMAIL: "[email protected]",
|
||||||
GIT_COMMITTER_EMAIL: "[email protected]",
|
GIT_COMMITTER_NAME: "T3 Code",
|
||||||
};
|
GIT_COMMITTER_EMAIL: "[email protected]",
|
||||||
|
};
|
||||||
|
|
||||||
const headExists = yield* hasHeadCommit(input.cwd);
|
const headExists = yield* hasHeadCommit(input.cwd);
|
||||||
if (headExists) {
|
if (headExists) {
|
||||||
yield* git.execute({
|
yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["read-tree", "HEAD"],
|
args: ["read-tree", "HEAD"],
|
||||||
env: commitEnv,
|
env: commitEnv,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
yield* git.execute({
|
yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["add", "-A", "--", "."],
|
args: ["add", "-A", "--", "."],
|
||||||
env: commitEnv,
|
env: commitEnv,
|
||||||
});
|
});
|
||||||
|
|
||||||
const writeTreeResult = yield* git.execute({
|
const writeTreeResult = yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["write-tree"],
|
args: ["write-tree"],
|
||||||
env: commitEnv,
|
env: commitEnv,
|
||||||
});
|
});
|
||||||
const treeOid = writeTreeResult.stdout.trim();
|
const treeOid = writeTreeResult.stdout.trim();
|
||||||
if (treeOid.length === 0) {
|
if (treeOid.length === 0) {
|
||||||
return yield* new GitCommandError({
|
return yield* new GitCommandError({
|
||||||
operation,
|
operation,
|
||||||
command: "git write-tree",
|
command: "git write-tree",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
detail: "git write-tree returned an empty tree oid.",
|
detail: "git write-tree returned an empty tree oid.",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const message = `t3 checkpoint ref=${input.checkpointRef}`;
|
const message = `t3 checkpoint ref=${input.checkpointRef}`;
|
||||||
const commitTreeResult = yield* git.execute({
|
const commitTreeResult = yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["commit-tree", treeOid, "-m", message],
|
args: ["commit-tree", treeOid, "-m", message],
|
||||||
env: commitEnv,
|
env: commitEnv,
|
||||||
});
|
});
|
||||||
const commitOid = commitTreeResult.stdout.trim();
|
const commitOid = commitTreeResult.stdout.trim();
|
||||||
if (commitOid.length === 0) {
|
if (commitOid.length === 0) {
|
||||||
return yield* new GitCommandError({
|
return yield* new GitCommandError({
|
||||||
operation,
|
operation,
|
||||||
command: "git commit-tree",
|
command: "git commit-tree",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
detail: "git commit-tree returned an empty commit oid.",
|
detail: "git commit-tree returned an empty commit oid.",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
yield* git.execute({
|
yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["update-ref", input.checkpointRef, commitOid],
|
args: ["update-ref", input.checkpointRef, commitOid],
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
(tempDir) => fs.remove(tempDir, { recursive: true }),
|
(tempDir) => fs.remove(tempDir, { recursive: true }),
|
||||||
).pipe(
|
).pipe(
|
||||||
Effect.catchTags({
|
Effect.catchTags({
|
||||||
PlatformError: (error) =>
|
PlatformError: (error) =>
|
||||||
Effect.fail(
|
Effect.fail(
|
||||||
new CheckpointInvariantError({
|
new CheckpointInvariantError({
|
||||||
operation: "CheckpointStore.captureCheckpoint",
|
operation: "CheckpointStore.captureCheckpoint",
|
||||||
detail: "Failed to capture checkpoint.",
|
detail: "Failed to capture checkpoint.",
|
||||||
cause: error,
|
cause: error,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
|
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
|
||||||
resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
|
resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
|
||||||
Effect.map((commit) => commit !== null),
|
Effect.map((commit) => commit !== null),
|
||||||
);
|
);
|
||||||
|
|
||||||
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = Effect.fn(
|
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = (input) =>
|
||||||
"restoreCheckpoint",
|
Effect.gen(function* () {
|
||||||
)(function* (input) {
|
const operation = "CheckpointStore.restoreCheckpoint";
|
||||||
const operation = "CheckpointStore.restoreCheckpoint";
|
|
||||||
|
|
||||||
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
|
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
|
||||||
|
|
||||||
if (!commitOid && input.fallbackToHead === true) {
|
if (!commitOid && input.fallbackToHead === true) {
|
||||||
commitOid = yield* resolveHeadCommit(input.cwd);
|
commitOid = yield* resolveHeadCommit(input.cwd);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!commitOid) {
|
if (!commitOid) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
yield* git.execute({
|
|
||||||
operation,
|
|
||||||
cwd: input.cwd,
|
|
||||||
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
|
|
||||||
});
|
|
||||||
yield* git.execute({
|
|
||||||
operation,
|
|
||||||
cwd: input.cwd,
|
|
||||||
args: ["clean", "-fd", "--", "."],
|
|
||||||
});
|
|
||||||
|
|
||||||
const headExists = yield* hasHeadCommit(input.cwd);
|
|
||||||
if (headExists) {
|
|
||||||
yield* git.execute({
|
yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["reset", "--quiet", "--", "."],
|
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
|
||||||
|
});
|
||||||
|
yield* git.execute({
|
||||||
|
operation,
|
||||||
|
cwd: input.cwd,
|
||||||
|
args: ["clean", "-fd", "--", "."],
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
const headExists = yield* hasHeadCommit(input.cwd);
|
||||||
});
|
if (headExists) {
|
||||||
|
yield* git.execute({
|
||||||
|
operation,
|
||||||
|
cwd: input.cwd,
|
||||||
|
args: ["reset", "--quiet", "--", "."],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = Effect.fn("diffCheckpoints")(
|
return true;
|
||||||
function* (input) {
|
});
|
||||||
|
|
||||||
|
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = (input) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
const operation = "CheckpointStore.diffCheckpoints";
|
const operation = "CheckpointStore.diffCheckpoints";
|
||||||
|
|
||||||
let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
|
let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
|
||||||
@@ -248,26 +248,24 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return result.stdout;
|
return result.stdout;
|
||||||
},
|
});
|
||||||
);
|
|
||||||
|
|
||||||
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = Effect.fn(
|
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = (input) =>
|
||||||
"deleteCheckpointRefs",
|
Effect.gen(function* () {
|
||||||
)(function* (input) {
|
const operation = "CheckpointStore.deleteCheckpointRefs";
|
||||||
const operation = "CheckpointStore.deleteCheckpointRefs";
|
|
||||||
|
|
||||||
yield* Effect.forEach(
|
yield* Effect.forEach(
|
||||||
input.checkpointRefs,
|
input.checkpointRefs,
|
||||||
(checkpointRef) =>
|
(checkpointRef) =>
|
||||||
git.execute({
|
git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["update-ref", "-d", checkpointRef],
|
args: ["update-ref", "-d", checkpointRef],
|
||||||
allowNonZeroExit: true,
|
allowNonZeroExit: true,
|
||||||
}),
|
}),
|
||||||
{ discard: true },
|
{ discard: true },
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
isGitRepository,
|
isGitRepository,
|
||||||
@@ -279,4 +277,6 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
} satisfies CheckpointStoreShape;
|
} satisfies CheckpointStoreShape;
|
||||||
});
|
});
|
||||||
|
|
||||||
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore);
|
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore).pipe(
|
||||||
|
Layer.provideMerge(GitServiceLive),
|
||||||
|
);
|
||||||
@@ -1,465 +0,0 @@
|
|||||||
import os from "node:os";
|
|
||||||
|
|
||||||
import { assert, expect, it } from "@effect/vitest";
|
|
||||||
import { ConfigProvider, Effect, FileSystem, Layer, Option, Path } from "effect";
|
|
||||||
|
|
||||||
import { NetService } from "@t3tools/shared/Net";
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import { deriveServerPaths } from "./config";
|
|
||||||
import { resolveServerConfig } from "./cli";
|
|
||||||
|
|
||||||
it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
|
||||||
const defaultObservabilityConfig = {
|
|
||||||
traceMinLevel: "Info",
|
|
||||||
traceTimingEnabled: true,
|
|
||||||
traceBatchWindowMs: 200,
|
|
||||||
traceMaxBytes: 10 * 1024 * 1024,
|
|
||||||
traceMaxFiles: 10,
|
|
||||||
otlpTracesUrl: undefined,
|
|
||||||
otlpMetricsUrl: undefined,
|
|
||||||
otlpExportIntervalMs: 10_000,
|
|
||||||
otlpServiceName: "t3-server",
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
const openBootstrapFd = Effect.fn(function* (payload: Record<string, unknown>) {
|
|
||||||
const fs = yield* FileSystem.FileSystem;
|
|
||||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
|
||||||
yield* fs.writeFileString(filePath, `${JSON.stringify(payload)}\n`);
|
|
||||||
const { fd } = yield* fs.open(filePath, { flag: "r" });
|
|
||||||
return fd;
|
|
||||||
});
|
|
||||||
|
|
||||||
it.effect("falls back to effect/config values when flags are omitted", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const { join } = yield* Path.Path;
|
|
||||||
const baseDir = join(os.tmpdir(), "t3-cli-config-env-base");
|
|
||||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
|
|
||||||
const resolved = yield* resolveServerConfig(
|
|
||||||
{
|
|
||||||
mode: Option.none(),
|
|
||||||
port: Option.none(),
|
|
||||||
host: Option.none(),
|
|
||||||
baseDir: Option.none(),
|
|
||||||
cwd: Option.none(),
|
|
||||||
devUrl: Option.none(),
|
|
||||||
noBrowser: Option.none(),
|
|
||||||
bootstrapFd: Option.none(),
|
|
||||||
autoBootstrapProjectFromCwd: Option.none(),
|
|
||||||
logWebSocketEvents: Option.none(),
|
|
||||||
},
|
|
||||||
Option.none(),
|
|
||||||
).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
Layer.mergeAll(
|
|
||||||
ConfigProvider.layer(
|
|
||||||
ConfigProvider.fromEnv({
|
|
||||||
env: {
|
|
||||||
T3CODE_LOG_LEVEL: "Warn",
|
|
||||||
T3CODE_MODE: "desktop",
|
|
||||||
T3CODE_PORT: "4001",
|
|
||||||
T3CODE_HOST: "0.0.0.0",
|
|
||||||
T3CODE_HOME: baseDir,
|
|
||||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
|
||||||
T3CODE_NO_BROWSER: "true",
|
|
||||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
|
|
||||||
T3CODE_LOG_WS_EVENTS: "true",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
NetService.layer,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(resolved).toEqual({
|
|
||||||
logLevel: "Warn",
|
|
||||||
...defaultObservabilityConfig,
|
|
||||||
mode: "desktop",
|
|
||||||
port: 4001,
|
|
||||||
cwd: process.cwd(),
|
|
||||||
baseDir,
|
|
||||||
...derivedPaths,
|
|
||||||
host: "0.0.0.0",
|
|
||||||
staticDir: undefined,
|
|
||||||
devUrl: new URL("http://127.0.0.1:5173"),
|
|
||||||
noBrowser: true,
|
|
||||||
startupPresentation: "browser",
|
|
||||||
desktopBootstrapToken: undefined,
|
|
||||||
autoBootstrapProjectFromCwd: false,
|
|
||||||
logWebSocketEvents: true,
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("uses CLI flags when provided", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const { join } = yield* Path.Path;
|
|
||||||
const baseDir = join(os.tmpdir(), "t3-cli-config-flags-base");
|
|
||||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
|
||||||
const resolved = yield* resolveServerConfig(
|
|
||||||
{
|
|
||||||
mode: Option.some("web"),
|
|
||||||
port: Option.some(8788),
|
|
||||||
host: Option.some("127.0.0.1"),
|
|
||||||
baseDir: Option.some(baseDir),
|
|
||||||
cwd: Option.none(),
|
|
||||||
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
|
|
||||||
noBrowser: Option.some(true),
|
|
||||||
bootstrapFd: Option.none(),
|
|
||||||
autoBootstrapProjectFromCwd: Option.some(true),
|
|
||||||
logWebSocketEvents: Option.some(true),
|
|
||||||
},
|
|
||||||
Option.some("Debug"),
|
|
||||||
).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
Layer.mergeAll(
|
|
||||||
ConfigProvider.layer(
|
|
||||||
ConfigProvider.fromEnv({
|
|
||||||
env: {
|
|
||||||
T3CODE_LOG_LEVEL: "Warn",
|
|
||||||
T3CODE_MODE: "desktop",
|
|
||||||
T3CODE_PORT: "4001",
|
|
||||||
T3CODE_HOST: "0.0.0.0",
|
|
||||||
T3CODE_HOME: join(os.tmpdir(), "ignored-base"),
|
|
||||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
|
||||||
T3CODE_NO_BROWSER: "false",
|
|
||||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
|
|
||||||
T3CODE_LOG_WS_EVENTS: "false",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
NetService.layer,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(resolved).toEqual({
|
|
||||||
logLevel: "Debug",
|
|
||||||
...defaultObservabilityConfig,
|
|
||||||
mode: "web",
|
|
||||||
port: 8788,
|
|
||||||
cwd: process.cwd(),
|
|
||||||
baseDir,
|
|
||||||
...derivedPaths,
|
|
||||||
host: "127.0.0.1",
|
|
||||||
staticDir: undefined,
|
|
||||||
devUrl: new URL("http://127.0.0.1:4173"),
|
|
||||||
noBrowser: true,
|
|
||||||
startupPresentation: "browser",
|
|
||||||
desktopBootstrapToken: undefined,
|
|
||||||
autoBootstrapProjectFromCwd: true,
|
|
||||||
logWebSocketEvents: true,
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("uses bootstrap envelope values as fallbacks when flags and env are absent", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const { join } = yield* Path.Path;
|
|
||||||
const baseDir = "/tmp/t3-bootstrap-home";
|
|
||||||
const fd = yield* openBootstrapFd({
|
|
||||||
mode: "desktop",
|
|
||||||
port: 4888,
|
|
||||||
host: "127.0.0.2",
|
|
||||||
t3Home: baseDir,
|
|
||||||
devUrl: "http://127.0.0.1:5173",
|
|
||||||
noBrowser: true,
|
|
||||||
autoBootstrapProjectFromCwd: false,
|
|
||||||
logWebSocketEvents: true,
|
|
||||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
|
||||||
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
|
||||||
});
|
|
||||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
|
|
||||||
|
|
||||||
const resolved = yield* resolveServerConfig(
|
|
||||||
{
|
|
||||||
mode: Option.none(),
|
|
||||||
port: Option.none(),
|
|
||||||
host: Option.none(),
|
|
||||||
baseDir: Option.none(),
|
|
||||||
cwd: Option.none(),
|
|
||||||
devUrl: Option.none(),
|
|
||||||
noBrowser: Option.none(),
|
|
||||||
bootstrapFd: Option.none(),
|
|
||||||
autoBootstrapProjectFromCwd: Option.none(),
|
|
||||||
logWebSocketEvents: Option.none(),
|
|
||||||
},
|
|
||||||
Option.none(),
|
|
||||||
).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
Layer.mergeAll(
|
|
||||||
ConfigProvider.layer(
|
|
||||||
ConfigProvider.fromEnv({
|
|
||||||
env: {
|
|
||||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
NetService.layer,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(resolved).toEqual({
|
|
||||||
logLevel: "Info",
|
|
||||||
...defaultObservabilityConfig,
|
|
||||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
|
||||||
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
|
||||||
mode: "desktop",
|
|
||||||
port: 4888,
|
|
||||||
cwd: process.cwd(),
|
|
||||||
baseDir,
|
|
||||||
...derivedPaths,
|
|
||||||
host: "127.0.0.2",
|
|
||||||
staticDir: undefined,
|
|
||||||
devUrl: new URL("http://127.0.0.1:5173"),
|
|
||||||
noBrowser: true,
|
|
||||||
startupPresentation: "browser",
|
|
||||||
desktopBootstrapToken: undefined,
|
|
||||||
autoBootstrapProjectFromCwd: false,
|
|
||||||
logWebSocketEvents: true,
|
|
||||||
});
|
|
||||||
assert.equal(join(baseDir, "dev"), resolved.stateDir);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("creates derived runtime directories during config resolution", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fs = yield* FileSystem.FileSystem;
|
|
||||||
const path = yield* Path.Path;
|
|
||||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-dirs-" });
|
|
||||||
const customCwd = path.join(baseDir, "nested", "project");
|
|
||||||
|
|
||||||
const resolved = yield* resolveServerConfig(
|
|
||||||
{
|
|
||||||
mode: Option.some("desktop"),
|
|
||||||
port: Option.some(4888),
|
|
||||||
host: Option.none(),
|
|
||||||
baseDir: Option.some(baseDir),
|
|
||||||
cwd: Option.some(customCwd),
|
|
||||||
devUrl: Option.some(new URL("http://127.0.0.1:5173")),
|
|
||||||
noBrowser: Option.none(),
|
|
||||||
bootstrapFd: Option.none(),
|
|
||||||
autoBootstrapProjectFromCwd: Option.none(),
|
|
||||||
logWebSocketEvents: Option.none(),
|
|
||||||
},
|
|
||||||
Option.none(),
|
|
||||||
).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
Layer.mergeAll(
|
|
||||||
ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
|
|
||||||
NetService.layer,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
for (const directory of [
|
|
||||||
customCwd,
|
|
||||||
resolved.stateDir,
|
|
||||||
resolved.logsDir,
|
|
||||||
resolved.providerLogsDir,
|
|
||||||
resolved.terminalLogsDir,
|
|
||||||
resolved.attachmentsDir,
|
|
||||||
resolved.worktreesDir,
|
|
||||||
path.dirname(resolved.serverLogPath),
|
|
||||||
path.dirname(resolved.serverTracePath),
|
|
||||||
]) {
|
|
||||||
expect(yield* fs.exists(directory)).toBe(true);
|
|
||||||
}
|
|
||||||
expect(resolved.cwd).toBe(path.resolve(customCwd));
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("applies flag then env precedence over bootstrap envelope values", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const { join } = yield* Path.Path;
|
|
||||||
const baseDir = join(os.tmpdir(), "t3-cli-config-env-wins");
|
|
||||||
const fd = yield* openBootstrapFd({
|
|
||||||
mode: "desktop",
|
|
||||||
port: 4888,
|
|
||||||
host: "127.0.0.2",
|
|
||||||
t3Home: "/tmp/t3-bootstrap-home",
|
|
||||||
devUrl: "http://127.0.0.1:5173",
|
|
||||||
noBrowser: false,
|
|
||||||
autoBootstrapProjectFromCwd: false,
|
|
||||||
logWebSocketEvents: false,
|
|
||||||
});
|
|
||||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
|
||||||
|
|
||||||
const resolved = yield* resolveServerConfig(
|
|
||||||
{
|
|
||||||
mode: Option.none(),
|
|
||||||
port: Option.some(8788),
|
|
||||||
host: Option.some("127.0.0.1"),
|
|
||||||
baseDir: Option.none(),
|
|
||||||
cwd: Option.none(),
|
|
||||||
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
|
|
||||||
noBrowser: Option.none(),
|
|
||||||
bootstrapFd: Option.none(),
|
|
||||||
autoBootstrapProjectFromCwd: Option.none(),
|
|
||||||
logWebSocketEvents: Option.none(),
|
|
||||||
},
|
|
||||||
Option.some("Debug"),
|
|
||||||
).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
Layer.mergeAll(
|
|
||||||
ConfigProvider.layer(
|
|
||||||
ConfigProvider.fromEnv({
|
|
||||||
env: {
|
|
||||||
T3CODE_MODE: "web",
|
|
||||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
|
||||||
T3CODE_HOME: baseDir,
|
|
||||||
T3CODE_NO_BROWSER: "true",
|
|
||||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
|
|
||||||
T3CODE_LOG_WS_EVENTS: "true",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
NetService.layer,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(resolved).toEqual({
|
|
||||||
logLevel: "Debug",
|
|
||||||
...defaultObservabilityConfig,
|
|
||||||
mode: "web",
|
|
||||||
port: 8788,
|
|
||||||
cwd: process.cwd(),
|
|
||||||
baseDir,
|
|
||||||
...derivedPaths,
|
|
||||||
host: "127.0.0.1",
|
|
||||||
staticDir: undefined,
|
|
||||||
devUrl: new URL("http://127.0.0.1:4173"),
|
|
||||||
noBrowser: true,
|
|
||||||
startupPresentation: "browser",
|
|
||||||
desktopBootstrapToken: undefined,
|
|
||||||
autoBootstrapProjectFromCwd: true,
|
|
||||||
logWebSocketEvents: true,
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("falls back to persisted observability settings when env vars are absent", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fs = yield* FileSystem.FileSystem;
|
|
||||||
const path = yield* Path.Path;
|
|
||||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-settings-" });
|
|
||||||
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
|
|
||||||
yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
|
|
||||||
yield* fs.writeFileString(
|
|
||||||
derivedPaths.settingsPath,
|
|
||||||
`${JSON.stringify({
|
|
||||||
observability: {
|
|
||||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
|
||||||
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
|
||||||
},
|
|
||||||
})}\n`,
|
|
||||||
);
|
|
||||||
|
|
||||||
const resolved = yield* resolveServerConfig(
|
|
||||||
{
|
|
||||||
mode: Option.some("desktop"),
|
|
||||||
port: Option.some(4888),
|
|
||||||
host: Option.none(),
|
|
||||||
baseDir: Option.some(baseDir),
|
|
||||||
cwd: Option.none(),
|
|
||||||
devUrl: Option.none(),
|
|
||||||
noBrowser: Option.none(),
|
|
||||||
bootstrapFd: Option.none(),
|
|
||||||
autoBootstrapProjectFromCwd: Option.none(),
|
|
||||||
logWebSocketEvents: Option.none(),
|
|
||||||
},
|
|
||||||
Option.none(),
|
|
||||||
).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
Layer.mergeAll(
|
|
||||||
ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
|
|
||||||
NetService.layer,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(resolved.otlpTracesUrl).toBe("http://localhost:4318/v1/traces");
|
|
||||||
expect(resolved.otlpMetricsUrl).toBe("http://localhost:4318/v1/metrics");
|
|
||||||
expect(resolved).toEqual({
|
|
||||||
logLevel: "Info",
|
|
||||||
...defaultObservabilityConfig,
|
|
||||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
|
||||||
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
|
||||||
mode: "desktop",
|
|
||||||
port: 4888,
|
|
||||||
cwd: process.cwd(),
|
|
||||||
baseDir,
|
|
||||||
...derivedPaths,
|
|
||||||
host: "127.0.0.1",
|
|
||||||
staticDir: resolved.staticDir,
|
|
||||||
devUrl: undefined,
|
|
||||||
noBrowser: true,
|
|
||||||
startupPresentation: "browser",
|
|
||||||
desktopBootstrapToken: undefined,
|
|
||||||
autoBootstrapProjectFromCwd: false,
|
|
||||||
logWebSocketEvents: false,
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("forces noBrowser and disables auto-bootstrap for headless startup presentation", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const { join } = yield* Path.Path;
|
|
||||||
const baseDir = join(os.tmpdir(), "t3-cli-config-headless-base");
|
|
||||||
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
|
|
||||||
|
|
||||||
const resolved = yield* resolveServerConfig(
|
|
||||||
{
|
|
||||||
mode: Option.some("web"),
|
|
||||||
port: Option.some(3773),
|
|
||||||
host: Option.none(),
|
|
||||||
baseDir: Option.some(baseDir),
|
|
||||||
cwd: Option.none(),
|
|
||||||
devUrl: Option.none(),
|
|
||||||
noBrowser: Option.none(),
|
|
||||||
bootstrapFd: Option.none(),
|
|
||||||
autoBootstrapProjectFromCwd: Option.none(),
|
|
||||||
logWebSocketEvents: Option.none(),
|
|
||||||
},
|
|
||||||
Option.none(),
|
|
||||||
{
|
|
||||||
startupPresentation: "headless",
|
|
||||||
},
|
|
||||||
).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
Layer.mergeAll(
|
|
||||||
ConfigProvider.layer(
|
|
||||||
ConfigProvider.fromEnv({
|
|
||||||
env: {
|
|
||||||
T3CODE_NO_BROWSER: "false",
|
|
||||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
NetService.layer,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(resolved).toEqual({
|
|
||||||
logLevel: "Info",
|
|
||||||
...defaultObservabilityConfig,
|
|
||||||
mode: "web",
|
|
||||||
port: 3773,
|
|
||||||
cwd: process.cwd(),
|
|
||||||
baseDir,
|
|
||||||
...derivedPaths,
|
|
||||||
host: undefined,
|
|
||||||
staticDir: resolved.staticDir,
|
|
||||||
devUrl: undefined,
|
|
||||||
noBrowser: true,
|
|
||||||
startupPresentation: "headless",
|
|
||||||
desktopBootstrapToken: undefined,
|
|
||||||
autoBootstrapProjectFromCwd: false,
|
|
||||||
logWebSocketEvents: false,
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,352 +0,0 @@
|
|||||||
import * as NodeHttp from "node:http";
|
|
||||||
import { mkdtempSync } from "node:fs";
|
|
||||||
import { tmpdir } from "node:os";
|
|
||||||
import { join } from "node:path";
|
|
||||||
|
|
||||||
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import { NetService } from "@t3tools/shared/Net";
|
|
||||||
import { assert, it } from "@effect/vitest";
|
|
||||||
import * as Effect from "effect/Effect";
|
|
||||||
import * as Layer from "effect/Layer";
|
|
||||||
import * as HttpRouter from "effect/unstable/http/HttpRouter";
|
|
||||||
import * as HttpServer from "effect/unstable/http/HttpServer";
|
|
||||||
import * as CliError from "effect/unstable/cli/CliError";
|
|
||||||
import * as TestConsole from "effect/testing/TestConsole";
|
|
||||||
import { Command } from "effect/unstable/cli";
|
|
||||||
|
|
||||||
import { cli } from "./cli.ts";
|
|
||||||
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";
|
|
||||||
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
|
|
||||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
|
||||||
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
|
|
||||||
import {
|
|
||||||
orchestrationDispatchRouteLayer,
|
|
||||||
orchestrationSnapshotRouteLayer,
|
|
||||||
} from "./orchestration/http.ts";
|
|
||||||
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
|
|
||||||
import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";
|
|
||||||
import {
|
|
||||||
makePersistedServerRuntimeState,
|
|
||||||
persistServerRuntimeState,
|
|
||||||
} from "./serverRuntimeState.ts";
|
|
||||||
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
|
|
||||||
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
|
|
||||||
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
|
|
||||||
|
|
||||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
|
||||||
|
|
||||||
const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
|
|
||||||
const runCliWithRuntime = (args: ReadonlyArray<string>) =>
|
|
||||||
runCli(args).pipe(Effect.provide(CliRuntimeLayer));
|
|
||||||
|
|
||||||
const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const result = yield* effect;
|
|
||||||
const output =
|
|
||||||
(yield* TestConsole.logLines).findLast((line): line is string => typeof line === "string") ??
|
|
||||||
"";
|
|
||||||
return { result, output };
|
|
||||||
}).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer)));
|
|
||||||
|
|
||||||
const makeCliTestServerConfig = (baseDir: string) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
|
|
||||||
return {
|
|
||||||
logLevel: "Info",
|
|
||||||
traceMinLevel: "Info",
|
|
||||||
traceTimingEnabled: true,
|
|
||||||
traceBatchWindowMs: 200,
|
|
||||||
traceMaxBytes: 10 * 1024 * 1024,
|
|
||||||
traceMaxFiles: 10,
|
|
||||||
otlpTracesUrl: undefined,
|
|
||||||
otlpMetricsUrl: undefined,
|
|
||||||
otlpExportIntervalMs: 10_000,
|
|
||||||
otlpServiceName: "t3-server",
|
|
||||||
mode: "web",
|
|
||||||
port: 0,
|
|
||||||
host: "127.0.0.1",
|
|
||||||
cwd: process.cwd(),
|
|
||||||
baseDir,
|
|
||||||
...derivedPaths,
|
|
||||||
staticDir: undefined,
|
|
||||||
devUrl: undefined,
|
|
||||||
noBrowser: true,
|
|
||||||
startupPresentation: "browser",
|
|
||||||
desktopBootstrapToken: undefined,
|
|
||||||
autoBootstrapProjectFromCwd: false,
|
|
||||||
logWebSocketEvents: false,
|
|
||||||
} satisfies ServerConfigShape;
|
|
||||||
});
|
|
||||||
|
|
||||||
const makeProjectPersistenceLayer = (config: ServerConfigShape) =>
|
|
||||||
Layer.mergeAll(
|
|
||||||
OrchestrationLayerLive.pipe(
|
|
||||||
Layer.provideMerge(RepositoryIdentityResolverLive),
|
|
||||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
|
||||||
),
|
|
||||||
WorkspacePathsLive,
|
|
||||||
).pipe(
|
|
||||||
Layer.provideMerge(NodeServices.layer),
|
|
||||||
Layer.provide(Layer.succeed(ServerConfig, config)),
|
|
||||||
);
|
|
||||||
|
|
||||||
const readPersistedSnapshot = (baseDir: string) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const config = yield* makeCliTestServerConfig(baseDir);
|
|
||||||
return yield* Effect.gen(function* () {
|
|
||||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
|
||||||
return yield* projectionSnapshotQuery.getSnapshot();
|
|
||||||
}).pipe(Effect.provide(makeProjectPersistenceLayer(config)));
|
|
||||||
});
|
|
||||||
|
|
||||||
const withLiveProjectCliServer = <A, E, R>(baseDir: string, run: () => Effect.Effect<A, E, R>) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const config = yield* makeCliTestServerConfig(baseDir);
|
|
||||||
const routesLayer = Layer.mergeAll(
|
|
||||||
orchestrationSnapshotRouteLayer,
|
|
||||||
orchestrationDispatchRouteLayer,
|
|
||||||
);
|
|
||||||
const appLayer = HttpRouter.serve(routesLayer, {
|
|
||||||
disableListenLog: true,
|
|
||||||
disableLogger: true,
|
|
||||||
}).pipe(
|
|
||||||
Layer.provideMerge(
|
|
||||||
ServerAuthLive.pipe(
|
|
||||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
|
||||||
Layer.provide(ServerSecretStoreLive),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Layer.provideMerge(makeProjectPersistenceLayer(config)),
|
|
||||||
Layer.provideMerge(
|
|
||||||
NodeHttpServer.layer(NodeHttp.createServer, {
|
|
||||||
host: "127.0.0.1",
|
|
||||||
port: 0,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
Layer.provideMerge(NodeServices.layer),
|
|
||||||
Layer.provide(Layer.succeed(ServerConfig, config)),
|
|
||||||
);
|
|
||||||
|
|
||||||
return yield* Effect.scoped(
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const server = yield* HttpServer.HttpServer;
|
|
||||||
const address = server.address;
|
|
||||||
if (typeof address === "string" || !("port" in address)) {
|
|
||||||
assert.fail(`Expected TCP address, got ${address}`);
|
|
||||||
}
|
|
||||||
yield* persistServerRuntimeState({
|
|
||||||
path: config.serverRuntimeStatePath,
|
|
||||||
state: makePersistedServerRuntimeState({
|
|
||||||
config,
|
|
||||||
port: address.port,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
return yield* run();
|
|
||||||
}).pipe(Effect.provide(Layer.mergeAll(appLayer, NodeServices.layer))),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
|
|
||||||
it.effect("accepts the built-in lowercase log-level flag values", () =>
|
|
||||||
runCliWithRuntime(["--log-level", "debug", "--version"]),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("rejects invalid log-level casing before launching the server", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(Effect.flip);
|
|
||||||
|
|
||||||
if (!CliError.isCliError(error)) {
|
|
||||||
assert.fail(`Expected CliError, got ${String(error)}`);
|
|
||||||
}
|
|
||||||
if (error._tag !== "InvalidValue") {
|
|
||||||
assert.fail(`Expected InvalidValue, got ${error._tag}`);
|
|
||||||
}
|
|
||||||
assert.equal(error.option, "log-level");
|
|
||||||
assert.equal(error.value, "Debug");
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("executes auth pairing subcommands and redacts secrets from list output", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-pairing-test-"));
|
|
||||||
|
|
||||||
const createdOutput = yield* captureStdout(
|
|
||||||
runCli(["auth", "pairing", "create", "--base-dir", baseDir, "--json"]),
|
|
||||||
);
|
|
||||||
const created = JSON.parse(createdOutput.output) as {
|
|
||||||
readonly id: string;
|
|
||||||
readonly credential: string;
|
|
||||||
};
|
|
||||||
const listedOutput = yield* captureStdout(
|
|
||||||
runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
|
|
||||||
);
|
|
||||||
const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
|
|
||||||
readonly id: string;
|
|
||||||
readonly credential?: string;
|
|
||||||
}>;
|
|
||||||
|
|
||||||
assert.equal(typeof created.id, "string");
|
|
||||||
assert.equal(typeof created.credential, "string");
|
|
||||||
assert.equal(created.credential.length > 0, true);
|
|
||||||
assert.equal(listed.length, 1);
|
|
||||||
assert.equal(listed[0]?.id, created.id);
|
|
||||||
assert.equal("credential" in (listed[0] ?? {}), false);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("executes auth session subcommands and redacts secrets from list output", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-session-test-"));
|
|
||||||
|
|
||||||
const issuedOutput = yield* captureStdout(
|
|
||||||
runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"]),
|
|
||||||
);
|
|
||||||
const issued = JSON.parse(issuedOutput.output) as {
|
|
||||||
readonly sessionId: string;
|
|
||||||
readonly token: string;
|
|
||||||
readonly role: string;
|
|
||||||
};
|
|
||||||
const listedOutput = yield* captureStdout(
|
|
||||||
runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]),
|
|
||||||
);
|
|
||||||
const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
|
|
||||||
readonly sessionId: string;
|
|
||||||
readonly token?: string;
|
|
||||||
readonly role: string;
|
|
||||||
}>;
|
|
||||||
|
|
||||||
assert.equal(typeof issued.sessionId, "string");
|
|
||||||
assert.equal(typeof issued.token, "string");
|
|
||||||
assert.equal(issued.role, "owner");
|
|
||||||
assert.equal(listed.length, 1);
|
|
||||||
assert.equal(listed[0]?.sessionId, issued.sessionId);
|
|
||||||
assert.equal(listed[0]?.role, "owner");
|
|
||||||
assert.equal("token" in (listed[0] ?? {}), false);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("rejects invalid ttl values before running auth commands", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const error = yield* runCliWithRuntime(["auth", "pairing", "create", "--ttl", "soon"]).pipe(
|
|
||||||
Effect.flip,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!CliError.isCliError(error)) {
|
|
||||||
assert.fail(`Expected CliError, got ${String(error)}`);
|
|
||||||
}
|
|
||||||
if (error._tag !== "ShowHelp") {
|
|
||||||
assert.fail(`Expected ShowHelp, got ${error._tag}`);
|
|
||||||
}
|
|
||||||
assert.deepEqual(error.commandPath, ["t3", "auth", "pairing", "create"]);
|
|
||||||
const ttlError = error.errors[0] as CliError.CliError | undefined;
|
|
||||||
if (!ttlError || ttlError._tag !== "InvalidValue") {
|
|
||||||
assert.fail(`Expected InvalidValue, got ${String(ttlError?._tag)}`);
|
|
||||||
}
|
|
||||||
assert.equal(ttlError.option, "ttl");
|
|
||||||
assert.equal(ttlError.value, "soon");
|
|
||||||
assert.isTrue(ttlError.message.includes("Invalid duration"));
|
|
||||||
assert.isTrue(ttlError.message.includes("5m, 1h, 30d, or 15 minutes"));
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("adds, renames, and removes projects offline through the orchestration engine", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-projects-offline-test-"));
|
|
||||||
const workspaceRoot = mkdtempSync(join(tmpdir(), "t3-cli-projects-workspace-"));
|
|
||||||
|
|
||||||
yield* runCliWithRuntime([
|
|
||||||
"project",
|
|
||||||
"add",
|
|
||||||
workspaceRoot,
|
|
||||||
"--title",
|
|
||||||
"Alpha",
|
|
||||||
"--base-dir",
|
|
||||||
baseDir,
|
|
||||||
]);
|
|
||||||
const afterAdd = yield* readPersistedSnapshot(baseDir);
|
|
||||||
const addedProject = afterAdd.projects.find(
|
|
||||||
(project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
|
|
||||||
);
|
|
||||||
assert.isTrue(addedProject !== undefined);
|
|
||||||
assert.equal(addedProject?.title, "Alpha");
|
|
||||||
|
|
||||||
yield* runCliWithRuntime(["project", "rename", workspaceRoot, "Beta", "--base-dir", baseDir]);
|
|
||||||
const afterRename = yield* readPersistedSnapshot(baseDir);
|
|
||||||
const renamedProject = afterRename.projects.find(
|
|
||||||
(project) => project.id === addedProject?.id,
|
|
||||||
);
|
|
||||||
assert.equal(renamedProject?.title, "Beta");
|
|
||||||
assert.equal(renamedProject?.deletedAt, null);
|
|
||||||
|
|
||||||
yield* runCliWithRuntime([
|
|
||||||
"project",
|
|
||||||
"remove",
|
|
||||||
addedProject?.id ?? "",
|
|
||||||
"--base-dir",
|
|
||||||
baseDir,
|
|
||||||
]);
|
|
||||||
const afterRemove = yield* readPersistedSnapshot(baseDir);
|
|
||||||
const removedProject = afterRemove.projects.find(
|
|
||||||
(project) => project.id === addedProject?.id,
|
|
||||||
);
|
|
||||||
assert.isTrue((removedProject?.deletedAt ?? null) !== null);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("routes project commands through a running server when runtime state is present", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-projects-live-test-"));
|
|
||||||
const workspaceRoot = mkdtempSync(join(tmpdir(), "t3-cli-projects-live-workspace-"));
|
|
||||||
|
|
||||||
yield* withLiveProjectCliServer(baseDir, () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
yield* runCliWithRuntime([
|
|
||||||
"project",
|
|
||||||
"add",
|
|
||||||
workspaceRoot,
|
|
||||||
"--title",
|
|
||||||
"Live Project",
|
|
||||||
"--base-dir",
|
|
||||||
baseDir,
|
|
||||||
]);
|
|
||||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
|
||||||
const readModel = yield* orchestrationEngine.getReadModel();
|
|
||||||
const addedProject = readModel.projects.find(
|
|
||||||
(project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
|
|
||||||
);
|
|
||||||
assert.isTrue(addedProject !== undefined);
|
|
||||||
assert.equal(addedProject?.title, "Live Project");
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("rejects dev-url on project commands", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const workspaceRoot = mkdtempSync(
|
|
||||||
join(tmpdir(), "t3-cli-projects-unknown-option-workspace-"),
|
|
||||||
);
|
|
||||||
const error = yield* runCliWithRuntime([
|
|
||||||
"project",
|
|
||||||
"add",
|
|
||||||
workspaceRoot,
|
|
||||||
"--dev-url",
|
|
||||||
"http://127.0.0.1:5173",
|
|
||||||
]).pipe(Effect.flip);
|
|
||||||
|
|
||||||
if (!CliError.isCliError(error)) {
|
|
||||||
assert.fail(`Expected CliError, got ${String(error)}`);
|
|
||||||
}
|
|
||||||
if (error._tag !== "ShowHelp") {
|
|
||||||
assert.fail(`Expected ShowHelp, got ${error._tag}`);
|
|
||||||
}
|
|
||||||
assert.deepEqual(error.commandPath, ["t3", "project", "add"]);
|
|
||||||
const optionError = error.errors[0] as CliError.CliError | undefined;
|
|
||||||
if (!optionError || optionError._tag !== "UnrecognizedOption") {
|
|
||||||
assert.fail(`Expected UnrecognizedOption, got ${String(optionError?._tag)}`);
|
|
||||||
}
|
|
||||||
assert.equal(optionError.option, "--dev-url");
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -1,88 +0,0 @@
|
|||||||
import { expect, it } from "@effect/vitest";
|
|
||||||
import { DateTime } from "effect";
|
|
||||||
|
|
||||||
import {
|
|
||||||
formatIssuedPairingCredential,
|
|
||||||
formatIssuedSession,
|
|
||||||
formatPairingCredentialList,
|
|
||||||
formatSessionList,
|
|
||||||
} from "./cliAuthFormat.ts";
|
|
||||||
|
|
||||||
it("formats issued pairing credentials with the secret and optional pair URL", () => {
|
|
||||||
const output = formatIssuedPairingCredential(
|
|
||||||
{
|
|
||||||
id: "pairing-1",
|
|
||||||
credential: "secret-pairing-token",
|
|
||||||
role: "client",
|
|
||||||
subject: "one-time-token",
|
|
||||||
createdAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
|
|
||||||
expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
|
|
||||||
},
|
|
||||||
{ baseUrl: "https://example.com", json: false },
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(output).toContain("secret-pairing-token");
|
|
||||||
expect(output).toContain("https://example.com/pair#token=secret-pairing-token");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("formats pairing listings without exposing the secret token", () => {
|
|
||||||
const output = formatPairingCredentialList(
|
|
||||||
[
|
|
||||||
{
|
|
||||||
id: "pairing-1",
|
|
||||||
credential: "secret-pairing-token",
|
|
||||||
subject: "one-time-token",
|
|
||||||
label: "Phone",
|
|
||||||
role: "client",
|
|
||||||
createdAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
|
|
||||||
expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
{ json: false },
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(output).toContain("pairing-1");
|
|
||||||
expect(output).not.toContain("secret-pairing-token");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("formats issued sessions with the bearer token but omits tokens from listings", () => {
|
|
||||||
const issuedOutput = formatIssuedSession(
|
|
||||||
{
|
|
||||||
sessionId: "session-1" as never,
|
|
||||||
token: "secret-session-token",
|
|
||||||
method: "bearer-session-token",
|
|
||||||
role: "owner",
|
|
||||||
subject: "cli-issued-session",
|
|
||||||
client: {
|
|
||||||
label: "deploy-bot",
|
|
||||||
deviceType: "bot",
|
|
||||||
},
|
|
||||||
expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
|
|
||||||
},
|
|
||||||
{ json: false },
|
|
||||||
);
|
|
||||||
|
|
||||||
const listedOutput = formatSessionList(
|
|
||||||
[
|
|
||||||
{
|
|
||||||
sessionId: "session-1" as never,
|
|
||||||
method: "bearer-session-token",
|
|
||||||
role: "owner",
|
|
||||||
subject: "cli-issued-session",
|
|
||||||
client: {
|
|
||||||
label: "deploy-bot",
|
|
||||||
deviceType: "bot",
|
|
||||||
},
|
|
||||||
connected: false,
|
|
||||||
current: false,
|
|
||||||
issuedAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
|
|
||||||
expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
|
|
||||||
lastConnectedAt: null,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
{ json: false },
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(issuedOutput).toContain("secret-session-token");
|
|
||||||
expect(listedOutput).not.toContain("secret-session-token");
|
|
||||||
});
|
|
||||||
@@ -1,190 +0,0 @@
|
|||||||
import type { AuthClientMetadata, AuthClientSession, AuthPairingLink } from "@t3tools/contracts";
|
|
||||||
import { DateTime } from "effect";
|
|
||||||
|
|
||||||
import type { IssuedBearerSession, IssuedPairingLink } from "./auth/Services/AuthControlPlane.ts";
|
|
||||||
|
|
||||||
const newline = "\n";
|
|
||||||
|
|
||||||
function serializeOptionalFields(values: ReadonlyArray<string | null | undefined>) {
|
|
||||||
return values.filter((value): value is string => typeof value === "string" && value.length > 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatClientMetadata(metadata: AuthClientMetadata): string {
|
|
||||||
const details = serializeOptionalFields([
|
|
||||||
metadata.label,
|
|
||||||
metadata.deviceType !== "unknown" ? metadata.deviceType : undefined,
|
|
||||||
metadata.os,
|
|
||||||
metadata.browser,
|
|
||||||
metadata.ipAddress,
|
|
||||||
]);
|
|
||||||
return details.length > 0 ? details.join(" | ") : "unlabeled client";
|
|
||||||
}
|
|
||||||
|
|
||||||
function toIsoString(value: DateTime.DateTime | DateTime.Utc): string {
|
|
||||||
return DateTime.formatIso(DateTime.toUtc(value));
|
|
||||||
}
|
|
||||||
|
|
||||||
export function formatIssuedPairingCredential(
|
|
||||||
credential: IssuedPairingLink,
|
|
||||||
options?: {
|
|
||||||
readonly json?: boolean;
|
|
||||||
readonly baseUrl?: string;
|
|
||||||
},
|
|
||||||
): string {
|
|
||||||
const pairUrl =
|
|
||||||
options?.baseUrl != null && options.baseUrl.length > 0
|
|
||||||
? (() => {
|
|
||||||
const url = new URL("/pair", options.baseUrl);
|
|
||||||
url.searchParams.delete("token");
|
|
||||||
url.hash = new URLSearchParams([["token", credential.credential]]).toString();
|
|
||||||
return url.toString();
|
|
||||||
})()
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
if (options?.json) {
|
|
||||||
return `${JSON.stringify(
|
|
||||||
{
|
|
||||||
id: credential.id,
|
|
||||||
credential: credential.credential,
|
|
||||||
...(credential.label ? { label: credential.label } : {}),
|
|
||||||
role: credential.role,
|
|
||||||
expiresAt: toIsoString(credential.expiresAt),
|
|
||||||
...(pairUrl ? { pairUrl } : {}),
|
|
||||||
},
|
|
||||||
null,
|
|
||||||
2,
|
|
||||||
)}${newline}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
[
|
|
||||||
`Issued client pairing token ${credential.id}.`,
|
|
||||||
`Token: ${credential.credential}`,
|
|
||||||
...(pairUrl ? [`Pair URL: ${pairUrl}`] : []),
|
|
||||||
`Expires at: ${credential.expiresAt}`,
|
|
||||||
].join(newline) + newline
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function formatPairingCredentialList(
|
|
||||||
credentials: ReadonlyArray<AuthPairingLink>,
|
|
||||||
options?: {
|
|
||||||
readonly json?: boolean;
|
|
||||||
},
|
|
||||||
): string {
|
|
||||||
if (options?.json) {
|
|
||||||
return `${JSON.stringify(
|
|
||||||
credentials.map((credential) => ({
|
|
||||||
id: credential.id,
|
|
||||||
...(credential.label ? { label: credential.label } : {}),
|
|
||||||
role: credential.role,
|
|
||||||
createdAt: toIsoString(credential.createdAt),
|
|
||||||
expiresAt: toIsoString(credential.expiresAt),
|
|
||||||
})),
|
|
||||||
null,
|
|
||||||
2,
|
|
||||||
)}${newline}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (credentials.length === 0) {
|
|
||||||
return `No active pairing credentials.${newline}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
credentials
|
|
||||||
.map((credential) =>
|
|
||||||
[
|
|
||||||
`${credential.id}${credential.label ? ` (${credential.label})` : ""}`,
|
|
||||||
` role: ${credential.role}`,
|
|
||||||
` created: ${toIsoString(credential.createdAt)}`,
|
|
||||||
` expires: ${toIsoString(credential.expiresAt)}`,
|
|
||||||
].join(newline),
|
|
||||||
)
|
|
||||||
.join(`${newline}${newline}`) + newline
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function formatIssuedSession(
|
|
||||||
session: IssuedBearerSession,
|
|
||||||
options?: {
|
|
||||||
readonly json?: boolean;
|
|
||||||
readonly tokenOnly?: boolean;
|
|
||||||
},
|
|
||||||
): string {
|
|
||||||
if (options?.tokenOnly) {
|
|
||||||
return `${session.token}${newline}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (options?.json) {
|
|
||||||
return `${JSON.stringify(
|
|
||||||
{
|
|
||||||
sessionId: session.sessionId,
|
|
||||||
token: session.token,
|
|
||||||
method: session.method,
|
|
||||||
role: session.role,
|
|
||||||
subject: session.subject,
|
|
||||||
client: session.client,
|
|
||||||
expiresAt: toIsoString(session.expiresAt),
|
|
||||||
},
|
|
||||||
null,
|
|
||||||
2,
|
|
||||||
)}${newline}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
[
|
|
||||||
`Issued ${session.role} bearer session ${session.sessionId}.`,
|
|
||||||
`Token: ${session.token}`,
|
|
||||||
`Subject: ${session.subject}`,
|
|
||||||
`Client: ${formatClientMetadata(session.client)}`,
|
|
||||||
`Expires at: ${toIsoString(session.expiresAt)}`,
|
|
||||||
].join(newline) + newline
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function formatSessionList(
|
|
||||||
sessions: ReadonlyArray<AuthClientSession>,
|
|
||||||
options?: {
|
|
||||||
readonly json?: boolean;
|
|
||||||
},
|
|
||||||
): string {
|
|
||||||
if (options?.json) {
|
|
||||||
return `${JSON.stringify(
|
|
||||||
sessions.map((session) => ({
|
|
||||||
sessionId: session.sessionId,
|
|
||||||
method: session.method,
|
|
||||||
role: session.role,
|
|
||||||
subject: session.subject,
|
|
||||||
client: session.client,
|
|
||||||
connected: session.connected,
|
|
||||||
issuedAt: toIsoString(session.issuedAt),
|
|
||||||
expiresAt: toIsoString(session.expiresAt),
|
|
||||||
lastConnectedAt: session.lastConnectedAt ? toIsoString(session.lastConnectedAt) : null,
|
|
||||||
})),
|
|
||||||
null,
|
|
||||||
2,
|
|
||||||
)}${newline}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (sessions.length === 0) {
|
|
||||||
return `No active sessions.${newline}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
sessions
|
|
||||||
.map((session) =>
|
|
||||||
[
|
|
||||||
`${session.sessionId} [${session.role}]${session.connected ? " connected" : ""}`,
|
|
||||||
` method: ${session.method}`,
|
|
||||||
` subject: ${session.subject}`,
|
|
||||||
` client: ${formatClientMetadata(session.client)}`,
|
|
||||||
` issued: ${toIsoString(session.issuedAt)}`,
|
|
||||||
` last connected: ${
|
|
||||||
session.lastConnectedAt ? toIsoString(session.lastConnectedAt) : "never"
|
|
||||||
}`,
|
|
||||||
` expires: ${toIsoString(session.expiresAt)}`,
|
|
||||||
].join(newline),
|
|
||||||
)
|
|
||||||
.join(`${newline}${newline}`) + newline
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -37,7 +37,6 @@ function createSendTurnHarness() {
|
|||||||
planType: null,
|
planType: null,
|
||||||
sparkEnabled: true,
|
sparkEnabled: true,
|
||||||
},
|
},
|
||||||
collabReceiverTurns: new Map(),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const requireSession = vi
|
const requireSession = vi
|
||||||
@@ -76,7 +75,6 @@ function createThreadControlHarness() {
|
|||||||
createdAt: "2026-02-10T00:00:00.000Z",
|
createdAt: "2026-02-10T00:00:00.000Z",
|
||||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||||
},
|
},
|
||||||
collabReceiverTurns: new Map(),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const requireSession = vi
|
const requireSession = vi
|
||||||
@@ -119,7 +117,6 @@ function createPendingUserInputHarness() {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
]),
|
]),
|
||||||
collabReceiverTurns: new Map(),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const requireSession = vi
|
const requireSession = vi
|
||||||
@@ -138,43 +135,6 @@ function createPendingUserInputHarness() {
|
|||||||
return { manager, context, requireSession, writeMessage, emitEvent };
|
return { manager, context, requireSession, writeMessage, emitEvent };
|
||||||
}
|
}
|
||||||
|
|
||||||
function createCollabNotificationHarness() {
|
|
||||||
const manager = new CodexAppServerManager();
|
|
||||||
const context = {
|
|
||||||
session: {
|
|
||||||
provider: "codex",
|
|
||||||
status: "running",
|
|
||||||
threadId: asThreadId("thread_1"),
|
|
||||||
runtimeMode: "full-access",
|
|
||||||
model: "gpt-5.3-codex",
|
|
||||||
activeTurnId: "turn_parent",
|
|
||||||
resumeCursor: { threadId: "provider_parent" },
|
|
||||||
createdAt: "2026-02-10T00:00:00.000Z",
|
|
||||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
|
||||||
},
|
|
||||||
account: {
|
|
||||||
type: "unknown",
|
|
||||||
planType: null,
|
|
||||||
sparkEnabled: true,
|
|
||||||
},
|
|
||||||
pending: new Map(),
|
|
||||||
pendingApprovals: new Map(),
|
|
||||||
pendingUserInputs: new Map(),
|
|
||||||
collabReceiverTurns: new Map<string, string>(),
|
|
||||||
nextRequestId: 1,
|
|
||||||
stopping: false,
|
|
||||||
};
|
|
||||||
|
|
||||||
const emitEvent = vi
|
|
||||||
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
|
|
||||||
.mockImplementation(() => {});
|
|
||||||
const updateSession = vi
|
|
||||||
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
|
|
||||||
.mockImplementation(() => {});
|
|
||||||
|
|
||||||
return { manager, context, emitEvent, updateSession };
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("classifyCodexStderrLine", () => {
|
describe("classifyCodexStderrLine", () => {
|
||||||
it("ignores empty lines", () => {
|
it("ignores empty lines", () => {
|
||||||
expect(classifyCodexStderrLine(" ")).toBeNull();
|
expect(classifyCodexStderrLine(" ")).toBeNull();
|
||||||
@@ -207,42 +167,6 @@ describe("classifyCodexStderrLine", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("process stderr events", () => {
|
|
||||||
it("emits classified stderr lines as notifications", () => {
|
|
||||||
const manager = new CodexAppServerManager();
|
|
||||||
const emitEvent = vi
|
|
||||||
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
|
|
||||||
.mockImplementation(() => {});
|
|
||||||
|
|
||||||
(
|
|
||||||
manager as unknown as {
|
|
||||||
emitNotificationEvent: (
|
|
||||||
context: { session: { threadId: ThreadId } },
|
|
||||||
method: string,
|
|
||||||
message: string,
|
|
||||||
) => void;
|
|
||||||
}
|
|
||||||
).emitNotificationEvent(
|
|
||||||
{
|
|
||||||
session: {
|
|
||||||
threadId: asThreadId("thread-1"),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"process/stderr",
|
|
||||||
"fatal: permission denied",
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(emitEvent).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({
|
|
||||||
kind: "notification",
|
|
||||||
method: "process/stderr",
|
|
||||||
threadId: "thread-1",
|
|
||||||
message: "fatal: permission denied",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("normalizeCodexModelSlug", () => {
|
describe("normalizeCodexModelSlug", () => {
|
||||||
it("maps 5.3 aliases to gpt-5.3-codex", () => {
|
it("maps 5.3 aliases to gpt-5.3-codex", () => {
|
||||||
expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
|
expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
|
||||||
@@ -310,7 +234,7 @@ describe("readCodexAccountSnapshot", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("disables spark for api key accounts", () => {
|
it("keeps spark enabled for api key accounts", () => {
|
||||||
expect(
|
expect(
|
||||||
readCodexAccountSnapshot({
|
readCodexAccountSnapshot({
|
||||||
type: "apiKey",
|
type: "apiKey",
|
||||||
@@ -318,20 +242,7 @@ describe("readCodexAccountSnapshot", () => {
|
|||||||
).toEqual({
|
).toEqual({
|
||||||
type: "apiKey",
|
type: "apiKey",
|
||||||
planType: null,
|
planType: null,
|
||||||
sparkEnabled: false,
|
sparkEnabled: true,
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("disables spark for unknown chatgpt plans", () => {
|
|
||||||
expect(
|
|
||||||
readCodexAccountSnapshot({
|
|
||||||
type: "chatgpt",
|
|
||||||
email: "[email protected]",
|
|
||||||
}),
|
|
||||||
).toEqual({
|
|
||||||
type: "chatgpt",
|
|
||||||
planType: "unknown",
|
|
||||||
sparkEnabled: false,
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -356,16 +267,6 @@ describe("resolveCodexModelForAccount", () => {
|
|||||||
}),
|
}),
|
||||||
).toBe("gpt-5.3-codex-spark");
|
).toBe("gpt-5.3-codex-spark");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("falls back from spark to default for api key auth", () => {
|
|
||||||
expect(
|
|
||||||
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
|
|
||||||
type: "apiKey",
|
|
||||||
planType: null,
|
|
||||||
sparkEnabled: false,
|
|
||||||
}),
|
|
||||||
).toBe("gpt-5.3-codex");
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("startSession", () => {
|
describe("startSession", () => {
|
||||||
@@ -401,7 +302,6 @@ describe("startSession", () => {
|
|||||||
manager.startSession({
|
manager.startSession({
|
||||||
threadId: asThreadId("thread-1"),
|
threadId: asThreadId("thread-1"),
|
||||||
provider: "codex",
|
provider: "codex",
|
||||||
binaryPath: "codex",
|
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
}),
|
}),
|
||||||
).rejects.toThrow("cwd missing");
|
).rejects.toThrow("cwd missing");
|
||||||
@@ -450,7 +350,6 @@ describe("startSession", () => {
|
|||||||
manager.startSession({
|
manager.startSession({
|
||||||
threadId: asThreadId("thread-1"),
|
threadId: asThreadId("thread-1"),
|
||||||
provider: "codex",
|
provider: "codex",
|
||||||
binaryPath: "codex",
|
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
}),
|
}),
|
||||||
).rejects.toThrow(
|
).rejects.toThrow(
|
||||||
@@ -822,7 +721,6 @@ describe("respondToUserInput", () => {
|
|||||||
},
|
},
|
||||||
pendingApprovals: new Map(),
|
pendingApprovals: new Map(),
|
||||||
pendingUserInputs: new Map(),
|
pendingUserInputs: new Map(),
|
||||||
collabReceiverTurns: new Map(),
|
|
||||||
};
|
};
|
||||||
type ApprovalRequestContext = {
|
type ApprovalRequestContext = {
|
||||||
session: typeof context.session;
|
session: typeof context.session;
|
||||||
@@ -850,152 +748,6 @@ describe("respondToUserInput", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("collab child conversation routing", () => {
|
|
||||||
it("rewrites child notification turn ids onto the parent turn", () => {
|
|
||||||
const { manager, context, emitEvent } = createCollabNotificationHarness();
|
|
||||||
|
|
||||||
(
|
|
||||||
manager as unknown as {
|
|
||||||
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
|
||||||
}
|
|
||||||
).handleServerNotification(context, {
|
|
||||||
method: "item/completed",
|
|
||||||
params: {
|
|
||||||
item: {
|
|
||||||
type: "collabAgentToolCall",
|
|
||||||
id: "call_collab_1",
|
|
||||||
receiverThreadIds: ["child_provider_1"],
|
|
||||||
},
|
|
||||||
threadId: "provider_parent",
|
|
||||||
turnId: "turn_parent",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
(
|
|
||||||
manager as unknown as {
|
|
||||||
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
|
||||||
}
|
|
||||||
).handleServerNotification(context, {
|
|
||||||
method: "item/agentMessage/delta",
|
|
||||||
params: {
|
|
||||||
threadId: "child_provider_1",
|
|
||||||
turnId: "turn_child_1",
|
|
||||||
itemId: "msg_child_1",
|
|
||||||
delta: "working",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(emitEvent).toHaveBeenLastCalledWith(
|
|
||||||
expect.objectContaining({
|
|
||||||
method: "item/agentMessage/delta",
|
|
||||||
turnId: "turn_parent",
|
|
||||||
itemId: "msg_child_1",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("suppresses child lifecycle notifications so they cannot replace the parent turn", () => {
|
|
||||||
const { manager, context, emitEvent, updateSession } = createCollabNotificationHarness();
|
|
||||||
|
|
||||||
(
|
|
||||||
manager as unknown as {
|
|
||||||
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
|
||||||
}
|
|
||||||
).handleServerNotification(context, {
|
|
||||||
method: "item/completed",
|
|
||||||
params: {
|
|
||||||
item: {
|
|
||||||
type: "collabAgentToolCall",
|
|
||||||
id: "call_collab_1",
|
|
||||||
receiverThreadIds: ["child_provider_1"],
|
|
||||||
},
|
|
||||||
threadId: "provider_parent",
|
|
||||||
turnId: "turn_parent",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
emitEvent.mockClear();
|
|
||||||
updateSession.mockClear();
|
|
||||||
|
|
||||||
(
|
|
||||||
manager as unknown as {
|
|
||||||
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
|
||||||
}
|
|
||||||
).handleServerNotification(context, {
|
|
||||||
method: "turn/started",
|
|
||||||
params: {
|
|
||||||
threadId: "child_provider_1",
|
|
||||||
turn: { id: "turn_child_1" },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
(
|
|
||||||
manager as unknown as {
|
|
||||||
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
|
||||||
}
|
|
||||||
).handleServerNotification(context, {
|
|
||||||
method: "turn/completed",
|
|
||||||
params: {
|
|
||||||
threadId: "child_provider_1",
|
|
||||||
turn: { id: "turn_child_1", status: "completed" },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(emitEvent).not.toHaveBeenCalled();
|
|
||||||
expect(updateSession).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rewrites child approval requests onto the parent turn", () => {
|
|
||||||
const { manager, context, emitEvent } = createCollabNotificationHarness();
|
|
||||||
|
|
||||||
(
|
|
||||||
manager as unknown as {
|
|
||||||
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
|
||||||
}
|
|
||||||
).handleServerNotification(context, {
|
|
||||||
method: "item/completed",
|
|
||||||
params: {
|
|
||||||
item: {
|
|
||||||
type: "collabAgentToolCall",
|
|
||||||
id: "call_collab_1",
|
|
||||||
receiverThreadIds: ["child_provider_1"],
|
|
||||||
},
|
|
||||||
threadId: "provider_parent",
|
|
||||||
turnId: "turn_parent",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
emitEvent.mockClear();
|
|
||||||
|
|
||||||
(
|
|
||||||
manager as unknown as {
|
|
||||||
handleServerRequest: (context: unknown, request: Record<string, unknown>) => void;
|
|
||||||
}
|
|
||||||
).handleServerRequest(context, {
|
|
||||||
id: 42,
|
|
||||||
method: "item/commandExecution/requestApproval",
|
|
||||||
params: {
|
|
||||||
threadId: "child_provider_1",
|
|
||||||
turnId: "turn_child_1",
|
|
||||||
itemId: "call_child_1",
|
|
||||||
command: "bun install",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(Array.from(context.pendingApprovals.values())[0]).toEqual(
|
|
||||||
expect.objectContaining({
|
|
||||||
turnId: "turn_parent",
|
|
||||||
itemId: "call_child_1",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
expect(emitEvent).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({
|
|
||||||
method: "item/commandExecution/requestApproval",
|
|
||||||
turnId: "turn_parent",
|
|
||||||
itemId: "call_child_1",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
|
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
|
||||||
it("keeps prior thread history when resuming with a changed runtime mode", async () => {
|
it("keeps prior thread history when resuming with a changed runtime mode", async () => {
|
||||||
const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
|
const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
|
||||||
@@ -1009,8 +761,12 @@ describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume"
|
|||||||
provider: "codex",
|
provider: "codex",
|
||||||
cwd: workspaceDir,
|
cwd: workspaceDir,
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
binaryPath: process.env.CODEX_BINARY_PATH!,
|
providerOptions: {
|
||||||
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
codex: {
|
||||||
|
...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
|
||||||
|
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
||||||
|
},
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const firstTurn = await manager.sendTurn({
|
const firstTurn = await manager.sendTurn({
|
||||||
@@ -1040,8 +796,12 @@ describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume"
|
|||||||
cwd: workspaceDir,
|
cwd: workspaceDir,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
resumeCursor: firstSession.resumeCursor,
|
resumeCursor: firstSession.resumeCursor,
|
||||||
binaryPath: process.env.CODEX_BINARY_PATH!,
|
providerOptions: {
|
||||||
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
codex: {
|
||||||
|
...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
|
||||||
|
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
||||||
|
},
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(resumedSession.threadId).toBe(originalThreadId);
|
expect(resumedSession.threadId).toBe(originalThreadId);
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
type ProviderApprovalDecision,
|
type ProviderApprovalDecision,
|
||||||
type ProviderEvent,
|
type ProviderEvent,
|
||||||
type ProviderSession,
|
type ProviderSession,
|
||||||
|
type ProviderSessionStartInput,
|
||||||
type ProviderTurnStartResult,
|
type ProviderTurnStartResult,
|
||||||
RuntimeMode,
|
RuntimeMode,
|
||||||
ProviderInteractionMode,
|
ProviderInteractionMode,
|
||||||
@@ -26,15 +27,6 @@ import {
|
|||||||
isCodexCliVersionSupported,
|
isCodexCliVersionSupported,
|
||||||
parseCodexCliVersion,
|
parseCodexCliVersion,
|
||||||
} from "./provider/codexCliVersion";
|
} from "./provider/codexCliVersion";
|
||||||
import {
|
|
||||||
readCodexAccountSnapshot,
|
|
||||||
resolveCodexModelForAccount,
|
|
||||||
type CodexAccountSnapshot,
|
|
||||||
} from "./provider/codexAccount";
|
|
||||||
import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer";
|
|
||||||
|
|
||||||
export { buildCodexInitializeParams } from "./provider/codexAppServer";
|
|
||||||
export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount";
|
|
||||||
|
|
||||||
type PendingRequestKey = string;
|
type PendingRequestKey = string;
|
||||||
|
|
||||||
@@ -78,7 +70,6 @@ interface CodexSessionContext {
|
|||||||
pending: Map<PendingRequestKey, PendingRequest>;
|
pending: Map<PendingRequestKey, PendingRequest>;
|
||||||
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
|
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
|
||||||
pendingUserInputs: Map<ApprovalRequestId, PendingUserInputRequest>;
|
pendingUserInputs: Map<ApprovalRequestId, PendingUserInputRequest>;
|
||||||
collabReceiverTurns: Map<string, TurnId>;
|
|
||||||
nextRequestId: number;
|
nextRequestId: number;
|
||||||
stopping: boolean;
|
stopping: boolean;
|
||||||
}
|
}
|
||||||
@@ -105,6 +96,23 @@ interface JsonRpcNotification {
|
|||||||
params?: unknown;
|
params?: unknown;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type CodexPlanType =
|
||||||
|
| "free"
|
||||||
|
| "go"
|
||||||
|
| "plus"
|
||||||
|
| "pro"
|
||||||
|
| "team"
|
||||||
|
| "business"
|
||||||
|
| "enterprise"
|
||||||
|
| "edu"
|
||||||
|
| "unknown";
|
||||||
|
|
||||||
|
interface CodexAccountSnapshot {
|
||||||
|
readonly type: "apiKey" | "chatgpt" | "unknown";
|
||||||
|
readonly planType: CodexPlanType | null;
|
||||||
|
readonly sparkEnabled: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export interface CodexAppServerSendTurnInput {
|
export interface CodexAppServerSendTurnInput {
|
||||||
readonly threadId: ThreadId;
|
readonly threadId: ThreadId;
|
||||||
readonly input?: string;
|
readonly input?: string;
|
||||||
@@ -122,8 +130,7 @@ export interface CodexAppServerStartSessionInput {
|
|||||||
readonly model?: string;
|
readonly model?: string;
|
||||||
readonly serviceTier?: string;
|
readonly serviceTier?: string;
|
||||||
readonly resumeCursor?: unknown;
|
readonly resumeCursor?: unknown;
|
||||||
readonly binaryPath: string;
|
readonly providerOptions?: ProviderSessionStartInput["providerOptions"];
|
||||||
readonly homePath?: string;
|
|
||||||
readonly runtimeMode: RuntimeMode;
|
readonly runtimeMode: RuntimeMode;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,6 +161,50 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
|
|||||||
"unknown thread",
|
"unknown thread",
|
||||||
"does not exist",
|
"does not exist",
|
||||||
];
|
];
|
||||||
|
const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
|
||||||
|
const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
|
||||||
|
const CODEX_SPARK_DISABLED_PLAN_TYPES = new Set<CodexPlanType>(["free", "go", "plus"]);
|
||||||
|
|
||||||
|
function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||||
|
if (!value || typeof value !== "object") {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return value as Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function asString(value: unknown): string | undefined {
|
||||||
|
return typeof value === "string" ? value : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
|
||||||
|
const record = asObject(response);
|
||||||
|
const account = asObject(record?.account) ?? record;
|
||||||
|
const accountType = asString(account?.type);
|
||||||
|
|
||||||
|
if (accountType === "apiKey") {
|
||||||
|
return {
|
||||||
|
type: "apiKey",
|
||||||
|
planType: null,
|
||||||
|
sparkEnabled: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (accountType === "chatgpt") {
|
||||||
|
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
|
||||||
|
return {
|
||||||
|
type: "chatgpt",
|
||||||
|
planType,
|
||||||
|
sparkEnabled: !CODEX_SPARK_DISABLED_PLAN_TYPES.has(planType),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: "unknown",
|
||||||
|
planType: null,
|
||||||
|
sparkEnabled: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
|
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
|
||||||
|
|
||||||
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
|
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
|
||||||
@@ -290,26 +341,31 @@ In Default mode, strongly prefer making reasonable assumptions and executing the
|
|||||||
</collaboration_mode>`;
|
</collaboration_mode>`;
|
||||||
|
|
||||||
function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
|
function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
|
||||||
readonly approvalPolicy: "untrusted" | "on-request" | "never";
|
readonly approvalPolicy: "on-request" | "never";
|
||||||
readonly sandbox: "read-only" | "workspace-write" | "danger-full-access";
|
readonly sandbox: "workspace-write" | "danger-full-access";
|
||||||
} {
|
} {
|
||||||
switch (runtimeMode) {
|
if (runtimeMode === "approval-required") {
|
||||||
case "approval-required":
|
return {
|
||||||
return {
|
approvalPolicy: "on-request",
|
||||||
approvalPolicy: "untrusted",
|
sandbox: "workspace-write",
|
||||||
sandbox: "read-only",
|
};
|
||||||
};
|
|
||||||
case "auto-accept-edits":
|
|
||||||
return {
|
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandbox: "workspace-write",
|
|
||||||
};
|
|
||||||
case "full-access":
|
|
||||||
return {
|
|
||||||
approvalPolicy: "never",
|
|
||||||
sandbox: "danger-full-access",
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
approvalPolicy: "never",
|
||||||
|
sandbox: "danger-full-access",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveCodexModelForAccount(
|
||||||
|
model: string | undefined,
|
||||||
|
account: CodexAccountSnapshot,
|
||||||
|
): string | undefined {
|
||||||
|
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
|
||||||
|
return model;
|
||||||
|
}
|
||||||
|
|
||||||
|
return CODEX_DEFAULT_MODEL;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -318,7 +374,15 @@ function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
|
|||||||
* entire process tree instead.
|
* entire process tree instead.
|
||||||
*/
|
*/
|
||||||
function killChildTree(child: ChildProcessWithoutNullStreams): void {
|
function killChildTree(child: ChildProcessWithoutNullStreams): void {
|
||||||
killCodexChildProcess(child);
|
if (process.platform === "win32" && child.pid !== undefined) {
|
||||||
|
try {
|
||||||
|
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
||||||
|
return;
|
||||||
|
} catch {
|
||||||
|
// fallback to direct kill
|
||||||
|
}
|
||||||
|
}
|
||||||
|
child.kill();
|
||||||
}
|
}
|
||||||
|
|
||||||
export function normalizeCodexModelSlug(
|
export function normalizeCodexModelSlug(
|
||||||
@@ -337,6 +401,19 @@ export function normalizeCodexModelSlug(
|
|||||||
return normalized;
|
return normalized;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function buildCodexInitializeParams() {
|
||||||
|
return {
|
||||||
|
clientInfo: {
|
||||||
|
name: "t3code_desktop",
|
||||||
|
title: "T3 Code Desktop",
|
||||||
|
version: "0.1.0",
|
||||||
|
},
|
||||||
|
capabilities: {
|
||||||
|
experimentalApi: true,
|
||||||
|
},
|
||||||
|
} as const;
|
||||||
|
}
|
||||||
|
|
||||||
function buildCodexCollaborationMode(input: {
|
function buildCodexCollaborationMode(input: {
|
||||||
readonly interactionMode?: "default" | "plan";
|
readonly interactionMode?: "default" | "plan";
|
||||||
readonly model?: string;
|
readonly model?: string;
|
||||||
@@ -463,8 +540,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
};
|
};
|
||||||
|
|
||||||
const codexBinaryPath = input.binaryPath;
|
const codexOptions = readCodexProviderOptions(input);
|
||||||
const codexHomePath = input.homePath;
|
const codexBinaryPath = codexOptions.binaryPath ?? "codex";
|
||||||
|
const codexHomePath = codexOptions.homePath;
|
||||||
this.assertSupportedCodexCliVersion({
|
this.assertSupportedCodexCliVersion({
|
||||||
binaryPath: codexBinaryPath,
|
binaryPath: codexBinaryPath,
|
||||||
cwd: resolvedCwd,
|
cwd: resolvedCwd,
|
||||||
@@ -493,7 +571,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
pending: new Map(),
|
pending: new Map(),
|
||||||
pendingApprovals: new Map(),
|
pendingApprovals: new Map(),
|
||||||
pendingUserInputs: new Map(),
|
pendingUserInputs: new Map(),
|
||||||
collabReceiverTurns: new Map(),
|
|
||||||
nextRequestId: 1,
|
nextRequestId: 1,
|
||||||
stopping: false,
|
stopping: false,
|
||||||
};
|
};
|
||||||
@@ -655,7 +732,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
|
|
||||||
async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
|
async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
|
||||||
const context = this.requireSession(input.threadId);
|
const context = this.requireSession(input.threadId);
|
||||||
context.collabReceiverTurns.clear();
|
|
||||||
|
|
||||||
const turnInput: Array<
|
const turnInput: Array<
|
||||||
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
|
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
|
||||||
@@ -968,7 +1044,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.emitNotificationEvent(context, "process/stderr", classified.message);
|
this.emitErrorEvent(context, "process/stderr", classified.message);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1045,16 +1121,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
context: CodexSessionContext,
|
context: CodexSessionContext,
|
||||||
notification: JsonRpcNotification,
|
notification: JsonRpcNotification,
|
||||||
): void {
|
): void {
|
||||||
const rawRoute = this.readRouteFields(notification.params);
|
const route = this.readRouteFields(notification.params);
|
||||||
this.rememberCollabReceiverTurns(context, notification.params, rawRoute.turnId);
|
|
||||||
const childParentTurnId = this.readChildParentTurnId(context, notification.params);
|
|
||||||
const isChildConversation = childParentTurnId !== undefined;
|
|
||||||
if (
|
|
||||||
isChildConversation &&
|
|
||||||
this.shouldSuppressChildConversationNotification(notification.method)
|
|
||||||
) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const textDelta =
|
const textDelta =
|
||||||
notification.method === "item/agentMessage/delta"
|
notification.method === "item/agentMessage/delta"
|
||||||
? this.readString(notification.params, "delta")
|
? this.readString(notification.params, "delta")
|
||||||
@@ -1067,10 +1134,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
threadId: context.session.threadId,
|
threadId: context.session.threadId,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
method: notification.method,
|
method: notification.method,
|
||||||
...((childParentTurnId ?? rawRoute.turnId)
|
turnId: route.turnId,
|
||||||
? { turnId: childParentTurnId ?? rawRoute.turnId }
|
itemId: route.itemId,
|
||||||
: {}),
|
|
||||||
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
|
|
||||||
textDelta,
|
textDelta,
|
||||||
payload: notification.params,
|
payload: notification.params,
|
||||||
});
|
});
|
||||||
@@ -1086,9 +1151,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (notification.method === "turn/started") {
|
if (notification.method === "turn/started") {
|
||||||
if (isChildConversation) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const turnId = toTurnId(this.readString(this.readObject(notification.params)?.turn, "id"));
|
const turnId = toTurnId(this.readString(this.readObject(notification.params)?.turn, "id"));
|
||||||
this.updateSession(context, {
|
this.updateSession(context, {
|
||||||
status: "running",
|
status: "running",
|
||||||
@@ -1098,10 +1160,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (notification.method === "turn/completed") {
|
if (notification.method === "turn/completed") {
|
||||||
if (isChildConversation) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
context.collabReceiverTurns.clear();
|
|
||||||
const turn = this.readObject(notification.params, "turn");
|
const turn = this.readObject(notification.params, "turn");
|
||||||
const status = this.readString(turn, "status");
|
const status = this.readString(turn, "status");
|
||||||
const errorMessage = this.readString(this.readObject(turn, "error"), "message");
|
const errorMessage = this.readString(this.readObject(turn, "error"), "message");
|
||||||
@@ -1114,9 +1172,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (notification.method === "error") {
|
if (notification.method === "error") {
|
||||||
if (isChildConversation) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const message = this.readString(this.readObject(notification.params)?.error, "message");
|
const message = this.readString(this.readObject(notification.params)?.error, "message");
|
||||||
const willRetry = this.readBoolean(notification.params, "willRetry");
|
const willRetry = this.readBoolean(notification.params, "willRetry");
|
||||||
|
|
||||||
@@ -1128,9 +1183,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
}
|
}
|
||||||
|
|
||||||
private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
|
private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
|
||||||
const rawRoute = this.readRouteFields(request.params);
|
const route = this.readRouteFields(request.params);
|
||||||
const childParentTurnId = this.readChildParentTurnId(context, request.params);
|
|
||||||
const effectiveTurnId = childParentTurnId ?? rawRoute.turnId;
|
|
||||||
const requestKind = this.requestKindForMethod(request.method);
|
const requestKind = this.requestKindForMethod(request.method);
|
||||||
let requestId: ApprovalRequestId | undefined;
|
let requestId: ApprovalRequestId | undefined;
|
||||||
if (requestKind) {
|
if (requestKind) {
|
||||||
@@ -1146,8 +1199,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
: "item/fileChange/requestApproval",
|
: "item/fileChange/requestApproval",
|
||||||
requestKind,
|
requestKind,
|
||||||
threadId: context.session.threadId,
|
threadId: context.session.threadId,
|
||||||
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
|
...(route.turnId ? { turnId: route.turnId } : {}),
|
||||||
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
|
...(route.itemId ? { itemId: route.itemId } : {}),
|
||||||
};
|
};
|
||||||
context.pendingApprovals.set(requestId, pendingRequest);
|
context.pendingApprovals.set(requestId, pendingRequest);
|
||||||
}
|
}
|
||||||
@@ -1158,8 +1211,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
requestId,
|
requestId,
|
||||||
jsonRpcId: request.id,
|
jsonRpcId: request.id,
|
||||||
threadId: context.session.threadId,
|
threadId: context.session.threadId,
|
||||||
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
|
...(route.turnId ? { turnId: route.turnId } : {}),
|
||||||
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
|
...(route.itemId ? { itemId: route.itemId } : {}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1170,8 +1223,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
threadId: context.session.threadId,
|
threadId: context.session.threadId,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
method: request.method,
|
method: request.method,
|
||||||
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
|
turnId: route.turnId,
|
||||||
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
|
itemId: route.itemId,
|
||||||
requestId,
|
requestId,
|
||||||
requestKind,
|
requestKind,
|
||||||
payload: request.params,
|
payload: request.params,
|
||||||
@@ -1276,22 +1329,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private emitNotificationEvent(
|
|
||||||
context: CodexSessionContext,
|
|
||||||
method: string,
|
|
||||||
message: string,
|
|
||||||
): void {
|
|
||||||
this.emitEvent({
|
|
||||||
id: EventId.makeUnsafe(randomUUID()),
|
|
||||||
kind: "notification",
|
|
||||||
provider: "codex",
|
|
||||||
threadId: context.session.threadId,
|
|
||||||
createdAt: new Date().toISOString(),
|
|
||||||
method,
|
|
||||||
message,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private emitEvent(event: ProviderEvent): void {
|
private emitEvent(event: ProviderEvent): void {
|
||||||
this.emit("event", event);
|
this.emit("event", event);
|
||||||
}
|
}
|
||||||
@@ -1414,64 +1451,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
return route;
|
return route;
|
||||||
}
|
}
|
||||||
|
|
||||||
private readProviderConversationId(params: unknown): string | undefined {
|
|
||||||
return (
|
|
||||||
this.readString(params, "threadId") ??
|
|
||||||
this.readString(this.readObject(params, "thread"), "id") ??
|
|
||||||
this.readString(params, "conversationId")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private readChildParentTurnId(context: CodexSessionContext, params: unknown): TurnId | undefined {
|
|
||||||
const providerConversationId = this.readProviderConversationId(params);
|
|
||||||
if (!providerConversationId) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
return context.collabReceiverTurns.get(providerConversationId);
|
|
||||||
}
|
|
||||||
|
|
||||||
private rememberCollabReceiverTurns(
|
|
||||||
context: CodexSessionContext,
|
|
||||||
params: unknown,
|
|
||||||
parentTurnId: TurnId | undefined,
|
|
||||||
): void {
|
|
||||||
if (!parentTurnId) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const payload = this.readObject(params);
|
|
||||||
const item = this.readObject(payload, "item") ?? payload;
|
|
||||||
const itemType = this.readString(item, "type") ?? this.readString(item, "kind");
|
|
||||||
if (itemType !== "collabAgentToolCall") {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const receiverThreadIds =
|
|
||||||
this.readArray(item, "receiverThreadIds")
|
|
||||||
?.map((value) => (typeof value === "string" ? value : null))
|
|
||||||
.filter((value): value is string => value !== null) ?? [];
|
|
||||||
for (const receiverThreadId of receiverThreadIds) {
|
|
||||||
context.collabReceiverTurns.set(receiverThreadId, parentTurnId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private shouldSuppressChildConversationNotification(method: string): boolean {
|
|
||||||
return (
|
|
||||||
method === "thread/started" ||
|
|
||||||
method === "thread/status/changed" ||
|
|
||||||
method === "thread/archived" ||
|
|
||||||
method === "thread/unarchived" ||
|
|
||||||
method === "thread/closed" ||
|
|
||||||
method === "thread/compacted" ||
|
|
||||||
method === "thread/name/updated" ||
|
|
||||||
method === "thread/tokenUsage/updated" ||
|
|
||||||
method === "turn/started" ||
|
|
||||||
method === "turn/completed" ||
|
|
||||||
method === "turn/aborted" ||
|
|
||||||
method === "turn/plan/updated" ||
|
|
||||||
method === "item/plan/delta"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private readObject(value: unknown, key?: string): Record<string, unknown> | undefined {
|
private readObject(value: unknown, key?: string): Record<string, unknown> | undefined {
|
||||||
const target =
|
const target =
|
||||||
key === undefined
|
key === undefined
|
||||||
@@ -1528,6 +1507,20 @@ function normalizeProviderThreadId(value: string | undefined): string | undefine
|
|||||||
return brandIfNonEmpty(value, (normalized) => normalized);
|
return brandIfNonEmpty(value, (normalized) => normalized);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function readCodexProviderOptions(input: CodexAppServerStartSessionInput): {
|
||||||
|
readonly binaryPath?: string;
|
||||||
|
readonly homePath?: string;
|
||||||
|
} {
|
||||||
|
const options = input.providerOptions?.codex;
|
||||||
|
if (!options) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...(options.binaryPath ? { binaryPath: options.binaryPath } : {}),
|
||||||
|
...(options.homePath ? { homePath: options.homePath } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function assertSupportedCodexCliVersion(input: {
|
function assertSupportedCodexCliVersion(input: {
|
||||||
readonly binaryPath: string;
|
readonly binaryPath: string;
|
||||||
readonly cwd: string;
|
readonly cwd: string;
|
||||||
@@ -1581,11 +1574,7 @@ function readResumeCursorThreadId(resumeCursor: unknown): string | undefined {
|
|||||||
return typeof rawThreadId === "string" ? normalizeProviderThreadId(rawThreadId) : undefined;
|
return typeof rawThreadId === "string" ? normalizeProviderThreadId(rawThreadId) : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
function readResumeThreadId(input: {
|
function readResumeThreadId(input: CodexAppServerStartSessionInput): string | undefined {
|
||||||
readonly resumeCursor?: unknown;
|
|
||||||
readonly threadId?: ThreadId;
|
|
||||||
readonly runtimeMode?: RuntimeMode;
|
|
||||||
}): string | undefined {
|
|
||||||
return readResumeCursorThreadId(input.resumeCursor);
|
return readResumeCursorThreadId(input.resumeCursor);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+13
-120
@@ -6,162 +6,55 @@
|
|||||||
*
|
*
|
||||||
* @module ServerConfig
|
* @module ServerConfig
|
||||||
*/
|
*/
|
||||||
import { Effect, FileSystem, Layer, LogLevel, Path, Schema, ServiceMap } from "effect";
|
import { Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
|
||||||
|
|
||||||
export const DEFAULT_PORT = 3773;
|
export const DEFAULT_PORT = 3773;
|
||||||
|
|
||||||
export const RuntimeMode = Schema.Literals(["web", "desktop"]);
|
export type RuntimeMode = "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.
|
|
||||||
*/
|
|
||||||
export interface ServerDerivedPaths {
|
|
||||||
readonly stateDir: string;
|
|
||||||
readonly dbPath: string;
|
|
||||||
readonly keybindingsConfigPath: string;
|
|
||||||
readonly settingsPath: string;
|
|
||||||
readonly worktreesDir: string;
|
|
||||||
readonly attachmentsDir: string;
|
|
||||||
readonly logsDir: string;
|
|
||||||
readonly serverLogPath: string;
|
|
||||||
readonly serverTracePath: string;
|
|
||||||
readonly providerLogsDir: string;
|
|
||||||
readonly providerEventLogPath: string;
|
|
||||||
readonly terminalLogsDir: string;
|
|
||||||
readonly anonymousIdPath: string;
|
|
||||||
readonly environmentIdPath: string;
|
|
||||||
readonly serverRuntimeStatePath: string;
|
|
||||||
readonly secretsDir: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ServerConfigShape - Process/runtime configuration required by the server.
|
* ServerConfigShape - Process/runtime configuration required by the server.
|
||||||
*/
|
*/
|
||||||
export interface ServerConfigShape extends ServerDerivedPaths {
|
export interface ServerConfigShape {
|
||||||
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 mode: RuntimeMode;
|
||||||
readonly port: number;
|
readonly port: number;
|
||||||
readonly host: string | undefined;
|
readonly host: string | undefined;
|
||||||
readonly cwd: string;
|
readonly cwd: string;
|
||||||
readonly baseDir: string;
|
readonly keybindingsConfigPath: string;
|
||||||
|
readonly stateDir: string;
|
||||||
readonly staticDir: string | undefined;
|
readonly staticDir: string | undefined;
|
||||||
readonly devUrl: URL | undefined;
|
readonly devUrl: URL | undefined;
|
||||||
readonly noBrowser: boolean;
|
readonly noBrowser: boolean;
|
||||||
readonly startupPresentation: StartupPresentation;
|
readonly authToken: string | undefined;
|
||||||
readonly desktopBootstrapToken: string | undefined;
|
|
||||||
readonly autoBootstrapProjectFromCwd: boolean;
|
readonly autoBootstrapProjectFromCwd: boolean;
|
||||||
readonly logWebSocketEvents: boolean;
|
readonly logWebSocketEvents: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const deriveServerPaths = Effect.fn(function* (
|
|
||||||
baseDir: ServerConfigShape["baseDir"],
|
|
||||||
devUrl: ServerConfigShape["devUrl"],
|
|
||||||
): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
|
|
||||||
const { join } = yield* Path.Path;
|
|
||||||
const stateDir = join(baseDir, devUrl !== undefined ? "dev" : "userdata");
|
|
||||||
const dbPath = join(stateDir, "state.sqlite");
|
|
||||||
const attachmentsDir = join(stateDir, "attachments");
|
|
||||||
const logsDir = join(stateDir, "logs");
|
|
||||||
const providerLogsDir = join(logsDir, "provider");
|
|
||||||
return {
|
|
||||||
stateDir,
|
|
||||||
dbPath,
|
|
||||||
keybindingsConfigPath: join(stateDir, "keybindings.json"),
|
|
||||||
settingsPath: join(stateDir, "settings.json"),
|
|
||||||
worktreesDir: join(baseDir, "worktrees"),
|
|
||||||
attachmentsDir,
|
|
||||||
logsDir,
|
|
||||||
serverLogPath: join(logsDir, "server.log"),
|
|
||||||
serverTracePath: join(logsDir, "server.trace.ndjson"),
|
|
||||||
providerLogsDir,
|
|
||||||
providerEventLogPath: join(providerLogsDir, "events.log"),
|
|
||||||
terminalLogsDir: join(logsDir, "terminals"),
|
|
||||||
anonymousIdPath: join(stateDir, "anonymous-id"),
|
|
||||||
environmentIdPath: join(stateDir, "environment-id"),
|
|
||||||
serverRuntimeStatePath: join(stateDir, "server-runtime.json"),
|
|
||||||
secretsDir: join(stateDir, "secrets"),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
export const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) {
|
|
||||||
const fs = yield* FileSystem.FileSystem;
|
|
||||||
const path = yield* Path.Path;
|
|
||||||
|
|
||||||
yield* Effect.all(
|
|
||||||
[
|
|
||||||
fs.makeDirectory(derivedPaths.stateDir, { recursive: true }),
|
|
||||||
fs.makeDirectory(derivedPaths.logsDir, { recursive: true }),
|
|
||||||
fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }),
|
|
||||||
fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }),
|
|
||||||
fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }),
|
|
||||||
fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
|
|
||||||
fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
|
|
||||||
fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
|
|
||||||
fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
|
|
||||||
fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),
|
|
||||||
],
|
|
||||||
{ concurrency: "unbounded" },
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ServerConfig - Service tag for server runtime configuration.
|
* ServerConfig - Service tag for server runtime configuration.
|
||||||
*/
|
*/
|
||||||
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
|
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
|
||||||
"t3/config/ServerConfig",
|
"t3/config/ServerConfig",
|
||||||
) {
|
) {
|
||||||
static readonly layerTest = (cwd: string, baseDirOrPrefix: string | { prefix: string }) =>
|
static readonly layerTest = (cwd: string, statedir: string) =>
|
||||||
Layer.effect(
|
Layer.effect(
|
||||||
ServerConfig,
|
ServerConfig,
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const devUrl = undefined;
|
const path = yield* Path.Path;
|
||||||
|
|
||||||
const fs = yield* FileSystem.FileSystem;
|
|
||||||
const baseDir =
|
|
||||||
typeof baseDirOrPrefix === "string"
|
|
||||||
? baseDirOrPrefix
|
|
||||||
: yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });
|
|
||||||
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
|
|
||||||
yield* ensureServerDirectories(derivedPaths);
|
|
||||||
|
|
||||||
return {
|
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,
|
cwd,
|
||||||
baseDir,
|
stateDir: statedir,
|
||||||
...derivedPaths,
|
|
||||||
mode: "web",
|
mode: "web",
|
||||||
autoBootstrapProjectFromCwd: false,
|
autoBootstrapProjectFromCwd: false,
|
||||||
logWebSocketEvents: false,
|
logWebSocketEvents: false,
|
||||||
port: 0,
|
port: 0,
|
||||||
host: undefined,
|
host: undefined,
|
||||||
desktopBootstrapToken: undefined,
|
authToken: undefined,
|
||||||
|
keybindingsConfigPath: path.join(statedir, "keybindings.json"),
|
||||||
staticDir: undefined,
|
staticDir: undefined,
|
||||||
devUrl,
|
devUrl: undefined,
|
||||||
noBrowser: false,
|
noBrowser: false,
|
||||||
startupPresentation: "browser",
|
};
|
||||||
} satisfies ServerConfigShape;
|
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,125 +0,0 @@
|
|||||||
import * as nodePath from "node:path";
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import { expect, it } from "@effect/vitest";
|
|
||||||
import { Effect, Exit, FileSystem, Layer, PlatformError } from "effect";
|
|
||||||
|
|
||||||
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "../../config.ts";
|
|
||||||
import { ServerEnvironment } from "../Services/ServerEnvironment.ts";
|
|
||||||
import { ServerEnvironmentLive } from "./ServerEnvironment.ts";
|
|
||||||
|
|
||||||
const makeServerEnvironmentLayer = (baseDir: string) =>
|
|
||||||
ServerEnvironmentLive.pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
|
|
||||||
|
|
||||||
const makeServerConfig = Effect.fn(function* (baseDir: string) {
|
|
||||||
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
|
|
||||||
|
|
||||||
return {
|
|
||||||
...derivedPaths,
|
|
||||||
logLevel: "Error",
|
|
||||||
traceMinLevel: "Info",
|
|
||||||
traceTimingEnabled: true,
|
|
||||||
traceBatchWindowMs: 200,
|
|
||||||
traceMaxBytes: 10 * 1024 * 1024,
|
|
||||||
traceMaxFiles: 10,
|
|
||||||
otlpTracesUrl: undefined,
|
|
||||||
otlpMetricsUrl: undefined,
|
|
||||||
otlpExportIntervalMs: 10_000,
|
|
||||||
otlpServiceName: "t3-server",
|
|
||||||
cwd: process.cwd(),
|
|
||||||
baseDir,
|
|
||||||
mode: "web",
|
|
||||||
autoBootstrapProjectFromCwd: false,
|
|
||||||
logWebSocketEvents: false,
|
|
||||||
port: 0,
|
|
||||||
host: undefined,
|
|
||||||
desktopBootstrapToken: undefined,
|
|
||||||
staticDir: undefined,
|
|
||||||
devUrl: undefined,
|
|
||||||
noBrowser: false,
|
|
||||||
startupPresentation: "browser",
|
|
||||||
} satisfies ServerConfigShape;
|
|
||||||
});
|
|
||||||
|
|
||||||
it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
|
|
||||||
it.effect("persists the environment id across service restarts", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
|
||||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
|
||||||
prefix: "t3-server-environment-test-",
|
|
||||||
});
|
|
||||||
|
|
||||||
const first = yield* Effect.gen(function* () {
|
|
||||||
const serverEnvironment = yield* ServerEnvironment;
|
|
||||||
return yield* serverEnvironment.getDescriptor;
|
|
||||||
}).pipe(Effect.provide(makeServerEnvironmentLayer(baseDir)));
|
|
||||||
const second = yield* Effect.gen(function* () {
|
|
||||||
const serverEnvironment = yield* ServerEnvironment;
|
|
||||||
return yield* serverEnvironment.getDescriptor;
|
|
||||||
}).pipe(Effect.provide(makeServerEnvironmentLayer(baseDir)));
|
|
||||||
|
|
||||||
expect(first.environmentId).toBe(second.environmentId);
|
|
||||||
expect(second.capabilities.repositoryIdentity).toBe(true);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("fails instead of overwriting a persisted id when reading the file errors", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
|
||||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
|
||||||
prefix: "t3-server-environment-read-error-test-",
|
|
||||||
});
|
|
||||||
const serverConfig = yield* makeServerConfig(baseDir);
|
|
||||||
const environmentIdPath = serverConfig.environmentIdPath;
|
|
||||||
yield* fileSystem.makeDirectory(nodePath.dirname(environmentIdPath), { recursive: true });
|
|
||||||
yield* fileSystem.writeFileString(environmentIdPath, "persisted-environment-id\n");
|
|
||||||
const writeAttempts: string[] = [];
|
|
||||||
const failingFileSystemLayer = FileSystem.layerNoop({
|
|
||||||
exists: (path) => Effect.succeed(path === environmentIdPath),
|
|
||||||
readFileString: (path) =>
|
|
||||||
path === environmentIdPath
|
|
||||||
? Effect.fail(
|
|
||||||
PlatformError.systemError({
|
|
||||||
_tag: "PermissionDenied",
|
|
||||||
module: "FileSystem",
|
|
||||||
method: "readFileString",
|
|
||||||
description: "permission denied",
|
|
||||||
pathOrDescriptor: path,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
: Effect.fail(
|
|
||||||
PlatformError.systemError({
|
|
||||||
_tag: "NotFound",
|
|
||||||
module: "FileSystem",
|
|
||||||
method: "readFileString",
|
|
||||||
description: "not found",
|
|
||||||
pathOrDescriptor: path,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
writeFileString: (path) => {
|
|
||||||
writeAttempts.push(path);
|
|
||||||
return Effect.void;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const exit = yield* Effect.gen(function* () {
|
|
||||||
const serverEnvironment = yield* ServerEnvironment;
|
|
||||||
return yield* serverEnvironment.getDescriptor;
|
|
||||||
}).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
ServerEnvironmentLive.pipe(
|
|
||||||
Layer.provide(
|
|
||||||
Layer.merge(Layer.succeed(ServerConfig, serverConfig), failingFileSystemLayer),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Effect.exit,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(Exit.isFailure(exit)).toBe(true);
|
|
||||||
expect(writeAttempts).toEqual([]);
|
|
||||||
expect(yield* fileSystem.readFileString(environmentIdPath)).toBe(
|
|
||||||
"persisted-environment-id\n",
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
|
|
||||||
import { Effect, FileSystem, Layer, Path, Random } from "effect";
|
|
||||||
|
|
||||||
import { ServerConfig } from "../../config.ts";
|
|
||||||
import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/ServerEnvironment.ts";
|
|
||||||
import { version } from "../../../package.json" with { type: "json" };
|
|
||||||
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
|
|
||||||
|
|
||||||
function platformOs(): ExecutionEnvironmentDescriptor["platform"]["os"] {
|
|
||||||
switch (process.platform) {
|
|
||||||
case "darwin":
|
|
||||||
return "darwin";
|
|
||||||
case "linux":
|
|
||||||
return "linux";
|
|
||||||
case "win32":
|
|
||||||
return "windows";
|
|
||||||
default:
|
|
||||||
return "unknown";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function platformArch(): ExecutionEnvironmentDescriptor["platform"]["arch"] {
|
|
||||||
switch (process.arch) {
|
|
||||||
case "arm64":
|
|
||||||
return "arm64";
|
|
||||||
case "x64":
|
|
||||||
return "x64";
|
|
||||||
default:
|
|
||||||
return "other";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function* () {
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
|
||||||
const path = yield* Path.Path;
|
|
||||||
const serverConfig = yield* ServerConfig;
|
|
||||||
|
|
||||||
const readPersistedEnvironmentId = Effect.gen(function* () {
|
|
||||||
const exists = yield* fileSystem
|
|
||||||
.exists(serverConfig.environmentIdPath)
|
|
||||||
.pipe(Effect.orElseSucceed(() => false));
|
|
||||||
if (!exists) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const raw = yield* fileSystem
|
|
||||||
.readFileString(serverConfig.environmentIdPath)
|
|
||||||
.pipe(Effect.map((value) => value.trim()));
|
|
||||||
|
|
||||||
return raw.length > 0 ? raw : null;
|
|
||||||
});
|
|
||||||
|
|
||||||
const persistEnvironmentId = (value: string) =>
|
|
||||||
fileSystem.writeFileString(serverConfig.environmentIdPath, `${value}\n`);
|
|
||||||
|
|
||||||
const environmentIdRaw = yield* Effect.gen(function* () {
|
|
||||||
const persisted = yield* readPersistedEnvironmentId;
|
|
||||||
if (persisted) {
|
|
||||||
return persisted;
|
|
||||||
}
|
|
||||||
|
|
||||||
const generated = yield* Random.nextUUIDv4;
|
|
||||||
yield* persistEnvironmentId(generated);
|
|
||||||
return generated;
|
|
||||||
});
|
|
||||||
|
|
||||||
const environmentId = EnvironmentId.makeUnsafe(environmentIdRaw);
|
|
||||||
const cwdBaseName = path.basename(serverConfig.cwd).trim();
|
|
||||||
const label = yield* resolveServerEnvironmentLabel({
|
|
||||||
cwdBaseName,
|
|
||||||
});
|
|
||||||
|
|
||||||
const descriptor: ExecutionEnvironmentDescriptor = {
|
|
||||||
environmentId,
|
|
||||||
label,
|
|
||||||
platform: {
|
|
||||||
os: platformOs(),
|
|
||||||
arch: platformArch(),
|
|
||||||
},
|
|
||||||
serverVersion: version,
|
|
||||||
capabilities: {
|
|
||||||
repositoryIdentity: true,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
|
||||||
getEnvironmentId: Effect.succeed(environmentId),
|
|
||||||
getDescriptor: Effect.succeed(descriptor),
|
|
||||||
} satisfies ServerEnvironmentShape;
|
|
||||||
});
|
|
||||||
|
|
||||||
export const ServerEnvironmentLive = Layer.effect(ServerEnvironment, makeServerEnvironment());
|
|
||||||
@@ -1,150 +0,0 @@
|
|||||||
import { afterEach, describe, expect, it } from "@effect/vitest";
|
|
||||||
import { Effect, FileSystem } from "effect";
|
|
||||||
import { vi } from "vitest";
|
|
||||||
|
|
||||||
vi.mock("../../processRunner.ts", () => ({
|
|
||||||
runProcess: vi.fn(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
import { runProcess } from "../../processRunner.ts";
|
|
||||||
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
|
|
||||||
|
|
||||||
const mockedRunProcess = vi.mocked(runProcess);
|
|
||||||
const NoopFileSystemLayer = FileSystem.layerNoop({});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
mockedRunProcess.mockReset();
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("resolveServerEnvironmentLabel", () => {
|
|
||||||
it.effect("uses hostname fallback regardless of launch mode", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const result = yield* resolveServerEnvironmentLabel({
|
|
||||||
cwdBaseName: "t3code",
|
|
||||||
platform: "win32",
|
|
||||||
hostname: "macbook-pro",
|
|
||||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
|
||||||
|
|
||||||
expect(result).toBe("macbook-pro");
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("prefers the macOS ComputerName", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
mockedRunProcess.mockResolvedValueOnce({
|
|
||||||
stdout: " Julius's MacBook Pro \n",
|
|
||||||
stderr: "",
|
|
||||||
code: 0,
|
|
||||||
signal: null,
|
|
||||||
timedOut: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = yield* resolveServerEnvironmentLabel({
|
|
||||||
cwdBaseName: "t3code",
|
|
||||||
platform: "darwin",
|
|
||||||
hostname: "macbook-pro",
|
|
||||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
|
||||||
|
|
||||||
expect(result).toBe("Julius's MacBook Pro");
|
|
||||||
expect(mockedRunProcess).toHaveBeenCalledWith(
|
|
||||||
"scutil",
|
|
||||||
["--get", "ComputerName"],
|
|
||||||
expect.objectContaining({ allowNonZeroExit: true }),
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("prefers Linux PRETTY_HOSTNAME from machine-info", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const result = yield* resolveServerEnvironmentLabel({
|
|
||||||
cwdBaseName: "t3code",
|
|
||||||
platform: "linux",
|
|
||||||
hostname: "buildbox",
|
|
||||||
}).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
FileSystem.layerNoop({
|
|
||||||
exists: (path) => Effect.succeed(path === "/etc/machine-info"),
|
|
||||||
readFileString: (path) =>
|
|
||||||
path === "/etc/machine-info"
|
|
||||||
? Effect.succeed('PRETTY_HOSTNAME="Build Agent 01"\nICON_NAME="computer-vm"\n')
|
|
||||||
: Effect.succeed(""),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(result).toBe("Build Agent 01");
|
|
||||||
expect(mockedRunProcess).not.toHaveBeenCalled();
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("falls back to hostnamectl pretty hostname on Linux", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
mockedRunProcess.mockResolvedValueOnce({
|
|
||||||
stdout: "CI Runner\n",
|
|
||||||
stderr: "",
|
|
||||||
code: 0,
|
|
||||||
signal: null,
|
|
||||||
timedOut: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = yield* resolveServerEnvironmentLabel({
|
|
||||||
cwdBaseName: "t3code",
|
|
||||||
platform: "linux",
|
|
||||||
hostname: "runner-01",
|
|
||||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
|
||||||
|
|
||||||
expect(result).toBe("CI Runner");
|
|
||||||
expect(mockedRunProcess).toHaveBeenCalledWith(
|
|
||||||
"hostnamectl",
|
|
||||||
["--pretty"],
|
|
||||||
expect.objectContaining({ allowNonZeroExit: true }),
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("falls back to the hostname when friendly labels are unavailable", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const result = yield* resolveServerEnvironmentLabel({
|
|
||||||
cwdBaseName: "t3code",
|
|
||||||
platform: "win32",
|
|
||||||
hostname: "JULIUS-LAPTOP",
|
|
||||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
|
||||||
|
|
||||||
expect(result).toBe("JULIUS-LAPTOP");
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("falls back to the hostname when the friendly-label command is missing", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
mockedRunProcess.mockRejectedValueOnce(new Error("spawn scutil ENOENT"));
|
|
||||||
|
|
||||||
const result = yield* resolveServerEnvironmentLabel({
|
|
||||||
cwdBaseName: "t3code",
|
|
||||||
platform: "darwin",
|
|
||||||
hostname: "macbook-pro",
|
|
||||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
|
||||||
|
|
||||||
expect(result).toBe("macbook-pro");
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("falls back to the cwd basename when the hostname is blank", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
mockedRunProcess.mockResolvedValueOnce({
|
|
||||||
stdout: " ",
|
|
||||||
stderr: "",
|
|
||||||
code: 0,
|
|
||||||
signal: null,
|
|
||||||
timedOut: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = yield* resolveServerEnvironmentLabel({
|
|
||||||
cwdBaseName: "t3code",
|
|
||||||
platform: "linux",
|
|
||||||
hostname: " ",
|
|
||||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
|
||||||
|
|
||||||
expect(result).toBe("t3code");
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
import * as OS from "node:os";
|
|
||||||
|
|
||||||
import { Effect, FileSystem } from "effect";
|
|
||||||
|
|
||||||
import { runProcess } from "../../processRunner.ts";
|
|
||||||
|
|
||||||
interface ResolveServerEnvironmentLabelInput {
|
|
||||||
readonly cwdBaseName: string;
|
|
||||||
readonly platform?: NodeJS.Platform;
|
|
||||||
readonly hostname?: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeLabel(value: string | null | undefined): string | null {
|
|
||||||
const trimmed = value?.trim();
|
|
||||||
return trimmed && trimmed.length > 0 ? trimmed : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseMachineInfoValue(raw: string, key: string): string | null {
|
|
||||||
for (const line of raw.split(/\r?\n/g)) {
|
|
||||||
const trimmed = line.trim();
|
|
||||||
if (trimmed.length === 0 || trimmed.startsWith("#") || !trimmed.startsWith(`${key}=`)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const value = trimmed.slice(key.length + 1).trim();
|
|
||||||
if (
|
|
||||||
(value.startsWith('"') && value.endsWith('"')) ||
|
|
||||||
(value.startsWith("'") && value.endsWith("'"))
|
|
||||||
) {
|
|
||||||
return normalizeLabel(value.slice(1, -1));
|
|
||||||
}
|
|
||||||
return normalizeLabel(value);
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const readLinuxMachineInfo = Effect.fn("readLinuxMachineInfo")(function* () {
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
|
||||||
const exists = yield* fileSystem
|
|
||||||
.exists("/etc/machine-info")
|
|
||||||
.pipe(Effect.orElseSucceed(() => false));
|
|
||||||
if (!exists) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return yield* fileSystem
|
|
||||||
.readFileString("/etc/machine-info")
|
|
||||||
.pipe(Effect.orElseSucceed(() => null));
|
|
||||||
});
|
|
||||||
|
|
||||||
const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
|
|
||||||
command: string,
|
|
||||||
args: readonly string[],
|
|
||||||
) {
|
|
||||||
const result = yield* Effect.tryPromise(() =>
|
|
||||||
runProcess(command, args, {
|
|
||||||
allowNonZeroExit: true,
|
|
||||||
}),
|
|
||||||
).pipe(Effect.orElseSucceed(() => null));
|
|
||||||
|
|
||||||
if (!result || result.code !== 0) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return normalizeLabel(result.stdout);
|
|
||||||
});
|
|
||||||
|
|
||||||
const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function* (
|
|
||||||
platform: NodeJS.Platform,
|
|
||||||
) {
|
|
||||||
if (platform === "darwin") {
|
|
||||||
return yield* runFriendlyLabelCommand("scutil", ["--get", "ComputerName"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (platform === "linux") {
|
|
||||||
const machineInfo = normalizeLabel(yield* readLinuxMachineInfo());
|
|
||||||
if (machineInfo) {
|
|
||||||
const prettyHostname = parseMachineInfoValue(machineInfo, "PRETTY_HOSTNAME");
|
|
||||||
if (prettyHostname) {
|
|
||||||
return prettyHostname;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return yield* runFriendlyLabelCommand("hostnamectl", ["--pretty"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
});
|
|
||||||
|
|
||||||
export const resolveServerEnvironmentLabel = Effect.fn("resolveServerEnvironmentLabel")(function* (
|
|
||||||
input: ResolveServerEnvironmentLabelInput,
|
|
||||||
) {
|
|
||||||
const platform = input.platform ?? process.platform;
|
|
||||||
const friendlyHostLabel = yield* resolveFriendlyHostLabel(platform);
|
|
||||||
if (friendlyHostLabel) {
|
|
||||||
return friendlyHostLabel;
|
|
||||||
}
|
|
||||||
|
|
||||||
const hostname = normalizeLabel(input.hostname ?? OS.hostname());
|
|
||||||
if (hostname) {
|
|
||||||
return hostname;
|
|
||||||
}
|
|
||||||
|
|
||||||
return normalizeLabel(input.cwdBaseName) ?? "T3 environment";
|
|
||||||
});
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import type { EnvironmentId, ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
|
|
||||||
import { ServiceMap } from "effect";
|
|
||||||
import type { Effect } from "effect";
|
|
||||||
|
|
||||||
export interface ServerEnvironmentShape {
|
|
||||||
readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
|
|
||||||
readonly getDescriptor: Effect.Effect<ExecutionEnvironmentDescriptor>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class ServerEnvironment extends ServiceMap.Service<
|
|
||||||
ServerEnvironment,
|
|
||||||
ServerEnvironmentShape
|
|
||||||
>()("t3/environment/Services/ServerEnvironment") {}
|
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import { Schema } from "effect";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GitCommandError - Git command execution failed.
|
||||||
|
*/
|
||||||
|
export class GitCommandError extends Schema.TaggedErrorClass<GitCommandError>()("GitCommandError", {
|
||||||
|
operation: Schema.String,
|
||||||
|
command: Schema.String,
|
||||||
|
cwd: Schema.String,
|
||||||
|
detail: Schema.String,
|
||||||
|
cause: Schema.optional(Schema.Defect),
|
||||||
|
}) {
|
||||||
|
override get message(): string {
|
||||||
|
return `Git command failed in ${this.operation}: ${this.command} (${this.cwd}) - ${this.detail}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GitHubCliError - GitHub CLI execution or authentication failed.
|
||||||
|
*/
|
||||||
|
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
|
||||||
|
operation: Schema.String,
|
||||||
|
detail: Schema.String,
|
||||||
|
cause: Schema.optional(Schema.Defect),
|
||||||
|
}) {
|
||||||
|
override get message(): string {
|
||||||
|
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TextGenerationError - Commit or PR text generation failed.
|
||||||
|
*/
|
||||||
|
export class TextGenerationError extends Schema.TaggedErrorClass<TextGenerationError>()(
|
||||||
|
"TextGenerationError",
|
||||||
|
{
|
||||||
|
operation: Schema.String,
|
||||||
|
detail: Schema.String,
|
||||||
|
cause: Schema.optional(Schema.Defect),
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
override get message(): string {
|
||||||
|
return `Text generation failed in ${this.operation}: ${this.detail}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GitManagerError - Stacked Git workflow orchestration failed.
|
||||||
|
*/
|
||||||
|
export class GitManagerError extends Schema.TaggedErrorClass<GitManagerError>()("GitManagerError", {
|
||||||
|
operation: Schema.String,
|
||||||
|
detail: Schema.String,
|
||||||
|
cause: Schema.optional(Schema.Defect),
|
||||||
|
}) {
|
||||||
|
override get message(): string {
|
||||||
|
return `Git manager failed in ${this.operation}: ${this.detail}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GitManagerServiceError - Errors emitted by stacked Git workflow orchestration.
|
||||||
|
*/
|
||||||
|
export type GitManagerServiceError =
|
||||||
|
| GitManagerError
|
||||||
|
| GitCommandError
|
||||||
|
| GitHubCliError
|
||||||
|
| TextGenerationError;
|
||||||
@@ -1,309 +0,0 @@
|
|||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import { it } from "@effect/vitest";
|
|
||||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
|
||||||
import { expect } from "vitest";
|
|
||||||
|
|
||||||
import { ServerConfig } from "../../config.ts";
|
|
||||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
|
||||||
import { sanitizeThreadTitle } from "../Utils.ts";
|
|
||||||
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
|
|
||||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
|
||||||
|
|
||||||
const ClaudeTextGenerationTestLayer = ClaudeTextGenerationLive.pipe(
|
|
||||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
|
||||||
Layer.provideMerge(
|
|
||||||
ServerConfig.layerTest(process.cwd(), {
|
|
||||||
prefix: "t3code-claude-text-generation-test-",
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
Layer.provideMerge(NodeServices.layer),
|
|
||||||
);
|
|
||||||
|
|
||||||
function makeFakeClaudeBinary(dir: string) {
|
|
||||||
return Effect.gen(function* () {
|
|
||||||
const fs = yield* FileSystem.FileSystem;
|
|
||||||
const path = yield* Path.Path;
|
|
||||||
const binDir = path.join(dir, "bin");
|
|
||||||
const claudePath = path.join(binDir, "claude");
|
|
||||||
yield* fs.makeDirectory(binDir, { recursive: true });
|
|
||||||
|
|
||||||
yield* fs.writeFileString(
|
|
||||||
claudePath,
|
|
||||||
[
|
|
||||||
"#!/bin/sh",
|
|
||||||
'args="$*"',
|
|
||||||
'stdin_content="$(cat)"',
|
|
||||||
'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" ]; then',
|
|
||||||
' printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" >/dev/null || {',
|
|
||||||
' printf "%s\\n" "args missing expected content" >&2',
|
|
||||||
" exit 2",
|
|
||||||
" }",
|
|
||||||
"fi",
|
|
||||||
'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" ]; then',
|
|
||||||
' if printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" >/dev/null; then',
|
|
||||||
' printf "%s\\n" "args contained forbidden content" >&2',
|
|
||||||
" exit 3",
|
|
||||||
" fi",
|
|
||||||
"fi",
|
|
||||||
'if [ -n "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" ]; then',
|
|
||||||
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" >/dev/null || {',
|
|
||||||
' printf "%s\\n" "stdin missing expected content" >&2',
|
|
||||||
" exit 4",
|
|
||||||
" }",
|
|
||||||
"fi",
|
|
||||||
'if [ -n "$T3_FAKE_CLAUDE_STDERR" ]; then',
|
|
||||||
' printf "%s\\n" "$T3_FAKE_CLAUDE_STDERR" >&2',
|
|
||||||
"fi",
|
|
||||||
'printf "%s" "$T3_FAKE_CLAUDE_OUTPUT"',
|
|
||||||
'exit "${T3_FAKE_CLAUDE_EXIT_CODE:-0}"',
|
|
||||||
"",
|
|
||||||
].join("\n"),
|
|
||||||
);
|
|
||||||
yield* fs.chmod(claudePath, 0o755);
|
|
||||||
return binDir;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function withFakeClaudeEnv<A, E, R>(
|
|
||||||
input: {
|
|
||||||
output: string;
|
|
||||||
exitCode?: number;
|
|
||||||
stderr?: string;
|
|
||||||
argsMustContain?: string;
|
|
||||||
argsMustNotContain?: string;
|
|
||||||
stdinMustContain?: string;
|
|
||||||
},
|
|
||||||
effect: Effect.Effect<A, E, R>,
|
|
||||||
) {
|
|
||||||
return Effect.acquireUseRelease(
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const fs = yield* FileSystem.FileSystem;
|
|
||||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });
|
|
||||||
const binDir = yield* makeFakeClaudeBinary(tempDir);
|
|
||||||
const previousPath = process.env.PATH;
|
|
||||||
const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT;
|
|
||||||
const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE;
|
|
||||||
const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR;
|
|
||||||
const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
|
|
||||||
const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
|
|
||||||
const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
|
|
||||||
|
|
||||||
yield* Effect.sync(() => {
|
|
||||||
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
|
|
||||||
process.env.T3_FAKE_CLAUDE_OUTPUT = input.output;
|
|
||||||
|
|
||||||
if (input.exitCode !== undefined) {
|
|
||||||
process.env.T3_FAKE_CLAUDE_EXIT_CODE = String(input.exitCode);
|
|
||||||
} else {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (input.stderr !== undefined) {
|
|
||||||
process.env.T3_FAKE_CLAUDE_STDERR = input.stderr;
|
|
||||||
} else {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_STDERR;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (input.argsMustContain !== undefined) {
|
|
||||||
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = input.argsMustContain;
|
|
||||||
} else {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (input.argsMustNotContain !== undefined) {
|
|
||||||
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = input.argsMustNotContain;
|
|
||||||
} else {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (input.stdinMustContain !== undefined) {
|
|
||||||
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = input.stdinMustContain;
|
|
||||||
} else {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
previousPath,
|
|
||||||
previousOutput,
|
|
||||||
previousExitCode,
|
|
||||||
previousStderr,
|
|
||||||
previousArgsMustContain,
|
|
||||||
previousArgsMustNotContain,
|
|
||||||
previousStdinMustContain,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
() => effect,
|
|
||||||
(previous) =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
process.env.PATH = previous.previousPath;
|
|
||||||
|
|
||||||
if (previous.previousOutput === undefined) {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_OUTPUT;
|
|
||||||
} else {
|
|
||||||
process.env.T3_FAKE_CLAUDE_OUTPUT = previous.previousOutput;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (previous.previousExitCode === undefined) {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
|
|
||||||
} else {
|
|
||||||
process.env.T3_FAKE_CLAUDE_EXIT_CODE = previous.previousExitCode;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (previous.previousStderr === undefined) {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_STDERR;
|
|
||||||
} else {
|
|
||||||
process.env.T3_FAKE_CLAUDE_STDERR = previous.previousStderr;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (previous.previousArgsMustContain === undefined) {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
|
|
||||||
} else {
|
|
||||||
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previous.previousArgsMustContain;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (previous.previousArgsMustNotContain === undefined) {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
|
|
||||||
} else {
|
|
||||||
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previous.previousArgsMustNotContain;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (previous.previousStdinMustContain === undefined) {
|
|
||||||
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
|
|
||||||
} else {
|
|
||||||
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
|
|
||||||
it.effect("forwards Claude thinking settings for Haiku without passing effort", () =>
|
|
||||||
withFakeClaudeEnv(
|
|
||||||
{
|
|
||||||
output: JSON.stringify({
|
|
||||||
structured_output: {
|
|
||||||
subject: "Add important change",
|
|
||||||
body: "",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
argsMustContain: '--settings {"alwaysThinkingEnabled":false}',
|
|
||||||
argsMustNotContain: "--effort",
|
|
||||||
},
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const textGeneration = yield* TextGeneration;
|
|
||||||
|
|
||||||
const generated = yield* textGeneration.generateCommitMessage({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
branch: "feature/claude-effect",
|
|
||||||
stagedSummary: "M README.md",
|
|
||||||
stagedPatch: "diff --git a/README.md b/README.md",
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-haiku-4-5",
|
|
||||||
options: {
|
|
||||||
thinking: false,
|
|
||||||
effort: "high",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(generated.subject).toBe("Add important change");
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("forwards Claude fast mode and supported effort", () =>
|
|
||||||
withFakeClaudeEnv(
|
|
||||||
{
|
|
||||||
output: JSON.stringify({
|
|
||||||
structured_output: {
|
|
||||||
title: "Improve orchestration flow",
|
|
||||||
body: "Body",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
argsMustContain: '--effort max --settings {"fastMode":true}',
|
|
||||||
},
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const textGeneration = yield* TextGeneration;
|
|
||||||
|
|
||||||
const generated = yield* textGeneration.generatePrContent({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
baseBranch: "main",
|
|
||||||
headBranch: "feature/claude-effect",
|
|
||||||
commitSummary: "Improve orchestration",
|
|
||||||
diffSummary: "1 file changed",
|
|
||||||
diffPatch: "diff --git a/README.md b/README.md",
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-opus-4-6",
|
|
||||||
options: {
|
|
||||||
effort: "max",
|
|
||||||
fastMode: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(generated.title).toBe("Improve orchestration flow");
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("generates thread titles through the Claude provider", () =>
|
|
||||||
withFakeClaudeEnv(
|
|
||||||
{
|
|
||||||
output: JSON.stringify({
|
|
||||||
structured_output: {
|
|
||||||
title:
|
|
||||||
' "Reconnect failures after restart because the session state does not recover" ',
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
stdinMustContain: "You write concise thread titles for coding conversations.",
|
|
||||||
},
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const textGeneration = yield* TextGeneration;
|
|
||||||
|
|
||||||
const generated = yield* textGeneration.generateThreadTitle({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
message: "Please investigate reconnect failures after restarting the session.",
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(generated.title).toBe(
|
|
||||||
sanitizeThreadTitle(
|
|
||||||
'"Reconnect failures after restart because the session state does not recover"',
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>
|
|
||||||
withFakeClaudeEnv(
|
|
||||||
{
|
|
||||||
output: JSON.stringify({
|
|
||||||
structured_output: {
|
|
||||||
title: ' """ """ ',
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const textGeneration = yield* TextGeneration;
|
|
||||||
|
|
||||||
const generated = yield* textGeneration.generateThreadTitle({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
message: "Name this thread.",
|
|
||||||
modelSelection: {
|
|
||||||
provider: "claudeAgent",
|
|
||||||
model: "claude-sonnet-4-6",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(generated.title).toBe("New thread");
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,339 +0,0 @@
|
|||||||
/**
|
|
||||||
* ClaudeTextGeneration – Text generation layer using the Claude CLI.
|
|
||||||
*
|
|
||||||
* Implements the same TextGenerationShape contract as CodexTextGeneration but
|
|
||||||
* delegates to the `claude` CLI (`claude -p`) with structured JSON output
|
|
||||||
* instead of the `codex exec` CLI.
|
|
||||||
*
|
|
||||||
* @module ClaudeTextGeneration
|
|
||||||
*/
|
|
||||||
import { Effect, Layer, Option, Schema, Stream } from "effect";
|
|
||||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
|
||||||
|
|
||||||
import { ClaudeModelSelection } from "@t3tools/contracts";
|
|
||||||
import { resolveApiModelId } from "@t3tools/shared/model";
|
|
||||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
|
||||||
|
|
||||||
import { TextGenerationError } from "@t3tools/contracts";
|
|
||||||
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
|
|
||||||
import {
|
|
||||||
buildBranchNamePrompt,
|
|
||||||
buildCommitMessagePrompt,
|
|
||||||
buildPrContentPrompt,
|
|
||||||
buildThreadTitlePrompt,
|
|
||||||
} from "../Prompts.ts";
|
|
||||||
import {
|
|
||||||
normalizeCliError,
|
|
||||||
sanitizeCommitSubject,
|
|
||||||
sanitizePrTitle,
|
|
||||||
sanitizeThreadTitle,
|
|
||||||
toJsonSchemaObject,
|
|
||||||
} from "../Utils.ts";
|
|
||||||
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
|
|
||||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
|
||||||
import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts";
|
|
||||||
|
|
||||||
const CLAUDE_TIMEOUT_MS = 180_000;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Schema for the wrapper JSON returned by `claude -p --output-format json`.
|
|
||||||
* We only care about `structured_output`.
|
|
||||||
*/
|
|
||||||
const ClaudeOutputEnvelope = Schema.Struct({
|
|
||||||
structured_output: Schema.Unknown,
|
|
||||||
});
|
|
||||||
|
|
||||||
const makeClaudeTextGeneration = Effect.gen(function* () {
|
|
||||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
|
||||||
const serverSettingsService = yield* Effect.service(ServerSettingsService);
|
|
||||||
|
|
||||||
const readStreamAsString = <E>(
|
|
||||||
operation: string,
|
|
||||||
stream: Stream.Stream<Uint8Array, E>,
|
|
||||||
): Effect.Effect<string, TextGenerationError> =>
|
|
||||||
stream.pipe(
|
|
||||||
Stream.decodeText(),
|
|
||||||
Stream.runFold(
|
|
||||||
() => "",
|
|
||||||
(acc, chunk) => acc + chunk,
|
|
||||||
),
|
|
||||||
Effect.mapError((cause) =>
|
|
||||||
normalizeCliError("claude", operation, cause, "Failed to collect process output"),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Spawn the Claude CLI with structured JSON output and return the parsed,
|
|
||||||
* schema-validated result.
|
|
||||||
*/
|
|
||||||
const runClaudeJson = Effect.fn("runClaudeJson")(function* <S extends Schema.Top>({
|
|
||||||
operation,
|
|
||||||
cwd,
|
|
||||||
prompt,
|
|
||||||
outputSchemaJson,
|
|
||||||
modelSelection,
|
|
||||||
}: {
|
|
||||||
operation:
|
|
||||||
| "generateCommitMessage"
|
|
||||||
| "generatePrContent"
|
|
||||||
| "generateBranchName"
|
|
||||||
| "generateThreadTitle";
|
|
||||||
cwd: string;
|
|
||||||
prompt: string;
|
|
||||||
outputSchemaJson: S;
|
|
||||||
modelSelection: ClaudeModelSelection;
|
|
||||||
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
|
||||||
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
|
|
||||||
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
|
|
||||||
getClaudeModelCapabilities(modelSelection.model),
|
|
||||||
modelSelection.options,
|
|
||||||
);
|
|
||||||
const settings = {
|
|
||||||
...(typeof normalizedOptions?.thinking === "boolean"
|
|
||||||
? { alwaysThinkingEnabled: normalizedOptions.thinking }
|
|
||||||
: {}),
|
|
||||||
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
|
|
||||||
};
|
|
||||||
|
|
||||||
const claudeSettings = yield* Effect.map(
|
|
||||||
serverSettingsService.getSettings,
|
|
||||||
(settings) => settings.providers.claudeAgent,
|
|
||||||
).pipe(Effect.catch(() => Effect.undefined));
|
|
||||||
|
|
||||||
const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
|
|
||||||
const command = ChildProcess.make(
|
|
||||||
claudeSettings?.binaryPath || "claude",
|
|
||||||
[
|
|
||||||
"-p",
|
|
||||||
"--output-format",
|
|
||||||
"json",
|
|
||||||
"--json-schema",
|
|
||||||
jsonSchemaStr,
|
|
||||||
"--model",
|
|
||||||
resolveApiModelId(modelSelection),
|
|
||||||
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
|
|
||||||
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
|
|
||||||
"--dangerously-skip-permissions",
|
|
||||||
],
|
|
||||||
{
|
|
||||||
cwd,
|
|
||||||
shell: process.platform === "win32",
|
|
||||||
stdin: {
|
|
||||||
stream: Stream.encodeText(Stream.make(prompt)),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
const child = yield* commandSpawner
|
|
||||||
.spawn(command)
|
|
||||||
.pipe(
|
|
||||||
Effect.mapError((cause) =>
|
|
||||||
normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
|
||||||
[
|
|
||||||
readStreamAsString(operation, child.stdout),
|
|
||||||
readStreamAsString(operation, child.stderr),
|
|
||||||
child.exitCode.pipe(
|
|
||||||
Effect.mapError((cause) =>
|
|
||||||
normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
{ 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
|
|
||||||
? `Claude CLI command failed: ${detail}`
|
|
||||||
: `Claude CLI command failed with code ${exitCode}.`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return stdout;
|
|
||||||
});
|
|
||||||
|
|
||||||
const rawStdout = yield* runClaudeCommand().pipe(
|
|
||||||
Effect.scoped,
|
|
||||||
Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
|
|
||||||
Effect.flatMap(
|
|
||||||
Option.match({
|
|
||||||
onNone: () =>
|
|
||||||
Effect.fail(
|
|
||||||
new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
|
|
||||||
),
|
|
||||||
onSome: (value) => Effect.succeed(value),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
|
|
||||||
rawStdout,
|
|
||||||
).pipe(
|
|
||||||
Effect.catchTag("SchemaError", (cause) =>
|
|
||||||
Effect.fail(
|
|
||||||
new TextGenerationError({
|
|
||||||
operation,
|
|
||||||
detail: "Claude CLI returned unexpected output format.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
|
|
||||||
Effect.catchTag("SchemaError", (cause) =>
|
|
||||||
Effect.fail(
|
|
||||||
new TextGenerationError({
|
|
||||||
operation,
|
|
||||||
detail: "Claude returned invalid structured output.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// TextGenerationShape methods
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
|
|
||||||
"ClaudeTextGeneration.generateCommitMessage",
|
|
||||||
)(function* (input) {
|
|
||||||
const { prompt, outputSchema } = buildCommitMessagePrompt({
|
|
||||||
branch: input.branch,
|
|
||||||
stagedSummary: input.stagedSummary,
|
|
||||||
stagedPatch: input.stagedPatch,
|
|
||||||
includeBranch: input.includeBranch === true,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (input.modelSelection.provider !== "claudeAgent") {
|
|
||||||
return yield* new TextGenerationError({
|
|
||||||
operation: "generateCommitMessage",
|
|
||||||
detail: "Invalid model selection.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const generated = yield* runClaudeJson({
|
|
||||||
operation: "generateCommitMessage",
|
|
||||||
cwd: input.cwd,
|
|
||||||
prompt,
|
|
||||||
outputSchemaJson: outputSchema,
|
|
||||||
modelSelection: input.modelSelection,
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
subject: sanitizeCommitSubject(generated.subject),
|
|
||||||
body: generated.body.trim(),
|
|
||||||
...("branch" in generated && typeof generated.branch === "string"
|
|
||||||
? { branch: sanitizeFeatureBranchName(generated.branch) }
|
|
||||||
: {}),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
|
|
||||||
"ClaudeTextGeneration.generatePrContent",
|
|
||||||
)(function* (input) {
|
|
||||||
const { prompt, outputSchema } = buildPrContentPrompt({
|
|
||||||
baseBranch: input.baseBranch,
|
|
||||||
headBranch: input.headBranch,
|
|
||||||
commitSummary: input.commitSummary,
|
|
||||||
diffSummary: input.diffSummary,
|
|
||||||
diffPatch: input.diffPatch,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (input.modelSelection.provider !== "claudeAgent") {
|
|
||||||
return yield* new TextGenerationError({
|
|
||||||
operation: "generatePrContent",
|
|
||||||
detail: "Invalid model selection.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const generated = yield* runClaudeJson({
|
|
||||||
operation: "generatePrContent",
|
|
||||||
cwd: input.cwd,
|
|
||||||
prompt,
|
|
||||||
outputSchemaJson: outputSchema,
|
|
||||||
modelSelection: input.modelSelection,
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
title: sanitizePrTitle(generated.title),
|
|
||||||
body: generated.body.trim(),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
|
|
||||||
"ClaudeTextGeneration.generateBranchName",
|
|
||||||
)(function* (input) {
|
|
||||||
const { prompt, outputSchema } = buildBranchNamePrompt({
|
|
||||||
message: input.message,
|
|
||||||
attachments: input.attachments,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (input.modelSelection.provider !== "claudeAgent") {
|
|
||||||
return yield* new TextGenerationError({
|
|
||||||
operation: "generateBranchName",
|
|
||||||
detail: "Invalid model selection.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const generated = yield* runClaudeJson({
|
|
||||||
operation: "generateBranchName",
|
|
||||||
cwd: input.cwd,
|
|
||||||
prompt,
|
|
||||||
outputSchemaJson: outputSchema,
|
|
||||||
modelSelection: input.modelSelection,
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
branch: sanitizeBranchFragment(generated.branch),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
|
|
||||||
"ClaudeTextGeneration.generateThreadTitle",
|
|
||||||
)(function* (input) {
|
|
||||||
const { prompt, outputSchema } = buildThreadTitlePrompt({
|
|
||||||
message: input.message,
|
|
||||||
attachments: input.attachments,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (input.modelSelection.provider !== "claudeAgent") {
|
|
||||||
return yield* new TextGenerationError({
|
|
||||||
operation: "generateThreadTitle",
|
|
||||||
detail: "Invalid model selection.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const generated = yield* runClaudeJson({
|
|
||||||
operation: "generateThreadTitle",
|
|
||||||
cwd: input.cwd,
|
|
||||||
prompt,
|
|
||||||
outputSchemaJson: outputSchema,
|
|
||||||
modelSelection: input.modelSelection,
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
title: sanitizeThreadTitle(generated.title),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
generateCommitMessage,
|
|
||||||
generatePrContent,
|
|
||||||
generateBranchName,
|
|
||||||
generateThreadTitle,
|
|
||||||
} satisfies TextGenerationShape;
|
|
||||||
});
|
|
||||||
|
|
||||||
export const ClaudeTextGenerationLive = Layer.effect(TextGeneration, makeClaudeTextGeneration);
|
|
||||||
@@ -1,43 +1,20 @@
|
|||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
import { it } from "@effect/vitest";
|
import { it } from "@effect/vitest";
|
||||||
import { Effect, FileSystem, Layer, Path, Result } from "effect";
|
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||||
import { expect } from "vitest";
|
import { expect } from "vitest";
|
||||||
|
|
||||||
import { ServerConfig } from "../../config.ts";
|
import { ServerConfig } from "../../config.ts";
|
||||||
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||||
import { TextGenerationError } from "@t3tools/contracts";
|
import { TextGenerationError } from "../Errors.ts";
|
||||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
|
||||||
|
|
||||||
const DEFAULT_TEST_MODEL_SELECTION = {
|
const makeCodexTextGenerationTestLayer = (stateDir: string) =>
|
||||||
provider: "codex" as const,
|
CodexTextGenerationLive.pipe(
|
||||||
model: "gpt-5.4-mini",
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
|
||||||
};
|
Layer.provideMerge(NodeServices.layer),
|
||||||
|
);
|
||||||
|
|
||||||
const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
|
function makeFakeCodexBinary(dir: string) {
|
||||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
|
||||||
Layer.provideMerge(
|
|
||||||
ServerConfig.layerTest(process.cwd(), {
|
|
||||||
prefix: "t3code-codex-text-generation-test-",
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
Layer.provideMerge(NodeServices.layer),
|
|
||||||
);
|
|
||||||
|
|
||||||
function makeFakeCodexBinary(
|
|
||||||
dir: string,
|
|
||||||
input: {
|
|
||||||
output: string;
|
|
||||||
exitCode?: number;
|
|
||||||
stderr?: string;
|
|
||||||
requireImage?: boolean;
|
|
||||||
requireFastServiceTier?: boolean;
|
|
||||||
requireReasoningEffort?: string;
|
|
||||||
forbidReasoningEffort?: boolean;
|
|
||||||
stdinMustContain?: string;
|
|
||||||
stdinMustNotContain?: string;
|
|
||||||
},
|
|
||||||
) {
|
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
@@ -50,102 +27,49 @@ function makeFakeCodexBinary(
|
|||||||
[
|
[
|
||||||
"#!/bin/sh",
|
"#!/bin/sh",
|
||||||
'output_path=""',
|
'output_path=""',
|
||||||
'seen_image="0"',
|
|
||||||
'seen_fast_service_tier="0"',
|
|
||||||
'seen_reasoning_effort=""',
|
|
||||||
"while [ $# -gt 0 ]; do",
|
"while [ $# -gt 0 ]; do",
|
||||||
' if [ "$1" = "--image" ]; then',
|
' if [ "$1" = "--image" ]; then',
|
||||||
" shift",
|
" shift",
|
||||||
' if [ -n "$1" ]; then',
|
' if [ -n "$1" ]; then',
|
||||||
' seen_image="1"',
|
' seen_image="1"',
|
||||||
" fi",
|
" fi",
|
||||||
" shift",
|
|
||||||
" continue",
|
|
||||||
" fi",
|
|
||||||
' if [ "$1" = "--config" ]; then',
|
|
||||||
" shift",
|
|
||||||
' if [ "$1" = "service_tier=\\"fast\\"" ]; then',
|
|
||||||
' seen_fast_service_tier="1"',
|
|
||||||
" fi",
|
|
||||||
' case "$1" in',
|
|
||||||
" model_reasoning_effort=*)",
|
|
||||||
' seen_reasoning_effort="$1"',
|
|
||||||
" ;;",
|
|
||||||
" esac",
|
|
||||||
" shift",
|
|
||||||
" continue",
|
" continue",
|
||||||
" fi",
|
" fi",
|
||||||
' if [ "$1" = "--output-last-message" ]; then',
|
' if [ "$1" = "--output-last-message" ]; then',
|
||||||
" shift",
|
" shift",
|
||||||
' output_path="$1"',
|
' output_path="$1"',
|
||||||
" shift",
|
|
||||||
" continue",
|
|
||||||
" fi",
|
" fi",
|
||||||
" shift",
|
" shift",
|
||||||
"done",
|
"done",
|
||||||
'stdin_content="$(cat)"',
|
'stdin_content="$(cat)"',
|
||||||
...(input.requireImage
|
'if [ "$T3_FAKE_CODEX_REQUIRE_IMAGE" = "1" ] && [ "$seen_image" != "1" ]; then',
|
||||||
? [
|
' printf "%s\\n" "missing --image input" >&2',
|
||||||
'if [ "$seen_image" != "1" ]; then',
|
" exit 2",
|
||||||
' printf "%s\\n" "missing --image input" >&2',
|
|
||||||
` exit 2`,
|
|
||||||
"fi",
|
|
||||||
]
|
|
||||||
: []),
|
|
||||||
...(input.requireFastServiceTier
|
|
||||||
? [
|
|
||||||
'if [ "$seen_fast_service_tier" != "1" ]; then',
|
|
||||||
' printf "%s\\n" "missing fast service tier config" >&2',
|
|
||||||
` exit 5`,
|
|
||||||
"fi",
|
|
||||||
]
|
|
||||||
: []),
|
|
||||||
...(input.requireReasoningEffort !== undefined
|
|
||||||
? [
|
|
||||||
`if [ "$seen_reasoning_effort" != "model_reasoning_effort=\\"${input.requireReasoningEffort}\\"" ]; then`,
|
|
||||||
' printf "%s\\n" "unexpected reasoning effort config: $seen_reasoning_effort" >&2',
|
|
||||||
` exit 6`,
|
|
||||||
"fi",
|
|
||||||
]
|
|
||||||
: []),
|
|
||||||
...(input.forbidReasoningEffort
|
|
||||||
? [
|
|
||||||
'if [ -n "$seen_reasoning_effort" ]; then',
|
|
||||||
' printf "%s\\n" "reasoning effort config should be omitted: $seen_reasoning_effort" >&2',
|
|
||||||
` exit 7`,
|
|
||||||
"fi",
|
|
||||||
]
|
|
||||||
: []),
|
|
||||||
...(input.stdinMustContain !== undefined
|
|
||||||
? [
|
|
||||||
`if ! printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustContain)} >/dev/null; then`,
|
|
||||||
' printf "%s\\n" "stdin missing expected content" >&2',
|
|
||||||
` exit 3`,
|
|
||||||
"fi",
|
|
||||||
]
|
|
||||||
: []),
|
|
||||||
...(input.stdinMustNotContain !== undefined
|
|
||||||
? [
|
|
||||||
`if printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustNotContain)} >/dev/null; then`,
|
|
||||||
' printf "%s\\n" "stdin contained forbidden content" >&2',
|
|
||||||
` exit 4`,
|
|
||||||
"fi",
|
|
||||||
]
|
|
||||||
: []),
|
|
||||||
...(input.stderr !== undefined
|
|
||||||
? [`printf "%s\\n" ${JSON.stringify(input.stderr)} >&2`]
|
|
||||||
: []),
|
|
||||||
'if [ -n "$output_path" ]; then',
|
|
||||||
" cat > \"$output_path\" <<'__T3CODE_FAKE_CODEX_OUTPUT__'",
|
|
||||||
input.output,
|
|
||||||
"__T3CODE_FAKE_CODEX_OUTPUT__",
|
|
||||||
"fi",
|
"fi",
|
||||||
`exit ${input.exitCode ?? 0}`,
|
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" ]; then',
|
||||||
|
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" >/dev/null || {',
|
||||||
|
' printf "%s\\n" "stdin missing expected content" >&2',
|
||||||
|
" exit 3",
|
||||||
|
" }",
|
||||||
|
"fi",
|
||||||
|
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" ]; then',
|
||||||
|
' if printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" >/dev/null; then',
|
||||||
|
' printf "%s\\n" "stdin contained forbidden content" >&2',
|
||||||
|
" exit 4",
|
||||||
|
" fi",
|
||||||
|
"fi",
|
||||||
|
'if [ -n "$T3_FAKE_CODEX_STDERR" ]; then',
|
||||||
|
' printf "%s\\n" "$T3_FAKE_CODEX_STDERR" >&2',
|
||||||
|
"fi",
|
||||||
|
'if [ -n "$output_path" ]; then',
|
||||||
|
' node -e \'const fs=require("node:fs"); const value=process.argv[2] ?? ""; fs.writeFileSync(process.argv[1], Buffer.from(value, "base64"));\' "$output_path" "${T3_FAKE_CODEX_OUTPUT_B64:-e30=}"',
|
||||||
|
"fi",
|
||||||
|
'exit "${T3_FAKE_CODEX_EXIT_CODE:-0}"',
|
||||||
"",
|
"",
|
||||||
].join("\n"),
|
].join("\n"),
|
||||||
);
|
);
|
||||||
yield* fs.chmod(codexPath, 0o755);
|
yield* fs.chmod(codexPath, 0o755);
|
||||||
return codexPath;
|
return binDir;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -155,9 +79,6 @@ function withFakeCodexEnv<A, E, R>(
|
|||||||
exitCode?: number;
|
exitCode?: number;
|
||||||
stderr?: string;
|
stderr?: string;
|
||||||
requireImage?: boolean;
|
requireImage?: boolean;
|
||||||
requireFastServiceTier?: boolean;
|
|
||||||
requireReasoningEffort?: string;
|
|
||||||
forbidReasoningEffort?: boolean;
|
|
||||||
stdinMustContain?: string;
|
stdinMustContain?: string;
|
||||||
stdinMustNotContain?: string;
|
stdinMustNotContain?: string;
|
||||||
},
|
},
|
||||||
@@ -167,32 +88,106 @@ function withFakeCodexEnv<A, E, R>(
|
|||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
|
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
|
||||||
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
|
const binDir = yield* makeFakeCodexBinary(tempDir);
|
||||||
const serverSettings = yield* ServerSettingsService;
|
const previousPath = process.env.PATH;
|
||||||
const previousSettings = yield* serverSettings.getSettings;
|
const previousOutput = process.env.T3_FAKE_CODEX_OUTPUT_B64;
|
||||||
yield* serverSettings.updateSettings({
|
const previousExitCode = process.env.T3_FAKE_CODEX_EXIT_CODE;
|
||||||
providers: {
|
const previousStderr = process.env.T3_FAKE_CODEX_STDERR;
|
||||||
codex: {
|
const previousRequireImage = process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||||
binaryPath: codexPath,
|
const previousStdinMustContain = process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
||||||
},
|
const previousStdinMustNotContain = process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
||||||
},
|
|
||||||
|
yield* Effect.sync(() => {
|
||||||
|
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
|
||||||
|
process.env.T3_FAKE_CODEX_OUTPUT_B64 = Buffer.from(input.output, "utf8").toString("base64");
|
||||||
|
|
||||||
|
if (input.exitCode !== undefined) {
|
||||||
|
process.env.T3_FAKE_CODEX_EXIT_CODE = String(input.exitCode);
|
||||||
|
} else {
|
||||||
|
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.stderr !== undefined) {
|
||||||
|
process.env.T3_FAKE_CODEX_STDERR = input.stderr;
|
||||||
|
} else {
|
||||||
|
delete process.env.T3_FAKE_CODEX_STDERR;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.requireImage) {
|
||||||
|
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = "1";
|
||||||
|
} else {
|
||||||
|
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.stdinMustContain !== undefined) {
|
||||||
|
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = input.stdinMustContain;
|
||||||
|
} else {
|
||||||
|
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.stdinMustNotContain !== undefined) {
|
||||||
|
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = input.stdinMustNotContain;
|
||||||
|
} else {
|
||||||
|
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
return { serverSettings, previousBinaryPath: previousSettings.providers.codex.binaryPath };
|
|
||||||
|
return {
|
||||||
|
previousPath,
|
||||||
|
previousOutput,
|
||||||
|
previousExitCode,
|
||||||
|
previousStderr,
|
||||||
|
previousRequireImage,
|
||||||
|
previousStdinMustContain,
|
||||||
|
previousStdinMustNotContain,
|
||||||
|
};
|
||||||
}),
|
}),
|
||||||
() => effect,
|
() => effect,
|
||||||
({ serverSettings, previousBinaryPath }) =>
|
(previous) =>
|
||||||
serverSettings
|
Effect.sync(() => {
|
||||||
.updateSettings({
|
process.env.PATH = previous.previousPath;
|
||||||
providers: {
|
|
||||||
codex: {
|
if (previous.previousOutput === undefined) {
|
||||||
binaryPath: previousBinaryPath,
|
delete process.env.T3_FAKE_CODEX_OUTPUT_B64;
|
||||||
},
|
} else {
|
||||||
},
|
process.env.T3_FAKE_CODEX_OUTPUT_B64 = previous.previousOutput;
|
||||||
})
|
}
|
||||||
.pipe(Effect.asVoid),
|
|
||||||
|
if (previous.previousExitCode === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CODEX_EXIT_CODE = previous.previousExitCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previous.previousStderr === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CODEX_STDERR;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CODEX_STDERR = previous.previousStderr;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previous.previousRequireImage === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = previous.previousRequireImage;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previous.previousStdinMustContain === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previous.previousStdinMustNotContain === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = previous.previousStdinMustNotContain;
|
||||||
|
}
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const CodexTextGenerationTestLayer = makeCodexTextGenerationTestLayer(process.cwd());
|
||||||
|
|
||||||
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||||
it.effect("generates and sanitizes commit messages without branch by default", () =>
|
it.effect("generates and sanitizes commit messages without branch by default", () =>
|
||||||
withFakeCodexEnv(
|
withFakeCodexEnv(
|
||||||
@@ -212,7 +207,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
branch: "feature/codex-effect",
|
branch: "feature/codex-effect",
|
||||||
stagedSummary: "M README.md",
|
stagedSummary: "M README.md",
|
||||||
stagedPatch: "diff --git a/README.md b/README.md",
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(generated.subject.length).toBeLessThanOrEqual(72);
|
expect(generated.subject.length).toBeLessThanOrEqual(72);
|
||||||
@@ -223,63 +217,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.effect(
|
|
||||||
"forwards codex fast mode and non-default reasoning effort into codex exec config",
|
|
||||||
() =>
|
|
||||||
withFakeCodexEnv(
|
|
||||||
{
|
|
||||||
output: JSON.stringify({
|
|
||||||
subject: "Add important change",
|
|
||||||
body: "",
|
|
||||||
}),
|
|
||||||
requireFastServiceTier: true,
|
|
||||||
requireReasoningEffort: "xhigh",
|
|
||||||
stdinMustNotContain: "branch must be a short semantic git branch fragment",
|
|
||||||
},
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const textGeneration = yield* TextGeneration;
|
|
||||||
|
|
||||||
yield* textGeneration.generateCommitMessage({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
branch: "feature/codex-effect",
|
|
||||||
stagedSummary: "M README.md",
|
|
||||||
stagedPatch: "diff --git a/README.md b/README.md",
|
|
||||||
modelSelection: {
|
|
||||||
provider: "codex",
|
|
||||||
model: "gpt-5.4",
|
|
||||||
options: {
|
|
||||||
reasoningEffort: "xhigh",
|
|
||||||
fastMode: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("defaults git text generation codex effort to low", () =>
|
|
||||||
withFakeCodexEnv(
|
|
||||||
{
|
|
||||||
output: JSON.stringify({
|
|
||||||
subject: "Add important change",
|
|
||||||
body: "",
|
|
||||||
}),
|
|
||||||
requireReasoningEffort: "low",
|
|
||||||
},
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const textGeneration = yield* TextGeneration;
|
|
||||||
|
|
||||||
yield* textGeneration.generateCommitMessage({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
branch: "feature/codex-effect",
|
|
||||||
stagedSummary: "M README.md",
|
|
||||||
stagedPatch: "diff --git a/README.md b/README.md",
|
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("generates commit message with branch when includeBranch is true", () =>
|
it.effect("generates commit message with branch when includeBranch is true", () =>
|
||||||
withFakeCodexEnv(
|
withFakeCodexEnv(
|
||||||
{
|
{
|
||||||
@@ -299,7 +236,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
stagedSummary: "M README.md",
|
stagedSummary: "M README.md",
|
||||||
stagedPatch: "diff --git a/README.md b/README.md",
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
includeBranch: true,
|
includeBranch: true,
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(generated.subject).toBe("Add important change");
|
expect(generated.subject).toBe("Add important change");
|
||||||
@@ -326,7 +262,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
commitSummary: "feat: improve orchestration flow",
|
commitSummary: "feat: improve orchestration flow",
|
||||||
diffSummary: "2 files changed",
|
diffSummary: "2 files changed",
|
||||||
diffPatch: "diff --git a/a.ts b/a.ts",
|
diffPatch: "diff --git a/a.ts b/a.ts",
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(generated.title).toBe("Improve orchestration flow");
|
expect(generated.title).toBe("Improve orchestration flow");
|
||||||
@@ -350,7 +285,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
const generated = yield* textGeneration.generateBranchName({
|
const generated = yield* textGeneration.generateBranchName({
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
message: "Please update session handling.",
|
message: "Please update session handling.",
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(generated.branch).toBe("feat/session");
|
expect(generated.branch).toBe("feat/session");
|
||||||
@@ -358,70 +292,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.effect("generates thread titles and trims them for sidebar use", () =>
|
|
||||||
withFakeCodexEnv(
|
|
||||||
{
|
|
||||||
output: JSON.stringify({
|
|
||||||
title:
|
|
||||||
' "Investigate websocket reconnect regressions after worktree restore" \nignored line',
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const textGeneration = yield* TextGeneration;
|
|
||||||
|
|
||||||
const generated = yield* textGeneration.generateThreadTitle({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
message: "Please investigate websocket reconnect regressions after a worktree restore.",
|
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(generated.title).toBe("Investigate websocket reconnect regressions aft...");
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("falls back when thread title normalization becomes whitespace-only", () =>
|
|
||||||
withFakeCodexEnv(
|
|
||||||
{
|
|
||||||
output: JSON.stringify({
|
|
||||||
title: ' """ """ ',
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const textGeneration = yield* TextGeneration;
|
|
||||||
|
|
||||||
const generated = yield* textGeneration.generateThreadTitle({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
message: "Name this thread.",
|
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(generated.title).toBe("New thread");
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("trims whitespace exposed after quote removal in thread titles", () =>
|
|
||||||
withFakeCodexEnv(
|
|
||||||
{
|
|
||||||
output: JSON.stringify({
|
|
||||||
title: ` "' hello world '" `,
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const textGeneration = yield* TextGeneration;
|
|
||||||
|
|
||||||
const generated = yield* textGeneration.generateThreadTitle({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
message: "Name this thread.",
|
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(generated.title).toBe("hello world");
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
it.effect("omits attachment metadata section when no attachments are provided", () =>
|
it.effect("omits attachment metadata section when no attachments are provided", () =>
|
||||||
withFakeCodexEnv(
|
withFakeCodexEnv(
|
||||||
{
|
{
|
||||||
@@ -436,7 +306,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
const generated = yield* textGeneration.generateBranchName({
|
const generated = yield* textGeneration.generateBranchName({
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
message: "Fix timeout behavior.",
|
message: "Fix timeout behavior.",
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(generated.branch).toBe("fix/session-timeout");
|
expect(generated.branch).toBe("fix/session-timeout");
|
||||||
@@ -456,27 +325,27 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
const { attachmentsDir } = yield* ServerConfig;
|
|
||||||
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
|
const attachmentPath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
|
||||||
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
|
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
|
||||||
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
|
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
|
||||||
|
|
||||||
const textGeneration = yield* TextGeneration;
|
const textGeneration = yield* TextGeneration;
|
||||||
const generated = yield* textGeneration.generateBranchName({
|
const generated = yield* textGeneration
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
.generateBranchName({
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
message: "Fix layout bug from screenshot.",
|
message: "Fix layout bug from screenshot.",
|
||||||
attachments: [
|
attachments: [
|
||||||
{
|
{
|
||||||
type: "image",
|
type: "image",
|
||||||
id: attachmentId,
|
id: attachmentId,
|
||||||
name: "bug.png",
|
name: "bug.png",
|
||||||
mimeType: "image/png",
|
mimeType: "image/png",
|
||||||
sizeBytes: 5,
|
sizeBytes: 5,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
})
|
||||||
|
.pipe(Effect.ensuring(fs.remove(attachmentPath).pipe(Effect.catch(() => Effect.void))));
|
||||||
|
|
||||||
expect(generated.branch).toBe("fix/ui-regression");
|
expect(generated.branch).toBe("fix/ui-regression");
|
||||||
}),
|
}),
|
||||||
@@ -494,16 +363,14 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
const { attachmentsDir } = yield* ServerConfig;
|
|
||||||
const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
|
const imagePath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
|
||||||
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
|
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
|
||||||
yield* fs.writeFile(imagePath, Buffer.from("hello"));
|
yield* fs.writeFile(imagePath, Buffer.from("hello"));
|
||||||
|
|
||||||
const textGeneration = yield* TextGeneration;
|
const textGeneration = yield* TextGeneration;
|
||||||
const generated = yield* textGeneration
|
const generated = yield* textGeneration
|
||||||
.generateBranchName({
|
.generateBranchName({
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
message: "Fix layout bug from screenshot.",
|
message: "Fix layout bug from screenshot.",
|
||||||
attachments: [
|
attachments: [
|
||||||
@@ -543,15 +410,13 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
const { attachmentsDir } = yield* ServerConfig;
|
|
||||||
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
|
const missingPath = path.join(process.cwd(), "attachments", `${missingAttachmentId}.png`);
|
||||||
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
|
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
|
||||||
|
|
||||||
const textGeneration = yield* TextGeneration;
|
const textGeneration = yield* TextGeneration;
|
||||||
const result = yield* textGeneration
|
const result = yield* textGeneration
|
||||||
.generateBranchName({
|
.generateBranchName({
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
message: "Fix layout bug from screenshot.",
|
message: "Fix layout bug from screenshot.",
|
||||||
attachments: [
|
attachments: [
|
||||||
@@ -564,12 +429,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
.pipe(Effect.result);
|
.pipe(
|
||||||
|
Effect.match({
|
||||||
|
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
||||||
|
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
expect(Result.isFailure(result)).toBe(true);
|
expect(result._tag).toBe("Left");
|
||||||
if (Result.isFailure(result)) {
|
if (result._tag === "Left") {
|
||||||
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
expect(result.left).toBeInstanceOf(TextGenerationError);
|
||||||
expect(result.failure.message).toContain("missing --image input");
|
expect(result.left.message).toContain("missing --image input");
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
@@ -591,14 +461,18 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
.generateBranchName({
|
.generateBranchName({
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
message: "Fix websocket reconnect flake",
|
message: "Fix websocket reconnect flake",
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
})
|
})
|
||||||
.pipe(Effect.result);
|
.pipe(
|
||||||
|
Effect.match({
|
||||||
|
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
||||||
|
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
expect(Result.isFailure(result)).toBe(true);
|
expect(result._tag).toBe("Left");
|
||||||
if (Result.isFailure(result)) {
|
if (result._tag === "Left") {
|
||||||
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
expect(result.left).toBeInstanceOf(TextGenerationError);
|
||||||
expect(result.failure.message).toContain("Codex returned invalid structured output");
|
expect(result.left.message).toContain("Codex returned invalid structured output");
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
@@ -620,16 +494,18 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
branch: "feature/codex-error",
|
branch: "feature/codex-error",
|
||||||
stagedSummary: "M README.md",
|
stagedSummary: "M README.md",
|
||||||
stagedPatch: "diff --git a/README.md b/README.md",
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
|
||||||
})
|
})
|
||||||
.pipe(Effect.result);
|
.pipe(
|
||||||
|
Effect.match({
|
||||||
expect(Result.isFailure(result)).toBe(true);
|
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
||||||
if (Result.isFailure(result)) {
|
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
||||||
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
}),
|
||||||
expect(result.failure.message).toContain(
|
|
||||||
"Codex CLI command failed: codex execution failed",
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
expect(result._tag).toBe("Left");
|
||||||
|
if (result._tag === "Left") {
|
||||||
|
expect(result.left).toBeInstanceOf(TextGenerationError);
|
||||||
|
expect(result.left.message).toContain("Codex CLI command failed: codex execution failed");
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -1,45 +1,105 @@
|
|||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
|
|
||||||
import { Effect, FileSystem, Layer, Option, Path, Schema, Scope, Stream } from "effect";
|
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
|
||||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||||
|
|
||||||
import { CodexModelSelection } from "@t3tools/contracts";
|
import { DEFAULT_GIT_TEXT_GENERATION_MODEL } from "@t3tools/contracts";
|
||||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||||
|
|
||||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||||
import { ServerConfig } from "../../config.ts";
|
import { ServerConfig } from "../../config.ts";
|
||||||
import { TextGenerationError } from "@t3tools/contracts";
|
import { TextGenerationError } from "../Errors.ts";
|
||||||
import {
|
import {
|
||||||
type BranchNameGenerationInput,
|
type BranchNameGenerationInput,
|
||||||
type ThreadTitleGenerationResult,
|
type BranchNameGenerationResult,
|
||||||
|
type CommitMessageGenerationResult,
|
||||||
|
type PrContentGenerationResult,
|
||||||
type TextGenerationShape,
|
type TextGenerationShape,
|
||||||
TextGeneration,
|
TextGeneration,
|
||||||
} from "../Services/TextGeneration.ts";
|
} from "../Services/TextGeneration.ts";
|
||||||
import {
|
|
||||||
buildBranchNamePrompt,
|
|
||||||
buildCommitMessagePrompt,
|
|
||||||
buildPrContentPrompt,
|
|
||||||
buildThreadTitlePrompt,
|
|
||||||
} from "../Prompts.ts";
|
|
||||||
import {
|
|
||||||
normalizeCliError,
|
|
||||||
sanitizeCommitSubject,
|
|
||||||
sanitizePrTitle,
|
|
||||||
sanitizeThreadTitle,
|
|
||||||
toJsonSchemaObject,
|
|
||||||
} from "../Utils.ts";
|
|
||||||
import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts";
|
|
||||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
|
||||||
import { normalizeCodexModelOptionsWithCapabilities } from "@t3tools/shared/model";
|
|
||||||
|
|
||||||
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
|
const CODEX_REASONING_EFFORT = "low";
|
||||||
const CODEX_TIMEOUT_MS = 180_000;
|
const CODEX_TIMEOUT_MS = 180_000;
|
||||||
|
|
||||||
|
function toCodexOutputJsonSchema(schema: Schema.Top): unknown {
|
||||||
|
const document = Schema.toJsonSchemaDocument(schema);
|
||||||
|
if (document.definitions && Object.keys(document.definitions).length > 0) {
|
||||||
|
return {
|
||||||
|
...document.schema,
|
||||||
|
$defs: document.definitions,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return document.schema;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeCodexError(
|
||||||
|
operation: string,
|
||||||
|
error: unknown,
|
||||||
|
fallback: string,
|
||||||
|
): TextGenerationError {
|
||||||
|
if (Schema.is(TextGenerationError)(error)) {
|
||||||
|
return error;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error instanceof Error) {
|
||||||
|
const lower = error.message.toLowerCase();
|
||||||
|
if (
|
||||||
|
error.message.includes("Command not found: codex") ||
|
||||||
|
lower.includes("spawn codex") ||
|
||||||
|
lower.includes("enoent")
|
||||||
|
) {
|
||||||
|
return new TextGenerationError({
|
||||||
|
operation,
|
||||||
|
detail: "Codex CLI (`codex`) is required but not available on PATH.",
|
||||||
|
cause: error,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return new TextGenerationError({
|
||||||
|
operation,
|
||||||
|
detail: `${fallback}: ${error.message}`,
|
||||||
|
cause: error,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return new TextGenerationError({
|
||||||
|
operation,
|
||||||
|
detail: fallback,
|
||||||
|
cause: error,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function limitSection(value: string, maxChars: number): string {
|
||||||
|
if (value.length <= maxChars) return value;
|
||||||
|
const truncated = value.slice(0, maxChars);
|
||||||
|
return `${truncated}\n\n[truncated]`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitizeCommitSubject(raw: string): string {
|
||||||
|
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||||
|
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
|
||||||
|
if (withoutTrailingPeriod.length === 0) {
|
||||||
|
return "Update project files";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (withoutTrailingPeriod.length <= 72) {
|
||||||
|
return withoutTrailingPeriod;
|
||||||
|
}
|
||||||
|
return withoutTrailingPeriod.slice(0, 72).trimEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitizePrTitle(raw: string): string {
|
||||||
|
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||||
|
if (singleLine.length > 0) {
|
||||||
|
return singleLine;
|
||||||
|
}
|
||||||
|
return "Update project changes";
|
||||||
|
}
|
||||||
|
|
||||||
const makeCodexTextGeneration = Effect.gen(function* () {
|
const makeCodexTextGeneration = Effect.gen(function* () {
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||||
const serverConfig = yield* Effect.service(ServerConfig);
|
const serverConfig = yield* Effect.service(ServerConfig);
|
||||||
const serverSettingsService = yield* Effect.service(ServerSettingsService);
|
|
||||||
|
|
||||||
type MaterializedImageAttachments = {
|
type MaterializedImageAttachments = {
|
||||||
readonly imagePaths: ReadonlyArray<string>;
|
readonly imagePaths: ReadonlyArray<string>;
|
||||||
@@ -49,367 +109,363 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
operation: string,
|
operation: string,
|
||||||
stream: Stream.Stream<Uint8Array, E>,
|
stream: Stream.Stream<Uint8Array, E>,
|
||||||
): Effect.Effect<string, TextGenerationError> =>
|
): Effect.Effect<string, TextGenerationError> =>
|
||||||
stream.pipe(
|
Effect.gen(function* () {
|
||||||
Stream.decodeText(),
|
let text = "";
|
||||||
Stream.runFold(
|
yield* Stream.runForEach(stream, (chunk) =>
|
||||||
() => "",
|
Effect.sync(() => {
|
||||||
(acc, chunk) => acc + chunk,
|
text += Buffer.from(chunk).toString("utf8");
|
||||||
),
|
}),
|
||||||
Effect.mapError((cause) =>
|
).pipe(
|
||||||
normalizeCliError("codex", operation, cause, "Failed to collect process output"),
|
Effect.mapError((cause) =>
|
||||||
),
|
normalizeCodexError(operation, cause, "Failed to collect process output"),
|
||||||
);
|
),
|
||||||
|
);
|
||||||
|
return text;
|
||||||
|
});
|
||||||
|
|
||||||
|
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
|
||||||
|
|
||||||
const writeTempFile = (
|
const writeTempFile = (
|
||||||
operation: string,
|
operation: string,
|
||||||
prefix: string,
|
prefix: string,
|
||||||
content: string,
|
content: string,
|
||||||
): Effect.Effect<string, TextGenerationError, Scope.Scope> => {
|
): Effect.Effect<string, TextGenerationError> => {
|
||||||
return fileSystem
|
const filePath = path.join(tempDir, `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`);
|
||||||
.makeTempFileScoped({
|
return fileSystem.writeFileString(filePath, content).pipe(
|
||||||
prefix: `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`,
|
Effect.mapError(
|
||||||
})
|
(cause) =>
|
||||||
.pipe(
|
new TextGenerationError({
|
||||||
Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)),
|
operation,
|
||||||
Effect.mapError(
|
detail: `Failed to write temp file at ${filePath}.`,
|
||||||
(cause) =>
|
cause,
|
||||||
new TextGenerationError({
|
}),
|
||||||
operation,
|
),
|
||||||
detail: `Failed to write temp file`,
|
Effect.as(filePath),
|
||||||
cause,
|
);
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
||||||
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
|
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
|
||||||
|
|
||||||
const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
|
const materializeImageAttachments = (
|
||||||
_operation:
|
_operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName",
|
||||||
| "generateCommitMessage"
|
|
||||||
| "generatePrContent"
|
|
||||||
| "generateBranchName"
|
|
||||||
| "generateThreadTitle",
|
|
||||||
attachments: BranchNameGenerationInput["attachments"],
|
attachments: BranchNameGenerationInput["attachments"],
|
||||||
): Effect.fn.Return<MaterializedImageAttachments, TextGenerationError> {
|
): Effect.Effect<MaterializedImageAttachments, TextGenerationError> =>
|
||||||
if (!attachments || attachments.length === 0) {
|
Effect.gen(function* () {
|
||||||
return { imagePaths: [] };
|
if (!attachments || attachments.length === 0) {
|
||||||
}
|
return { imagePaths: [] };
|
||||||
|
|
||||||
const imagePaths: string[] = [];
|
|
||||||
for (const attachment of attachments) {
|
|
||||||
if (attachment.type !== "image") {
|
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const resolvedPath = resolveAttachmentPath({
|
const imagePaths: string[] = [];
|
||||||
attachmentsDir: serverConfig.attachmentsDir,
|
for (const attachment of attachments) {
|
||||||
attachment,
|
if (attachment.type !== "image") {
|
||||||
});
|
continue;
|
||||||
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
|
}
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const fileInfo = yield* fileSystem
|
|
||||||
.stat(resolvedPath)
|
|
||||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
|
||||||
if (!fileInfo || fileInfo.type !== "File") {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
imagePaths.push(resolvedPath);
|
|
||||||
}
|
|
||||||
return { imagePaths };
|
|
||||||
});
|
|
||||||
|
|
||||||
const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
|
const resolvedPath = resolveAttachmentPath({
|
||||||
|
stateDir: serverConfig.stateDir,
|
||||||
|
attachment,
|
||||||
|
});
|
||||||
|
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const fileInfo = yield* fileSystem
|
||||||
|
.stat(resolvedPath)
|
||||||
|
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||||
|
if (!fileInfo || fileInfo.type !== "File") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
imagePaths.push(resolvedPath);
|
||||||
|
}
|
||||||
|
return { imagePaths };
|
||||||
|
});
|
||||||
|
|
||||||
|
const runCodexJson = <S extends Schema.Top>({
|
||||||
operation,
|
operation,
|
||||||
cwd,
|
cwd,
|
||||||
prompt,
|
prompt,
|
||||||
outputSchemaJson,
|
outputSchemaJson,
|
||||||
imagePaths = [],
|
imagePaths = [],
|
||||||
cleanupPaths = [],
|
cleanupPaths = [],
|
||||||
modelSelection,
|
model,
|
||||||
}: {
|
}: {
|
||||||
operation:
|
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
|
||||||
| "generateCommitMessage"
|
|
||||||
| "generatePrContent"
|
|
||||||
| "generateBranchName"
|
|
||||||
| "generateThreadTitle";
|
|
||||||
cwd: string;
|
cwd: string;
|
||||||
prompt: string;
|
prompt: string;
|
||||||
outputSchemaJson: S;
|
outputSchemaJson: S;
|
||||||
imagePaths?: ReadonlyArray<string>;
|
imagePaths?: ReadonlyArray<string>;
|
||||||
cleanupPaths?: ReadonlyArray<string>;
|
cleanupPaths?: ReadonlyArray<string>;
|
||||||
modelSelection: CodexModelSelection;
|
model?: string;
|
||||||
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||||
const schemaPath = yield* writeTempFile(
|
Effect.gen(function* () {
|
||||||
operation,
|
const schemaPath = yield* writeTempFile(
|
||||||
"codex-schema",
|
operation,
|
||||||
JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
|
"codex-schema",
|
||||||
);
|
JSON.stringify(toCodexOutputJsonSchema(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 reasoningEffort =
|
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
||||||
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
|
|
||||||
const command = ChildProcess.make(
|
const runCodexCommand = Effect.gen(function* () {
|
||||||
codexSettings?.binaryPath || "codex",
|
const command = ChildProcess.make(
|
||||||
[
|
"codex",
|
||||||
"exec",
|
[
|
||||||
"--ephemeral",
|
"exec",
|
||||||
"-s",
|
"--ephemeral",
|
||||||
"read-only",
|
"-s",
|
||||||
"--model",
|
"read-only",
|
||||||
modelSelection.model,
|
"--model",
|
||||||
"--config",
|
model ?? DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||||
`model_reasoning_effort="${reasoningEffort}"`,
|
"--config",
|
||||||
...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
|
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
|
||||||
"--output-schema",
|
"--output-schema",
|
||||||
schemaPath,
|
schemaPath,
|
||||||
"--output-last-message",
|
"--output-last-message",
|
||||||
outputPath,
|
outputPath,
|
||||||
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
||||||
"-",
|
"-",
|
||||||
],
|
],
|
||||||
|
{
|
||||||
|
cwd,
|
||||||
|
shell: process.platform === "win32",
|
||||||
|
stdin: {
|
||||||
|
stream: Stream.make(new TextEncoder().encode(prompt)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const child = yield* commandSpawner
|
||||||
|
.spawn(command)
|
||||||
|
.pipe(
|
||||||
|
Effect.mapError((cause) =>
|
||||||
|
normalizeCodexError(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.map((value) => Number(value)),
|
||||||
|
Effect.mapError((cause) =>
|
||||||
|
normalizeCodexError(operation, cause, "Failed to read Codex CLI exit code"),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
{ concurrency: "unbounded" },
|
||||||
|
);
|
||||||
|
|
||||||
|
if (exitCode !== 0) {
|
||||||
|
const stderrDetail = stderr.trim();
|
||||||
|
const stdoutDetail = stdout.trim();
|
||||||
|
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation,
|
||||||
|
detail:
|
||||||
|
detail.length > 0
|
||||||
|
? `Codex CLI command failed: ${detail}`
|
||||||
|
: `Codex CLI command failed with code ${exitCode}.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const cleanup = Effect.all(
|
||||||
|
[schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
|
||||||
{
|
{
|
||||||
env: {
|
concurrency: "unbounded",
|
||||||
...process.env,
|
|
||||||
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
|
|
||||||
},
|
|
||||||
cwd,
|
|
||||||
shell: process.platform === "win32",
|
|
||||||
stdin: {
|
|
||||||
stream: Stream.encodeText(Stream.make(prompt)),
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
);
|
).pipe(Effect.asVoid);
|
||||||
|
|
||||||
const child = yield* commandSpawner
|
return yield* Effect.gen(function* () {
|
||||||
.spawn(command)
|
yield* runCodexCommand.pipe(
|
||||||
.pipe(
|
Effect.scoped,
|
||||||
Effect.mapError((cause) =>
|
Effect.timeoutOption(CODEX_TIMEOUT_MS),
|
||||||
normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
|
Effect.flatMap(
|
||||||
|
Option.match({
|
||||||
|
onNone: () =>
|
||||||
|
Effect.fail(
|
||||||
|
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
|
||||||
|
),
|
||||||
|
onSome: () => Effect.void,
|
||||||
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
return yield* fileSystem.readFileString(outputPath).pipe(
|
||||||
[
|
Effect.mapError(
|
||||||
readStreamAsString(operation, child.stdout),
|
(cause) =>
|
||||||
readStreamAsString(operation, child.stderr),
|
new TextGenerationError({
|
||||||
child.exitCode.pipe(
|
operation,
|
||||||
Effect.mapError((cause) =>
|
detail: "Failed to read Codex output file.",
|
||||||
normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
|
cause,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
|
||||||
|
Effect.catchTag("SchemaError", (cause) =>
|
||||||
|
Effect.fail(
|
||||||
|
new TextGenerationError({
|
||||||
|
operation,
|
||||||
|
detail: "Codex returned invalid structured output.",
|
||||||
|
cause,
|
||||||
|
}),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
);
|
||||||
{ concurrency: "unbounded" },
|
}).pipe(Effect.ensuring(cleanup));
|
||||||
);
|
});
|
||||||
|
|
||||||
if (exitCode !== 0) {
|
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = (input) => {
|
||||||
const stderrDetail = stderr.trim();
|
const wantsBranch = input.includeBranch === true;
|
||||||
const stdoutDetail = stdout.trim();
|
|
||||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
const prompt = [
|
||||||
return yield* new TextGenerationError({
|
"You write concise git commit messages.",
|
||||||
operation,
|
wantsBranch
|
||||||
detail:
|
? "Return a JSON object with keys: subject, body, branch."
|
||||||
detail.length > 0
|
: "Return a JSON object with keys: subject, body.",
|
||||||
? `Codex CLI command failed: ${detail}`
|
"Rules:",
|
||||||
: `Codex CLI command failed with code ${exitCode}.`,
|
"- subject must be imperative, <= 72 chars, and no trailing period",
|
||||||
|
"- body can be empty string or short bullet points",
|
||||||
|
...(wantsBranch
|
||||||
|
? ["- branch must be a short semantic git branch fragment for this change"]
|
||||||
|
: []),
|
||||||
|
"- capture the primary user-visible or developer-visible change",
|
||||||
|
"",
|
||||||
|
`Branch: ${input.branch ?? "(detached)"}`,
|
||||||
|
"",
|
||||||
|
"Staged files:",
|
||||||
|
limitSection(input.stagedSummary, 6_000),
|
||||||
|
"",
|
||||||
|
"Staged patch:",
|
||||||
|
limitSection(input.stagedPatch, 40_000),
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
|
const outputSchemaJson = wantsBranch
|
||||||
|
? Schema.Struct({
|
||||||
|
subject: Schema.String,
|
||||||
|
body: Schema.String,
|
||||||
|
branch: Schema.String,
|
||||||
|
})
|
||||||
|
: Schema.Struct({
|
||||||
|
subject: Schema.String,
|
||||||
|
body: Schema.String,
|
||||||
});
|
});
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const cleanup = Effect.all(
|
return runCodexJson({
|
||||||
[schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
|
|
||||||
{
|
|
||||||
concurrency: "unbounded",
|
|
||||||
},
|
|
||||||
).pipe(Effect.asVoid);
|
|
||||||
|
|
||||||
return yield* Effect.gen(function* () {
|
|
||||||
yield* runCodexCommand().pipe(
|
|
||||||
Effect.scoped,
|
|
||||||
Effect.timeoutOption(CODEX_TIMEOUT_MS),
|
|
||||||
Effect.flatMap(
|
|
||||||
Option.match({
|
|
||||||
onNone: () =>
|
|
||||||
Effect.fail(
|
|
||||||
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
|
|
||||||
),
|
|
||||||
onSome: () => Effect.void,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
return yield* fileSystem.readFileString(outputPath).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new TextGenerationError({
|
|
||||||
operation,
|
|
||||||
detail: "Failed to read Codex output file.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
|
|
||||||
Effect.catchTag("SchemaError", (cause) =>
|
|
||||||
Effect.fail(
|
|
||||||
new TextGenerationError({
|
|
||||||
operation,
|
|
||||||
detail: "Codex returned invalid structured output.",
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}).pipe(Effect.ensuring(cleanup));
|
|
||||||
});
|
|
||||||
|
|
||||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
|
|
||||||
"CodexTextGeneration.generateCommitMessage",
|
|
||||||
)(function* (input) {
|
|
||||||
const { prompt, outputSchema } = buildCommitMessagePrompt({
|
|
||||||
branch: input.branch,
|
|
||||||
stagedSummary: input.stagedSummary,
|
|
||||||
stagedPatch: input.stagedPatch,
|
|
||||||
includeBranch: input.includeBranch === true,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (input.modelSelection.provider !== "codex") {
|
|
||||||
return yield* new TextGenerationError({
|
|
||||||
operation: "generateCommitMessage",
|
|
||||||
detail: "Invalid model selection.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const generated = yield* runCodexJson({
|
|
||||||
operation: "generateCommitMessage",
|
operation: "generateCommitMessage",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
prompt,
|
prompt,
|
||||||
outputSchemaJson: outputSchema,
|
outputSchemaJson,
|
||||||
modelSelection: input.modelSelection,
|
...(input.model ? { model: input.model } : {}),
|
||||||
});
|
}).pipe(
|
||||||
|
Effect.map(
|
||||||
|
(generated) =>
|
||||||
|
({
|
||||||
|
subject: sanitizeCommitSubject(generated.subject),
|
||||||
|
body: generated.body.trim(),
|
||||||
|
...("branch" in generated && typeof generated.branch === "string"
|
||||||
|
? { branch: sanitizeFeatureBranchName(generated.branch) }
|
||||||
|
: {}),
|
||||||
|
}) satisfies CommitMessageGenerationResult,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
return {
|
const generatePrContent: TextGenerationShape["generatePrContent"] = (input) => {
|
||||||
subject: sanitizeCommitSubject(generated.subject),
|
const prompt = [
|
||||||
body: generated.body.trim(),
|
"You write GitHub pull request content.",
|
||||||
...("branch" in generated && typeof generated.branch === "string"
|
"Return a JSON object with keys: title, body.",
|
||||||
? { branch: sanitizeFeatureBranchName(generated.branch) }
|
"Rules:",
|
||||||
: {}),
|
"- title should be concise and specific",
|
||||||
};
|
"- body must be markdown and include headings '## Summary' and '## Testing'",
|
||||||
});
|
"- under Summary, provide short bullet points",
|
||||||
|
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
|
||||||
|
"",
|
||||||
|
`Base branch: ${input.baseBranch}`,
|
||||||
|
`Head branch: ${input.headBranch}`,
|
||||||
|
"",
|
||||||
|
"Commits:",
|
||||||
|
limitSection(input.commitSummary, 12_000),
|
||||||
|
"",
|
||||||
|
"Diff stat:",
|
||||||
|
limitSection(input.diffSummary, 12_000),
|
||||||
|
"",
|
||||||
|
"Diff patch:",
|
||||||
|
limitSection(input.diffPatch, 40_000),
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
|
return runCodexJson({
|
||||||
"CodexTextGeneration.generatePrContent",
|
|
||||||
)(function* (input) {
|
|
||||||
const { prompt, outputSchema } = buildPrContentPrompt({
|
|
||||||
baseBranch: input.baseBranch,
|
|
||||||
headBranch: input.headBranch,
|
|
||||||
commitSummary: input.commitSummary,
|
|
||||||
diffSummary: input.diffSummary,
|
|
||||||
diffPatch: input.diffPatch,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (input.modelSelection.provider !== "codex") {
|
|
||||||
return yield* new TextGenerationError({
|
|
||||||
operation: "generatePrContent",
|
|
||||||
detail: "Invalid model selection.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const generated = yield* runCodexJson({
|
|
||||||
operation: "generatePrContent",
|
operation: "generatePrContent",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
prompt,
|
prompt,
|
||||||
outputSchemaJson: outputSchema,
|
outputSchemaJson: Schema.Struct({
|
||||||
modelSelection: input.modelSelection,
|
title: Schema.String,
|
||||||
});
|
body: Schema.String,
|
||||||
|
}),
|
||||||
return {
|
...(input.model ? { model: input.model } : {}),
|
||||||
title: sanitizePrTitle(generated.title),
|
}).pipe(
|
||||||
body: generated.body.trim(),
|
Effect.map(
|
||||||
};
|
(generated) =>
|
||||||
});
|
({
|
||||||
|
title: sanitizePrTitle(generated.title),
|
||||||
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
|
body: generated.body.trim(),
|
||||||
"CodexTextGeneration.generateBranchName",
|
}) satisfies PrContentGenerationResult,
|
||||||
)(function* (input) {
|
),
|
||||||
const { imagePaths } = yield* materializeImageAttachments(
|
|
||||||
"generateBranchName",
|
|
||||||
input.attachments,
|
|
||||||
);
|
);
|
||||||
const { prompt, outputSchema } = buildBranchNamePrompt({
|
};
|
||||||
message: input.message,
|
|
||||||
attachments: input.attachments,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (input.modelSelection.provider !== "codex") {
|
const generateBranchName: TextGenerationShape["generateBranchName"] = (input) => {
|
||||||
return yield* new TextGenerationError({
|
return Effect.gen(function* () {
|
||||||
|
const { imagePaths } = yield* materializeImageAttachments(
|
||||||
|
"generateBranchName",
|
||||||
|
input.attachments,
|
||||||
|
);
|
||||||
|
const attachmentLines = (input.attachments ?? []).map(
|
||||||
|
(attachment) =>
|
||||||
|
`- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
|
||||||
|
);
|
||||||
|
|
||||||
|
const promptSections = [
|
||||||
|
"You generate concise git branch names.",
|
||||||
|
"Return a JSON object with key: branch.",
|
||||||
|
"Rules:",
|
||||||
|
"- Branch should describe the requested work from the user message.",
|
||||||
|
"- Keep it short and specific (2-6 words).",
|
||||||
|
"- Use plain words only, no issue prefixes and no punctuation-heavy text.",
|
||||||
|
"- If images are attached, use them as primary context for visual/UI issues.",
|
||||||
|
"",
|
||||||
|
"User message:",
|
||||||
|
limitSection(input.message, 8_000),
|
||||||
|
];
|
||||||
|
if (attachmentLines.length > 0) {
|
||||||
|
promptSections.push(
|
||||||
|
"",
|
||||||
|
"Attachment metadata:",
|
||||||
|
limitSection(attachmentLines.join("\n"), 4_000),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const prompt = promptSections.join("\n");
|
||||||
|
|
||||||
|
const generated = yield* runCodexJson({
|
||||||
operation: "generateBranchName",
|
operation: "generateBranchName",
|
||||||
detail: "Invalid model selection.",
|
cwd: input.cwd,
|
||||||
|
prompt,
|
||||||
|
outputSchemaJson: Schema.Struct({
|
||||||
|
branch: Schema.String,
|
||||||
|
}),
|
||||||
|
imagePaths,
|
||||||
|
...(input.model ? { model: input.model } : {}),
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
|
||||||
const generated = yield* runCodexJson({
|
return {
|
||||||
operation: "generateBranchName",
|
branch: sanitizeBranchFragment(generated.branch),
|
||||||
cwd: input.cwd,
|
} satisfies BranchNameGenerationResult;
|
||||||
prompt,
|
|
||||||
outputSchemaJson: outputSchema,
|
|
||||||
imagePaths,
|
|
||||||
modelSelection: input.modelSelection,
|
|
||||||
});
|
});
|
||||||
|
};
|
||||||
return {
|
|
||||||
branch: sanitizeBranchFragment(generated.branch),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
|
|
||||||
"CodexTextGeneration.generateThreadTitle",
|
|
||||||
)(function* (input) {
|
|
||||||
const { imagePaths } = yield* materializeImageAttachments(
|
|
||||||
"generateThreadTitle",
|
|
||||||
input.attachments,
|
|
||||||
);
|
|
||||||
const { prompt, outputSchema } = buildThreadTitlePrompt({
|
|
||||||
message: input.message,
|
|
||||||
attachments: input.attachments,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (input.modelSelection.provider !== "codex") {
|
|
||||||
return yield* new TextGenerationError({
|
|
||||||
operation: "generateThreadTitle",
|
|
||||||
detail: "Invalid model selection.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const generated = yield* runCodexJson({
|
|
||||||
operation: "generateThreadTitle",
|
|
||||||
cwd: input.cwd,
|
|
||||||
prompt,
|
|
||||||
outputSchemaJson: outputSchema,
|
|
||||||
imagePaths,
|
|
||||||
modelSelection: input.modelSelection,
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
title: sanitizeThreadTitle(generated.title),
|
|
||||||
} satisfies ThreadTitleGenerationResult;
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
generateCommitMessage,
|
generateCommitMessage,
|
||||||
generatePrContent,
|
generatePrContent,
|
||||||
generateBranchName,
|
generateBranchName,
|
||||||
generateThreadTitle,
|
|
||||||
} satisfies TextGenerationShape;
|
} satisfies TextGenerationShape;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
+742
-1467
File diff suppressed because it is too large.
Load diff
@@ -2,7 +2,7 @@ import { Effect, Layer, Schema } from "effect";
|
|||||||
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||||
|
|
||||||
import { runProcess } from "../../processRunner";
|
import { runProcess } from "../../processRunner";
|
||||||
import { GitHubCliError } from "@t3tools/contracts";
|
import { GitHubCliError } from "../Errors.ts";
|
||||||
import {
|
import {
|
||||||
GitHubCli,
|
GitHubCli,
|
||||||
type GitHubRepositoryCloneUrls,
|
type GitHubRepositoryCloneUrls,
|
||||||
@@ -168,7 +168,6 @@ const makeGitHubCli = Effect.sync(() => {
|
|||||||
runProcess("gh", input.args, {
|
runProcess("gh", input.args, {
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||||
shell: false,
|
|
||||||
}),
|
}),
|
||||||
catch: (error) => normalizeGitHubCliError("execute", error),
|
catch: (error) => normalizeGitHubCliError("execute", error),
|
||||||
});
|
});
|
||||||
@@ -188,7 +187,7 @@ const makeGitHubCli = Effect.sync(() => {
|
|||||||
"--limit",
|
"--limit",
|
||||||
String(input.limit ?? 1),
|
String(input.limit ?? 1),
|
||||||
"--json",
|
"--json",
|
||||||
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
"number,title,url,baseRefName,headRefName",
|
||||||
],
|
],
|
||||||
}).pipe(
|
}).pipe(
|
||||||
Effect.map((result) => result.stdout.trim()),
|
Effect.map((result) => result.stdout.trim()),
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,59 @@
|
|||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
import { it, assert } from "@effect/vitest";
|
||||||
|
import { Effect, Layer, Schema } from "effect";
|
||||||
|
|
||||||
|
import { GitCommandError } from "../Errors.ts";
|
||||||
|
import { GitServiceLive } from "./GitService.ts";
|
||||||
|
import { GitService } from "../Services/GitService.ts";
|
||||||
|
|
||||||
|
const layer = it.layer(Layer.provideMerge(GitServiceLive, NodeServices.layer));
|
||||||
|
|
||||||
|
layer("GitServiceLive", (it) => {
|
||||||
|
it.effect("runGit executes successful git commands", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const gitService = yield* GitService;
|
||||||
|
const result = yield* gitService.execute({
|
||||||
|
operation: "GitProcess.test.version",
|
||||||
|
cwd: process.cwd(),
|
||||||
|
args: ["--version"],
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(result.code, 0);
|
||||||
|
assert.ok(result.stdout.toLowerCase().includes("git version"));
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("runGit can return non-zero exit codes when allowed", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const gitService = yield* GitService;
|
||||||
|
const result = yield* gitService.execute({
|
||||||
|
operation: "GitProcess.test.allowNonZero",
|
||||||
|
cwd: process.cwd(),
|
||||||
|
args: ["rev-parse", "--verify", "__definitely_missing_ref__"],
|
||||||
|
allowNonZeroExit: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.notEqual(result.code, 0);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("runGit fails with GitCommandError when non-zero exits are not allowed", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const gitService = yield* GitService;
|
||||||
|
const result = yield* Effect.result(
|
||||||
|
gitService.execute({
|
||||||
|
operation: "GitProcess.test.failOnNonZero",
|
||||||
|
cwd: process.cwd(),
|
||||||
|
args: ["rev-parse", "--verify", "__definitely_missing_ref__"],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.equal(result._tag, "Failure");
|
||||||
|
if (result._tag === "Failure") {
|
||||||
|
assert.ok(Schema.is(GitCommandError)(result.failure));
|
||||||
|
assert.equal(result.failure.operation, "GitProcess.test.failOnNonZero");
|
||||||
|
assert.equal(result.failure.command, "git rev-parse --verify __definitely_missing_ref__");
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
/**
|
||||||
|
* Git process helpers - Effect-native git execution with typed errors.
|
||||||
|
*
|
||||||
|
* Centralizes child-process git invocation for server modules. This module
|
||||||
|
* only executes git commands and reports structured failures.
|
||||||
|
*
|
||||||
|
* @module GitServiceLive
|
||||||
|
*/
|
||||||
|
import { Effect, Layer, Option, Schema, Stream } from "effect";
|
||||||
|
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||||
|
import { GitCommandError } from "../Errors.ts";
|
||||||
|
import {
|
||||||
|
ExecuteGitInput,
|
||||||
|
ExecuteGitResult,
|
||||||
|
GitService,
|
||||||
|
GitServiceShape,
|
||||||
|
} from "../Services/GitService.ts";
|
||||||
|
|
||||||
|
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||||
|
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
||||||
|
|
||||||
|
function quoteGitCommand(args: ReadonlyArray<string>): string {
|
||||||
|
return `git ${args.join(" ")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toGitCommandError(
|
||||||
|
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||||
|
detail: string,
|
||||||
|
) {
|
||||||
|
return (cause: unknown) =>
|
||||||
|
Schema.is(GitCommandError)(cause)
|
||||||
|
? cause
|
||||||
|
: new GitCommandError({
|
||||||
|
operation: input.operation,
|
||||||
|
command: quoteGitCommand(input.args),
|
||||||
|
cwd: input.cwd,
|
||||||
|
detail: `${cause instanceof Error && cause.message.length > 0 ? cause.message : "Unknown error"} - ${detail}`,
|
||||||
|
...(cause !== undefined ? { cause } : {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const collectOutput = Effect.fn(function* <E>(
|
||||||
|
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||||
|
stream: Stream.Stream<Uint8Array, E>,
|
||||||
|
maxOutputBytes: number,
|
||||||
|
): Effect.fn.Return<string, GitCommandError> {
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
let bytes = 0;
|
||||||
|
let text = "";
|
||||||
|
|
||||||
|
yield* Stream.runForEach(stream, (chunk) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
bytes += chunk.byteLength;
|
||||||
|
if (bytes > maxOutputBytes) {
|
||||||
|
return yield* new GitCommandError({
|
||||||
|
operation: input.operation,
|
||||||
|
command: quoteGitCommand(input.args),
|
||||||
|
cwd: input.cwd,
|
||||||
|
detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
text += decoder.decode(chunk, { stream: true });
|
||||||
|
}),
|
||||||
|
).pipe(Effect.mapError(toGitCommandError(input, "output stream failed.")));
|
||||||
|
|
||||||
|
text += decoder.decode();
|
||||||
|
return text;
|
||||||
|
});
|
||||||
|
|
||||||
|
const makeGitService = Effect.gen(function* () {
|
||||||
|
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||||
|
|
||||||
|
const execute: GitServiceShape["execute"] = Effect.fnUntraced(function* (input) {
|
||||||
|
const commandInput = {
|
||||||
|
...input,
|
||||||
|
args: [...input.args],
|
||||||
|
} as const;
|
||||||
|
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||||
|
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||||
|
|
||||||
|
const commandEffect = Effect.gen(function* () {
|
||||||
|
const child = yield* commandSpawner
|
||||||
|
.spawn(
|
||||||
|
ChildProcess.make("git", commandInput.args, {
|
||||||
|
cwd: commandInput.cwd,
|
||||||
|
...(input.env ? { env: input.env } : {}),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn.")));
|
||||||
|
|
||||||
|
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||||
|
[
|
||||||
|
collectOutput(commandInput, child.stdout, maxOutputBytes),
|
||||||
|
collectOutput(commandInput, child.stderr, maxOutputBytes),
|
||||||
|
child.exitCode.pipe(
|
||||||
|
Effect.map((value) => Number(value)),
|
||||||
|
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
{ concurrency: "unbounded" },
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||||
|
const trimmedStderr = stderr.trim();
|
||||||
|
return yield* new GitCommandError({
|
||||||
|
operation: commandInput.operation,
|
||||||
|
command: quoteGitCommand(commandInput.args),
|
||||||
|
cwd: commandInput.cwd,
|
||||||
|
detail:
|
||||||
|
trimmedStderr.length > 0
|
||||||
|
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
|
||||||
|
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
|
||||||
|
});
|
||||||
|
|
||||||
|
return yield* commandEffect.pipe(
|
||||||
|
Effect.scoped,
|
||||||
|
Effect.timeoutOption(timeoutMs),
|
||||||
|
Effect.flatMap((result) =>
|
||||||
|
Option.match(result, {
|
||||||
|
onNone: () =>
|
||||||
|
Effect.fail(
|
||||||
|
new GitCommandError({
|
||||||
|
operation: commandInput.operation,
|
||||||
|
command: quoteGitCommand(commandInput.args),
|
||||||
|
cwd: commandInput.cwd,
|
||||||
|
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
onSome: Effect.succeed,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
execute,
|
||||||
|
} satisfies GitServiceShape;
|
||||||
|
});
|
||||||
|
|
||||||
|
export const GitServiceLive = Layer.effect(GitService, makeGitService);
|
||||||
Loaded 100 of 557 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user