Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
84b54f7284 | ||
|
|
acd1abbd66 | ||
|
|
58e5f714b0 | ||
|
|
4ae9de311b | ||
|
|
5fa09fa2d9 | ||
|
|
12c3af7821 | ||
|
|
e2316814da | ||
|
|
678f827f0b | ||
|
|
a3dadf311e | ||
|
|
e3004ae806 | ||
|
|
9385314d26 | ||
|
|
a3f292770e | ||
|
|
2028d57e88 | ||
|
|
3405a64dd8 | ||
|
|
1cba2f64d3 | ||
|
|
1a05d8ca1a | ||
|
|
cf9f236c80 | ||
|
|
e82b987386 | ||
|
|
ea9e61b266 | ||
|
|
e32077cee7 | ||
|
|
5d9eb18312 | ||
|
|
abb84c09e3 | ||
|
|
65d797c13e | ||
|
|
7c0849fe2e | ||
|
|
592c234fd5 | ||
|
|
66d76b5d02 | ||
|
|
528bb2a1fa | ||
|
|
869789b4ed | ||
|
|
9bedd7140c | ||
|
|
70f5dfcef7 | ||
|
|
9847e9b621 | ||
|
|
b547fee77e | ||
|
|
7b3cdc6a8c | ||
|
|
386eb18a58 | ||
|
|
7372184d06 | ||
|
|
d9ded65dfe | ||
|
|
2aa73985ea | ||
|
|
5b3b31b6e6 | ||
|
|
b7559c4678 | ||
|
|
b96308fc5a | ||
|
|
72b7f90c50 | ||
|
|
1ec346c22e | ||
|
|
28e481eb24 | ||
|
|
b1934b925a | ||
|
|
8244fb80e6 | ||
|
|
afc3924393 | ||
|
|
11d456f6c8 | ||
|
|
a221542921 | ||
|
|
226ed997e1 | ||
|
|
c6f57a1064 | ||
|
|
340dbbb36e | ||
|
|
53a552e80d | ||
|
|
cf2c628bc0 | ||
|
|
e0874b651d | ||
|
|
12347082ef | ||
|
|
740d7a3216 | ||
|
|
cd7980b457 | ||
|
|
f2cd53f232 | ||
|
|
04a1ae77e6 | ||
|
|
6de4b47ecb | ||
|
|
27c2b145f8 | ||
|
|
8515f02770 | ||
|
|
e9ed849b53 | ||
|
|
e8f5b4ad5b | ||
|
|
752f96e9ae | ||
|
|
1b272fd709 | ||
|
|
9013c07f6d | ||
|
|
085340588a | ||
|
|
48481aa923 | ||
|
|
da107f315c | ||
|
|
d2822a8883 | ||
|
|
ae3ea3980d | ||
|
|
915a0548c0 | ||
|
|
5ce5472bc3 | ||
|
|
9ea443d73a | ||
|
|
60f7ae86bb | ||
|
|
867cf4cf09 | ||
|
|
ae6f9715c6 | ||
|
|
b92c78f552 | ||
|
|
801dfe5b41 | ||
|
|
823d69f621 | ||
|
|
4963fccb05 | ||
|
|
dd89d5ce1a | ||
|
|
9132c37c86 | ||
|
|
b9c7ea0581 | ||
|
|
556a195c9d | ||
|
|
80b282ece7 | ||
|
|
d15075b32d | ||
|
|
9f6686a13d | ||
|
|
c6ff7c0d5b | ||
|
|
a9e5a84c03 | ||
|
|
67ca528fea | ||
|
|
6d9b21c5d0 | ||
|
|
ddffdfc095 | ||
|
|
a58290ed79 | ||
|
|
3488ca3570 | ||
|
|
c542ce3369 | ||
|
|
15f0be848d | ||
|
|
1c3fa67374 | ||
|
|
0ac59d569d | ||
|
|
d8aa2f85df | ||
|
|
64d6938cf4 | ||
|
|
0a88719a3a | ||
|
|
0bc94bc24e | ||
|
|
19eb9e7227 | ||
|
|
aa5521dcfb | ||
|
|
2d03847ccd | ||
|
|
d303ac39cb | ||
|
|
48fc85e7fe | ||
|
|
0ea639196a | ||
|
|
6f51725732 | ||
|
|
8622b952ca | ||
|
|
f47c1f1046 | ||
|
|
145ddfc408 | ||
|
|
0bb787b90d | ||
|
|
59f23d7bfd | ||
|
|
4a4795e5f0 | ||
|
|
5b58f74e9a | ||
|
|
32dca3b76b | ||
|
|
6358444900 | ||
|
|
792ad4b5c1 | ||
|
|
d41781987c | ||
|
|
fc6507066e | ||
|
|
bf9c828aef | ||
|
|
7b676b76de | ||
|
|
d5f2333173 | ||
|
|
40e7dbdae9 | ||
|
|
a60daa1c76 | ||
|
|
bc1024caf0 | ||
|
|
a1c428b6e2 | ||
|
|
00f3efb95b | ||
|
|
7f3387a86c | ||
|
|
5462d50177 | ||
|
|
f82bae1668 | ||
|
|
9e60597174 | ||
|
|
afc807ac3f | ||
|
|
58ba4f1263 | ||
|
|
5513845fd5 | ||
|
|
33773ff17e | ||
|
|
64d21bd6d2 | ||
|
|
5210a833a5 | ||
|
|
5b1d5c1220 | ||
|
|
f4617e7b19 | ||
|
|
c426452239 | ||
|
|
73b2f255a9 | ||
|
|
ce463a5360 | ||
|
|
52fa6a7333 | ||
|
|
04298962be | ||
|
|
61f983098b | ||
|
|
32c1f98a02 | ||
|
|
5851b8aca4 | ||
|
|
3e2df5a782 | ||
|
|
f0cdaf94c2 | ||
|
|
48196e67a7 | ||
|
|
80a176fe1f | ||
|
|
42ea7cfae1 | ||
|
|
d2e6c82709 | ||
|
|
23b3f0c3d0 | ||
|
|
e08cea3a23 | ||
|
|
83eb396c40 | ||
|
|
59a383e1ea | ||
|
|
fb7260792f | ||
|
|
d8a485ea7e | ||
|
|
02989fe600 | ||
|
|
648f0676bd | ||
|
|
add5f34619 | ||
|
|
9403429a7a | ||
|
|
37cf0c1144 | ||
|
|
bf1f3e1c4f | ||
|
|
2aa11ae076 | ||
|
|
8888f6a0c9 |
No files matched your search
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "T3 Code Dev",
|
||||
"image": "debian:bookworm",
|
||||
"features": {
|
||||
"ghcr.io/devcontainers-extra/features/bun:1": {},
|
||||
"ghcr.io/devcontainers/features/node:1": {
|
||||
"version": "24",
|
||||
"nodeGypDependencies": true
|
||||
},
|
||||
"ghcr.io/devcontainers/features/python:1": {
|
||||
"version": "3.12"
|
||||
}
|
||||
},
|
||||
"postCreateCommand": {
|
||||
"bun-install": "bun install --backend=copyfile --frozen-lockfile"
|
||||
},
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
"extensions": ["oxc.oxc-vscode"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
# Remote Architecture
|
||||
|
||||
This document describes the target architecture for first-class remote environments in T3 Code.
|
||||
|
||||
It is intentionally architecture-first. It does not define a complete implementation plan or user-facing rollout checklist. The goal is to establish the core model so remote support can be added without another broad rewrite.
|
||||
|
||||
## Goals
|
||||
|
||||
- Treat remote environments as first-class product primitives, not special cases.
|
||||
- Support multiple ways to reach the same environment.
|
||||
- Keep the T3 server as the execution boundary.
|
||||
- Let desktop, mobile, and web all share the same conceptual model.
|
||||
- Avoid introducing a local control plane unless product pressure proves it is necessary.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Replacing the existing WebSocket server boundary with a custom transport protocol.
|
||||
- Making SSH the only remote story.
|
||||
- Syncing provider auth across machines.
|
||||
- Shipping every access method in the first iteration.
|
||||
|
||||
## High-level architecture
|
||||
|
||||
T3 already has a clean runtime boundary: the client talks to a T3 server over HTTP/WebSocket, and the server owns orchestration, providers, terminals, git, and filesystem operations.
|
||||
|
||||
Remote support should preserve that boundary.
|
||||
|
||||
```text
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ Client (desktop / mobile / web) │
|
||||
│ │
|
||||
│ - known environments │
|
||||
│ - connection manager │
|
||||
│ - environment-aware routing │
|
||||
└───────────────┬──────────────────────────────┘
|
||||
│
|
||||
│ resolves one access endpoint
|
||||
│
|
||||
┌───────────────▼──────────────────────────────┐
|
||||
│ Access method │
|
||||
│ │
|
||||
│ - direct ws / wss │
|
||||
│ - tunneled ws / wss │
|
||||
│ - desktop-managed ssh bootstrap + forward │
|
||||
└───────────────┬──────────────────────────────┘
|
||||
│
|
||||
│ connects to one T3 server
|
||||
│
|
||||
┌───────────────▼──────────────────────────────┐
|
||||
│ Execution environment = one T3 server │
|
||||
│ │
|
||||
│ - environment identity │
|
||||
│ - provider state │
|
||||
│ - projects / threads / terminals │
|
||||
│ - git / filesystem / process runtime │
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
The important decision is that remoteness is expressed at the environment connection layer, not by splitting the T3 runtime itself.
|
||||
|
||||
## Domain model
|
||||
|
||||
### ExecutionEnvironment
|
||||
|
||||
An `ExecutionEnvironment` is one running T3 server instance.
|
||||
|
||||
It is the unit that owns:
|
||||
|
||||
- provider availability and auth state
|
||||
- model availability
|
||||
- projects and threads
|
||||
- terminal processes
|
||||
- filesystem access
|
||||
- git operations
|
||||
- server settings
|
||||
|
||||
It is identified by a stable `environmentId`.
|
||||
|
||||
This is the shared cross-client primitive. Desktop, mobile, and web should all reason about the same concept here.
|
||||
|
||||
### KnownEnvironment
|
||||
|
||||
A `KnownEnvironment` is a client-side saved entry for an environment the client knows how to reach.
|
||||
|
||||
It is not server-authored. It is local to a device or client profile.
|
||||
|
||||
Examples:
|
||||
|
||||
- a saved LAN URL
|
||||
- a saved public `wss://` endpoint
|
||||
- a desktop-managed SSH host entry
|
||||
- a saved tunneled environment
|
||||
|
||||
A known environment may or may not know the target `environmentId` before first successful connect.
|
||||
|
||||
### AccessEndpoint
|
||||
|
||||
An `AccessEndpoint` is one concrete way to reach a known environment.
|
||||
|
||||
This is the key abstraction that keeps SSH from taking over the model.
|
||||
|
||||
A single environment may have many endpoints:
|
||||
|
||||
- `wss://t3.example.com`
|
||||
- `ws://10.0.0.25:3773`
|
||||
- a tunneled relay URL
|
||||
- a desktop-managed SSH tunnel that resolves to a local forwarded WebSocket URL
|
||||
|
||||
The environment stays the same. Only the access path changes.
|
||||
|
||||
### RepositoryIdentity
|
||||
|
||||
`RepositoryIdentity` remains a best-effort logical repo grouping mechanism across environments.
|
||||
|
||||
It is not used for routing. It is only used for UI grouping and correlation between local and remote clones of the same repository.
|
||||
|
||||
### Workspace / Project
|
||||
|
||||
The current `Project` model remains environment-local.
|
||||
|
||||
That means:
|
||||
|
||||
- a local clone and a remote clone are different projects
|
||||
- they may share a `RepositoryIdentity`
|
||||
- threads still bind to one project in one environment
|
||||
|
||||
## Access methods
|
||||
|
||||
Access methods answer one question:
|
||||
|
||||
How does the client speak WebSocket to a T3 server?
|
||||
|
||||
They do not answer:
|
||||
|
||||
- how the server got started
|
||||
- who manages the server process
|
||||
- whether the environment is local or remote
|
||||
|
||||
### 1. Direct WebSocket access
|
||||
|
||||
Examples:
|
||||
|
||||
- `ws://10.0.0.15:3773`
|
||||
- `wss://t3.example.com`
|
||||
|
||||
This is the base model and should be the first-class default.
|
||||
|
||||
Benefits:
|
||||
|
||||
- works for desktop, mobile, and web
|
||||
- no client-specific process management required
|
||||
- best fit for hosted or self-managed remote T3 deployments
|
||||
|
||||
### 2. Tunneled WebSocket access
|
||||
|
||||
Examples:
|
||||
|
||||
- public relay URLs
|
||||
- private network relay URLs
|
||||
- local tunnel products such as pipenet
|
||||
|
||||
This is still direct WebSocket access from the client's perspective. The difference is that the route is mediated by a tunnel or relay.
|
||||
|
||||
For T3, tunnels are best modeled as another `AccessEndpoint`, not as a different kind of environment.
|
||||
|
||||
This is especially useful when:
|
||||
|
||||
- the host is behind NAT
|
||||
- inbound ports are unavailable
|
||||
- mobile must reach a desktop-hosted environment
|
||||
- a machine should be reachable without exposing raw LAN or public ports
|
||||
|
||||
### 3. Desktop-managed SSH access
|
||||
|
||||
SSH is an access and launch helper, not a separate environment type.
|
||||
|
||||
The desktop main process can use SSH to:
|
||||
|
||||
- reach a machine
|
||||
- probe it
|
||||
- launch or reuse a remote T3 server
|
||||
- establish a local port forward
|
||||
|
||||
After that, the renderer should still connect using an ordinary WebSocket URL against the forwarded local port.
|
||||
|
||||
This keeps the renderer transport model consistent with every other access method.
|
||||
|
||||
## Launch methods
|
||||
|
||||
Launch methods answer a different question:
|
||||
|
||||
How does a T3 server come to exist on the target machine?
|
||||
|
||||
Launch and access should stay separate in the design.
|
||||
|
||||
### 1. Pre-existing server
|
||||
|
||||
The simplest launch method is no launch at all.
|
||||
|
||||
The user or operator already runs T3 on the target machine, and the client connects through a direct or tunneled WebSocket endpoint.
|
||||
|
||||
This should be the first remote mode shipped because it validates the environment model with minimal extra machinery.
|
||||
|
||||
### 2. Desktop-managed remote launch over SSH
|
||||
|
||||
This is the main place where Zed is a useful reference.
|
||||
|
||||
Useful ideas to borrow from Zed:
|
||||
|
||||
- remote probing
|
||||
- platform detection
|
||||
- session directories with pid/log metadata
|
||||
- reconnect-friendly launcher behavior
|
||||
- desktop-owned connection UX
|
||||
|
||||
What should be different in T3:
|
||||
|
||||
- no custom stdio/socket proxy protocol between renderer and remote runtime
|
||||
- no attempt to make the remote runtime look like an editor transport
|
||||
- keep the final client-to-server connection as WebSocket
|
||||
|
||||
The recommended T3 flow is:
|
||||
|
||||
1. Desktop connects over SSH.
|
||||
2. Desktop probes the remote machine and verifies T3 availability.
|
||||
3. Desktop launches or reuses a remote T3 server.
|
||||
4. Desktop establishes local port forwarding.
|
||||
5. Renderer connects to the forwarded WebSocket endpoint as a normal environment.
|
||||
|
||||
### 3. Client-managed local publish
|
||||
|
||||
This is the inverse of remote launch: a local T3 server is already running, and the client publishes it through a tunnel.
|
||||
|
||||
This is useful for:
|
||||
|
||||
- exposing a desktop-hosted environment to mobile
|
||||
- temporary remote access without changing router or firewall settings
|
||||
|
||||
This is still a launch concern, not a new environment kind.
|
||||
|
||||
## Why access and launch must stay separate
|
||||
|
||||
These concerns are easy to conflate, but separating them prevents architectural drift.
|
||||
|
||||
Examples:
|
||||
|
||||
- A manually hosted T3 server might be reached through direct `wss`.
|
||||
- The same server might also be reachable through a tunnel.
|
||||
- An SSH-managed server might be launched over SSH but then reached through forwarded WebSocket.
|
||||
- A local desktop server might be published through a tunnel for mobile.
|
||||
|
||||
In all of those cases, the `ExecutionEnvironment` is the same kind of thing.
|
||||
|
||||
Only the launch and access paths differ.
|
||||
|
||||
## Security model
|
||||
|
||||
Remote support must assume that some environments will be reachable over untrusted networks.
|
||||
|
||||
That means:
|
||||
|
||||
- remote-capable environments should require explicit authentication
|
||||
- tunnel exposure should not rely on obscurity
|
||||
- client-saved endpoints should carry enough auth metadata to reconnect safely
|
||||
|
||||
T3 already supports a WebSocket auth token on the server. That should become a first-class part of environment access rather than remaining an incidental query parameter convention.
|
||||
|
||||
For publicly reachable environments, authenticated access should be treated as required.
|
||||
|
||||
## Relationship to Zed
|
||||
|
||||
Zed is a useful reference implementation for managed remote launch and reconnect behavior.
|
||||
|
||||
The relevant lessons are:
|
||||
|
||||
- remote bootstrap should be explicit
|
||||
- reconnect should be first-class
|
||||
- connection UX belongs in the client shell
|
||||
- runtime ownership should stay clearly on the remote host
|
||||
|
||||
The important mismatch is transport shape.
|
||||
|
||||
Zed needs a custom proxy/server protocol because its remote boundary sits below the editor and project runtime.
|
||||
|
||||
T3 should not copy that part.
|
||||
|
||||
T3 already has the right runtime boundary:
|
||||
|
||||
- one T3 server per environment
|
||||
- ordinary HTTP/WebSocket between client and environment
|
||||
|
||||
So T3 should borrow Zed's launch discipline, not its transport protocol.
|
||||
|
||||
## Recommended rollout
|
||||
|
||||
1. First-class known environments and access endpoints.
|
||||
2. Direct `ws` / `wss` remote environments.
|
||||
3. Authenticated tunnel-backed environments.
|
||||
4. Desktop-managed SSH launch and forwarding.
|
||||
5. Multi-environment UI improvements after the base runtime path is proven.
|
||||
|
||||
This ordering keeps the architecture network-first and transport-agnostic while still leaving room for richer managed remote flows.
|
||||
@@ -0,0 +1,2 @@
|
||||
# git autocrlf=true converts LF to CRLF on Windows, causing issues with oxfmt
|
||||
* text=auto eol=lf
|
||||
+2
-1
@@ -28,4 +28,5 @@ github:realAhmedRoach
|
||||
github:shiroyasha9
|
||||
github:Yash-Singh1
|
||||
github:eggfriedrice24
|
||||
github:Ymit24
|
||||
github:Ymit24
|
||||
github:shivamhwp
|
||||
@@ -10,6 +10,7 @@ jobs:
|
||||
quality:
|
||||
name: Format, Lint, Typecheck, Test, Browser Test, Build
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
@@ -71,11 +72,12 @@ jobs:
|
||||
- name: Verify preload bundle output
|
||||
run: |
|
||||
test -f apps/desktop/dist-electron/preload.js
|
||||
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
|
||||
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
|
||||
|
||||
release_smoke:
|
||||
name: Release Smoke
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
@@ -124,25 +124,49 @@ jobs:
|
||||
group: pr-size-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
steps:
|
||||
- name: Checkout base repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Sync PR size label
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
|
||||
with:
|
||||
script: |
|
||||
const { execFileSync } = require("node:child_process");
|
||||
|
||||
const issueNumber = context.payload.pull_request.number;
|
||||
const baseSha = context.payload.pull_request.base.sha;
|
||||
const headSha = context.payload.pull_request.head.sha;
|
||||
const headTrackingRef = `refs/remotes/pr-size/${issueNumber}`;
|
||||
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
|
||||
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
|
||||
// Keep this aligned with the repo's test entrypoints and test-only support files.
|
||||
const testFilePatterns = [
|
||||
/(^|\/)__tests__(\/|$)/,
|
||||
/(^|\/)tests?(\/|$)/,
|
||||
/^apps\/server\/integration\//,
|
||||
/\.(test|spec|browser|integration)\.[^.\/]+$/,
|
||||
const testExcludePathspecs = [
|
||||
":(glob,exclude)**/__tests__/**",
|
||||
":(glob,exclude)**/test/**",
|
||||
":(glob,exclude)**/tests/**",
|
||||
":(glob,exclude)apps/server/integration/**",
|
||||
":(glob,exclude)**/*.test.*",
|
||||
":(glob,exclude)**/*.spec.*",
|
||||
":(glob,exclude)**/*.browser.*",
|
||||
":(glob,exclude)**/*.integration.*",
|
||||
];
|
||||
|
||||
const isTestFile = (filename) =>
|
||||
testFilePatterns.some((pattern) => pattern.test(filename));
|
||||
const sumNumstat = (text) =>
|
||||
text
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.reduce((total, line) => {
|
||||
const [insertionsRaw = "0", deletionsRaw = "0"] = line.split("\t");
|
||||
const additions =
|
||||
insertionsRaw === "-" ? 0 : Number.parseInt(insertionsRaw, 10) || 0;
|
||||
const deletions =
|
||||
deletionsRaw === "-" ? 0 : Number.parseInt(deletionsRaw, 10) || 0;
|
||||
|
||||
return total + additions + deletions;
|
||||
}, 0);
|
||||
|
||||
const resolveSizeLabel = (totalChangedLines) => {
|
||||
if (totalChangedLines < 10) {
|
||||
@@ -168,40 +192,53 @@ jobs:
|
||||
return "size:XXL";
|
||||
};
|
||||
|
||||
const files = await github.paginate(
|
||||
github.rest.pulls.listFiles,
|
||||
execFileSync("git", ["fetch", "--no-tags", "origin", baseSha], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
|
||||
execFileSync(
|
||||
"git",
|
||||
["fetch", "--no-tags", "origin", `+refs/pull/${issueNumber}/head:${headTrackingRef}`],
|
||||
{
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
pull_number: issueNumber,
|
||||
per_page: 100,
|
||||
stdio: "inherit",
|
||||
},
|
||||
(response) => response.data,
|
||||
);
|
||||
|
||||
if (files.length >= 3000) {
|
||||
const resolvedHeadSha = execFileSync("git", ["rev-parse", headTrackingRef], {
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
|
||||
if (resolvedHeadSha !== headSha) {
|
||||
core.warning(
|
||||
"The GitHub pull request files API may truncate results at 3,000 files; PR size may be undercounted.",
|
||||
`Fetched head SHA ${resolvedHeadSha} does not match pull request head SHA ${headSha}; using fetched ref for sizing.`,
|
||||
);
|
||||
}
|
||||
|
||||
let testChangedLines = 0;
|
||||
let nonTestChangedLines = 0;
|
||||
execFileSync("git", ["cat-file", "-e", `${baseSha}^{commit}`], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
|
||||
for (const file of files) {
|
||||
const changedLinesForFile = (file.additions ?? 0) + (file.deletions ?? 0);
|
||||
const diffArgs = [
|
||||
"diff",
|
||||
"--numstat",
|
||||
"--ignore-all-space",
|
||||
"--ignore-blank-lines",
|
||||
`${baseSha}...${resolvedHeadSha}`,
|
||||
];
|
||||
|
||||
if (changedLinesForFile === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isTestFile(file.filename)) {
|
||||
testChangedLines += changedLinesForFile;
|
||||
continue;
|
||||
}
|
||||
|
||||
nonTestChangedLines += changedLinesForFile;
|
||||
}
|
||||
const totalChangedLines = sumNumstat(
|
||||
execFileSync(
|
||||
"git",
|
||||
diffArgs,
|
||||
{ encoding: "utf8" },
|
||||
),
|
||||
);
|
||||
const nonTestChangedLines = sumNumstat(
|
||||
execFileSync("git", [...diffArgs, "--", ".", ...testExcludePathspecs], {
|
||||
encoding: "utf8",
|
||||
}),
|
||||
);
|
||||
const testChangedLines = Math.max(0, totalChangedLines - nonTestChangedLines);
|
||||
|
||||
const changedLines = nonTestChangedLines === 0 ? testChangedLines : nonTestChangedLines;
|
||||
const nextLabelName = resolveSizeLabel(changedLines);
|
||||
|
||||
@@ -19,6 +19,7 @@ jobs:
|
||||
preflight:
|
||||
name: Preflight
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
outputs:
|
||||
version: ${{ steps.release_meta.outputs.version }}
|
||||
tag: ${{ steps.release_meta.outputs.tag }}
|
||||
@@ -81,6 +82,7 @@ jobs:
|
||||
name: Build ${{ matrix.label }}
|
||||
needs: preflight
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -227,6 +229,7 @@ jobs:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, build]
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
@@ -260,6 +263,7 @@ jobs:
|
||||
name: Publish GitHub Release
|
||||
needs: [preflight, build, publish_cli]
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
@@ -307,6 +311,7 @@ jobs:
|
||||
name: Finalize release
|
||||
needs: [preflight, release]
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- id: app_token
|
||||
name: Mint release app token
|
||||
|
||||
@@ -12,6 +12,7 @@ packages/*/dist
|
||||
build/
|
||||
.logs/
|
||||
release/
|
||||
release-mock/
|
||||
.t3
|
||||
.idea/
|
||||
apps/web/.playwright
|
||||
@@ -20,3 +21,4 @@ apps/web/src/components/__screenshots__
|
||||
.vitest-*
|
||||
__screenshots__/
|
||||
.tanstack
|
||||
squashfs-root/
|
||||
+3
-1
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
||||
"ignorePatterns": [
|
||||
".reference",
|
||||
".plans",
|
||||
"dist",
|
||||
"dist-electron",
|
||||
@@ -8,7 +9,8 @@
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo",
|
||||
"**/routeTree.gen.ts",
|
||||
"apps/web/public/mockServiceWorker.js"
|
||||
"apps/web/public/mockServiceWorker.js",
|
||||
"apps/web/src/lib/vendor/qrcodegen.ts"
|
||||
],
|
||||
"sortPackageJson": {}
|
||||
}
|
||||
@@ -0,0 +1,823 @@
|
||||
# Server Auth Model Plan
|
||||
|
||||
## Purpose
|
||||
|
||||
Define the long-term server auth architecture for T3 Code before first-class remote environments ship.
|
||||
|
||||
This plan is deliberately broader than the current WebSocket token check and narrower than a complete remote collaboration system. The goal is to make the server secure by default, keep local desktop UX frictionless, and leave clean integration points for future remote access methods.
|
||||
|
||||
This document is written in terms of Effect-native services and layers because auth needs to be a core runtime concern, not route-local glue code.
|
||||
|
||||
## Primary goals
|
||||
|
||||
- Make auth server-wide, not WebSocket-only.
|
||||
- Make insecure exposure hard to do accidentally.
|
||||
- Preserve zero-login local desktop UX for desktop-managed environments.
|
||||
- Support browser-native pairing and session auth.
|
||||
- Leave room for native/mobile credentials later without rewriting the server boundary.
|
||||
- Keep auth separate from transport and launch method.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Full multi-user authorization and RBAC.
|
||||
- OAuth / SSO / enterprise identity.
|
||||
- Passkeys or biometric UX in v1.
|
||||
- Syncing auth state across environments.
|
||||
- Designing the full remote environment product in this document.
|
||||
|
||||
## Core decisions
|
||||
|
||||
### 1. Auth is a server concern
|
||||
|
||||
Every privileged surface of the T3 server must go through the same auth policy engine:
|
||||
|
||||
- HTTP routes
|
||||
- WebSocket upgrades
|
||||
- RPC methods reached through WebSocket
|
||||
|
||||
The current split where [`/ws`](../apps/server/src/ws.ts) checks `authToken` but routes in [`http.ts`](../apps/server/src/http.ts) do not is not sufficient for a remote-capable product.
|
||||
|
||||
### 2. Pairing and session are different things
|
||||
|
||||
The system should distinguish:
|
||||
|
||||
- bootstrap credentials
|
||||
- session credentials
|
||||
|
||||
Bootstrap credentials are short-lived and high-trust. They allow a client to become authenticated.
|
||||
|
||||
Session credentials are the durable credentials used after pairing.
|
||||
|
||||
Bootstrap should never become the long-lived request credential.
|
||||
|
||||
### 3. Auth and transport are separate
|
||||
|
||||
Auth must not be defined by how the client reached the server.
|
||||
|
||||
Examples:
|
||||
|
||||
- local desktop-managed server
|
||||
- LAN `ws://`
|
||||
- public `wss://`
|
||||
- tunneled `wss://`
|
||||
- SSH-forwarded `ws://127.0.0.1:<port>`
|
||||
|
||||
All of these should feed into the same auth model.
|
||||
|
||||
### 4. Exposure level changes defaults
|
||||
|
||||
The more exposed an environment is, the narrower the safe default should be.
|
||||
|
||||
Safe default expectations:
|
||||
|
||||
- local desktop-managed: auto-pair allowed
|
||||
- loopback browser access: explicit bootstrap allowed
|
||||
- non-loopback bind: auth required
|
||||
- tunnel/public endpoint: auth required, explicit enablement required
|
||||
|
||||
### 5. Browser and native clients may use different session credentials
|
||||
|
||||
The auth model should support more than one session credential type even if only one ships first.
|
||||
|
||||
Examples:
|
||||
|
||||
- browser session cookie
|
||||
- native bearer/device token
|
||||
|
||||
This should be represented in the model now, even if browser cookies are the first implementation.
|
||||
|
||||
## Target auth domain
|
||||
|
||||
### Route classes
|
||||
|
||||
Every route or transport entrypoint should be classified as one of:
|
||||
|
||||
1. `public`
|
||||
2. `bootstrap`
|
||||
3. `authenticated`
|
||||
|
||||
#### `public`
|
||||
|
||||
Unauthenticated by definition.
|
||||
|
||||
Should be extremely small. Examples:
|
||||
|
||||
- static shell needed to render the pairing/login UI
|
||||
- favicon/assets required for the pairing screen
|
||||
- a minimal server health/version endpoint if needed
|
||||
|
||||
#### `bootstrap`
|
||||
|
||||
Used only to exchange a bootstrap credential for a session.
|
||||
|
||||
Examples:
|
||||
|
||||
- Initial bootstrap envelope over file descriptor at startup
|
||||
- `POST /api/auth/bootstrap`
|
||||
- `GET /api/auth/session` if unauthenticated checks are part of bootstrap UX
|
||||
|
||||
#### `authenticated`
|
||||
|
||||
Everything that reveals machine state or mutates it.
|
||||
|
||||
Examples:
|
||||
|
||||
- WebSocket upgrade
|
||||
- orchestration snapshot and events
|
||||
- terminal open/write/close
|
||||
- project search and file writes
|
||||
- git routes
|
||||
- attachments
|
||||
- project favicon lookup
|
||||
- server settings
|
||||
|
||||
The default stance should be: if it touches the machine, it is authenticated.
|
||||
|
||||
## Credential model
|
||||
|
||||
### Bootstrap credentials
|
||||
|
||||
Initial credential types to model:
|
||||
|
||||
- `desktop-bootstrap`
|
||||
- `one-time-token`
|
||||
|
||||
Possible future credential types:
|
||||
|
||||
- `device-code`
|
||||
- `passkey-assertion`
|
||||
- `external-identity`
|
||||
|
||||
#### `desktop-bootstrap`
|
||||
|
||||
Used when the desktop shell manages the server and should be the only default pairing method for desktop-local environments.
|
||||
|
||||
Properties:
|
||||
|
||||
- launcher-provided
|
||||
- short-lived
|
||||
- one-time or bounded-use
|
||||
- never shown to the user as a reusable password
|
||||
|
||||
#### `one-time-token`
|
||||
|
||||
Used for explicit browser/mobile pairing flows.
|
||||
|
||||
Properties:
|
||||
|
||||
- short TTL
|
||||
- one-time use
|
||||
- safe to embed in a pairing URL fragment
|
||||
- exchanged for a session credential
|
||||
|
||||
### Session credentials
|
||||
|
||||
Initial credential types to model:
|
||||
|
||||
- `browser-session-cookie`
|
||||
- `bearer-session-token`
|
||||
|
||||
#### `browser-session-cookie`
|
||||
|
||||
Primary browser credential.
|
||||
|
||||
Properties:
|
||||
|
||||
- signed
|
||||
- `HttpOnly`
|
||||
- bounded lifetime
|
||||
- revocable by server key rotation or session invalidation
|
||||
|
||||
#### `bearer-session-token`
|
||||
|
||||
Reserved for native/mobile or non-browser clients.
|
||||
|
||||
Properties:
|
||||
|
||||
- opaque token, not a bootstrap secret
|
||||
- long enough lifetime to survive reconnects
|
||||
- stored in secure client storage when available
|
||||
|
||||
## Auth policy model
|
||||
|
||||
Auth behavior should be driven by an explicit environment auth policy, not route-local heuristics.
|
||||
|
||||
### Policy examples
|
||||
|
||||
#### `DesktopManagedLocalPolicy`
|
||||
|
||||
Default for desktop-managed local server.
|
||||
|
||||
Allowed bootstrap methods:
|
||||
|
||||
- `desktop-bootstrap`
|
||||
|
||||
Allowed session methods:
|
||||
|
||||
- `browser-session-cookie`
|
||||
|
||||
Disabled by default:
|
||||
|
||||
- `one-time-token`
|
||||
- `bearer-session-token`
|
||||
- password login
|
||||
- public pairing
|
||||
|
||||
#### `LoopbackBrowserPolicy`
|
||||
|
||||
Used for browser access on localhost without desktop-managed bootstrap.
|
||||
|
||||
Allowed bootstrap methods:
|
||||
|
||||
- `one-time-token`
|
||||
|
||||
Allowed session methods:
|
||||
|
||||
- `browser-session-cookie`
|
||||
|
||||
#### `RemoteReachablePolicy`
|
||||
|
||||
Used when binding non-loopback or using an explicit remote/tunnel workflow.
|
||||
|
||||
Allowed bootstrap methods:
|
||||
|
||||
- `one-time-token`
|
||||
- possibly `desktop-bootstrap` when a desktop shell is brokering access
|
||||
|
||||
Allowed session methods:
|
||||
|
||||
- `browser-session-cookie`
|
||||
- `bearer-session-token`
|
||||
|
||||
#### `UnsafeNoAuthPolicy`
|
||||
|
||||
Should exist only as an explicit escape hatch.
|
||||
|
||||
Requirements:
|
||||
|
||||
- explicit opt-in flag
|
||||
- loud startup warnings
|
||||
- never defaulted automatically
|
||||
|
||||
## Effect-native service model
|
||||
|
||||
### `ServerAuth`
|
||||
|
||||
The main auth facade used by HTTP routes and WebSocket upgrade handling.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- classify requests
|
||||
- authenticate requests
|
||||
- authorize bootstrap attempts
|
||||
- create sessions from bootstrap credentials
|
||||
- enforce policy by environment mode
|
||||
|
||||
Sketch:
|
||||
|
||||
```ts
|
||||
export interface ServerAuthShape {
|
||||
readonly getCapabilities: Effect.Effect<AuthCapabilities>;
|
||||
readonly authenticateHttpRequest: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
routeClass: RouteAuthClass,
|
||||
) => Effect.Effect<AuthContext, AuthError>;
|
||||
readonly authenticateWebSocketUpgrade: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthContext, AuthError>;
|
||||
readonly exchangeBootstrapCredential: (
|
||||
input: BootstrapExchangeInput,
|
||||
) => Effect.Effect<SessionGrant, AuthError>;
|
||||
}
|
||||
|
||||
export class ServerAuth extends ServiceMap.Service<ServerAuth, ServerAuthShape>()(
|
||||
"t3/ServerAuth",
|
||||
) {}
|
||||
```
|
||||
|
||||
### `BootstrapCredentialService`
|
||||
|
||||
Owns issuance, storage, validation, and consumption of bootstrap credentials.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- issue desktop bootstrap grants
|
||||
- issue one-time pairing tokens
|
||||
- validate TTL and single-use semantics
|
||||
- consume bootstrap grants atomically
|
||||
|
||||
Sketch:
|
||||
|
||||
```ts
|
||||
export interface BootstrapCredentialServiceShape {
|
||||
readonly issueDesktopBootstrap: (
|
||||
input: IssueDesktopBootstrapInput,
|
||||
) => Effect.Effect<BootstrapCredential>;
|
||||
readonly issueOneTimeToken: (
|
||||
input: IssueOneTimeTokenInput,
|
||||
) => Effect.Effect<BootstrapCredential>;
|
||||
readonly consume: (
|
||||
presented: PresentedBootstrapCredential,
|
||||
) => Effect.Effect<ConsumedBootstrapCredential, BootstrapCredentialError>;
|
||||
}
|
||||
```
|
||||
|
||||
### `SessionCredentialService`
|
||||
|
||||
Owns creation and validation of authenticated sessions.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- mint cookie sessions
|
||||
- mint bearer sessions
|
||||
- validate active session credentials
|
||||
- revoke sessions if needed later
|
||||
|
||||
Sketch:
|
||||
|
||||
```ts
|
||||
export interface SessionCredentialServiceShape {
|
||||
readonly createBrowserSession: (
|
||||
input: CreateSessionFromBootstrapInput,
|
||||
) => Effect.Effect<BrowserSessionGrant, SessionCredentialError>;
|
||||
readonly createBearerSession: (
|
||||
input: CreateSessionFromBootstrapInput,
|
||||
) => Effect.Effect<BearerSessionGrant, SessionCredentialError>;
|
||||
readonly authenticateCookie: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthContext, SessionCredentialError>;
|
||||
readonly authenticateBearer: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthContext, SessionCredentialError>;
|
||||
}
|
||||
```
|
||||
|
||||
### `ServerAuthPolicy`
|
||||
|
||||
Pure policy/config service that decides which credential types are allowed.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- map runtime mode and bind/exposure settings to allowed auth methods
|
||||
- answer whether a route can be public
|
||||
- answer whether remote exposure requires auth
|
||||
|
||||
This should stay mostly pure and cheap to test.
|
||||
|
||||
### `ServerSecretStore`
|
||||
|
||||
Owns long-lived server signing keys and secrets.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- get or create signing key
|
||||
- rotate signing key
|
||||
- abstract secure OS-backed storage vs filesystem fallback
|
||||
|
||||
Important:
|
||||
|
||||
- prefer platform secure storage when available
|
||||
- support hardened filesystem fallback for headless/server-only environments
|
||||
|
||||
### `BrowserSessionCookieCodec`
|
||||
|
||||
Focused utility service for cookie encode/decode/signing behavior.
|
||||
|
||||
This should not own policy. It should only own the cookie format.
|
||||
|
||||
### `AuthRouteGuards`
|
||||
|
||||
Thin helper layer used by routes to enforce auth consistently.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- require auth for HTTP route handlers
|
||||
- classify route auth mode
|
||||
- convert auth failures into `401` / `403`
|
||||
|
||||
This prevents every route from re-implementing the same pattern.
|
||||
|
||||
Integrates with `HttpRouter.middleware` to enforce auth consistently.
|
||||
|
||||
## Suggested layer graph
|
||||
|
||||
```text
|
||||
ServerSecretStore
|
||||
├─> BootstrapCredentialService
|
||||
├─> BrowserSessionCookieCodec
|
||||
└─> SessionCredentialService
|
||||
|
||||
ServerAuthPolicy
|
||||
├─> BootstrapCredentialService
|
||||
├─> SessionCredentialService
|
||||
└─> ServerAuth
|
||||
|
||||
ServerAuth
|
||||
└─> AuthRouteGuards
|
||||
```
|
||||
|
||||
Layer naming should follow existing repo style:
|
||||
|
||||
- `ServerSecretStoreLive`
|
||||
- `BootstrapCredentialServiceLive`
|
||||
- `SessionCredentialServiceLive`
|
||||
- `ServerAuthPolicyLive`
|
||||
- `ServerAuthLive`
|
||||
- `AuthRouteGuardsLive`
|
||||
|
||||
## High-level implementation examples
|
||||
|
||||
### Example: WebSocket upgrade auth
|
||||
|
||||
Current state:
|
||||
|
||||
- `authToken` query param is checked in [`ws.ts`](../apps/server/src/ws.ts)
|
||||
|
||||
Target shape:
|
||||
|
||||
```ts
|
||||
const websocketUpgradeAuth = HttpMiddleware.make((httpApp) =>
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
yield* serverAuth.authenticateWebSocketUpgrade(request);
|
||||
return yield* httpApp;
|
||||
}),
|
||||
);
|
||||
```
|
||||
|
||||
Then the `/ws` route becomes:
|
||||
|
||||
```ts
|
||||
export const websocketRpcRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
"/ws",
|
||||
rpcWebSocketHttpEffect.pipe(
|
||||
websocketUpgradeAuth,
|
||||
Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)),
|
||||
),
|
||||
);
|
||||
```
|
||||
|
||||
This keeps the route itself declarative and makes auth compose like normal HTTP middleware.
|
||||
|
||||
### Example: authenticated HTTP route
|
||||
|
||||
For routes like attachments or project favicon:
|
||||
|
||||
```ts
|
||||
const authenticatedRoute = (routeClass: RouteAuthClass) =>
|
||||
HttpMiddleware.make((httpApp) =>
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
yield* serverAuth.authenticateHttpRequest(request, routeClass);
|
||||
return yield* httpApp;
|
||||
}),
|
||||
);
|
||||
```
|
||||
|
||||
Then:
|
||||
|
||||
```ts
|
||||
export const attachmentsRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
`${ATTACHMENTS_ROUTE_PREFIX}/*`,
|
||||
serveAttachment.pipe(
|
||||
authenticatedRoute(RouteAuthClass.Authenticated),
|
||||
Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)),
|
||||
),
|
||||
);
|
||||
```
|
||||
|
||||
### Example: desktop bootstrap exchange
|
||||
|
||||
The desktop shell launches the local server and gets a short-lived bootstrap grant through a trusted side channel.
|
||||
|
||||
That grant is then exchanged for a browser cookie session when the renderer loads.
|
||||
|
||||
Sketch:
|
||||
|
||||
```ts
|
||||
const pairDesktopRenderer = Effect.gen(function* () {
|
||||
const bootstrapService = yield* BootstrapCredentialService;
|
||||
const credential = yield* bootstrapService.issueDesktopBootstrap({
|
||||
audience: "desktop-renderer",
|
||||
ttlMs: 30_000,
|
||||
});
|
||||
return credential;
|
||||
});
|
||||
```
|
||||
|
||||
The renderer then calls a bootstrap endpoint and receives a cookie session. The bootstrap credential is consumed and becomes invalid.
|
||||
|
||||
### Example: one-time pairing URL
|
||||
|
||||
For browser-driven pairing:
|
||||
|
||||
```ts
|
||||
const createPairingToken = Effect.gen(function* () {
|
||||
const bootstrapService = yield* BootstrapCredentialService;
|
||||
return yield* bootstrapService.issueOneTimeToken({
|
||||
ttlMs: 5 * 60_000,
|
||||
audience: "browser",
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
The server can emit a pairing URL where the token lives in the URL fragment so it is not automatically sent to the server before the client explicitly exchanges it.
|
||||
|
||||
## Sequence diagrams
|
||||
|
||||
These flows are meant to anchor the auth model in concrete user journeys.
|
||||
|
||||
The important invariant across all of them is:
|
||||
|
||||
- access method is not the auth method
|
||||
- launch method is not the auth method
|
||||
- bootstrap credential is not the session credential
|
||||
|
||||
### Normal desktop user
|
||||
|
||||
This is the default desktop-managed local flow.
|
||||
|
||||
The desktop shell is trusted to bootstrap the local renderer, but the renderer should still exchange that one-time bootstrap grant for a normal browser session cookie.
|
||||
|
||||
```text
|
||||
Participants:
|
||||
DesktopMain = Electron main
|
||||
SecretStore = secure local secret backend
|
||||
T3Server = local backend child process
|
||||
Frontend = desktop renderer
|
||||
|
||||
DesktopMain -> SecretStore : getOrCreate("server-signing-key")
|
||||
SecretStore --> DesktopMain : signing key available
|
||||
|
||||
DesktopMain -> T3Server : spawn server (--bootstrap-fd ...)
|
||||
DesktopMain -> T3Server : send desktop bootstrap envelope
|
||||
note over T3Server : policy = DesktopManagedLocalPolicy
|
||||
note over T3Server : allowed pairing = desktop-bootstrap only
|
||||
|
||||
Frontend -> DesktopMain : request local bootstrap grant
|
||||
DesktopMain --> Frontend : short-lived desktop bootstrap grant
|
||||
|
||||
Frontend -> T3Server : POST /api/auth/bootstrap
|
||||
T3Server -> T3Server : validate desktop bootstrap grant
|
||||
T3Server -> T3Server : create browser session
|
||||
T3Server --> Frontend : Set-Cookie: session=...
|
||||
|
||||
Frontend -> T3Server : GET /ws + authenticated cookie
|
||||
T3Server -> T3Server : validate cookie session
|
||||
T3Server --> Frontend : websocket accepted
|
||||
```
|
||||
|
||||
### `npx t3` user
|
||||
|
||||
This is the standalone local server flow.
|
||||
|
||||
There is no trusted desktop shell here, so pairing should be explicit.
|
||||
|
||||
```text
|
||||
Participants:
|
||||
UserShell = npx t3 launcher
|
||||
T3Server = standalone local server
|
||||
Browser = browser tab
|
||||
|
||||
UserShell -> T3Server : start server
|
||||
T3Server -> T3Server : getOrCreate("server-signing-key")
|
||||
note over T3Server : policy = LoopbackBrowserPolicy
|
||||
|
||||
UserShell -> T3Server : issue one-time pairing token
|
||||
T3Server --> UserShell : pairing URL or pairing token
|
||||
|
||||
UserShell --> Browser : open /pair?token=...
|
||||
|
||||
Browser -> T3Server : GET /pair?token=...
|
||||
T3Server -> T3Server : validate one-time token
|
||||
T3Server -> T3Server : create browser session
|
||||
T3Server --> Browser : Set-Cookie: session=...
|
||||
T3Server --> Browser : redirect to app
|
||||
|
||||
Browser -> T3Server : GET /ws + authenticated cookie
|
||||
T3Server --> Browser : websocket accepted
|
||||
```
|
||||
|
||||
### Phone user with tunneled host
|
||||
|
||||
This is the explicit remote access flow for a browser on another device.
|
||||
|
||||
The tunnel only provides reachability. It must not imply trust.
|
||||
|
||||
Recommended UX:
|
||||
|
||||
- desktop shows a QR code
|
||||
- desktop also shows a copyable pairing URL
|
||||
- if the phone opens the host URL without a valid token, the server should render a login or pairing screen rather than granting access
|
||||
|
||||
```text
|
||||
Participants:
|
||||
DesktopUser = user at the host machine
|
||||
DesktopMain = desktop app
|
||||
Tunnel = tunnel provider
|
||||
T3Server = T3 server
|
||||
PhoneBrowser = mobile browser
|
||||
|
||||
DesktopUser -> DesktopMain : enable remote access via tunnel
|
||||
DesktopMain -> T3Server : switch policy to RemoteReachablePolicy
|
||||
DesktopMain -> Tunnel : publish local T3 endpoint
|
||||
Tunnel --> DesktopMain : public https/wss URL
|
||||
|
||||
DesktopMain -> T3Server : issue one-time pairing token
|
||||
T3Server --> DesktopMain : pairing token
|
||||
DesktopMain -> DesktopUser : show QR code / shareable URL
|
||||
|
||||
DesktopUser -> PhoneBrowser : scan QR / open URL
|
||||
PhoneBrowser -> Tunnel : GET https://public-host/pair?token=...
|
||||
Tunnel -> T3Server : forward request
|
||||
T3Server -> T3Server : validate one-time token
|
||||
T3Server -> T3Server : create mobile browser session
|
||||
T3Server --> PhoneBrowser : Set-Cookie: session=...
|
||||
T3Server --> PhoneBrowser : redirect to app
|
||||
|
||||
PhoneBrowser -> Tunnel : GET /ws + authenticated cookie
|
||||
Tunnel -> T3Server : forward websocket upgrade
|
||||
T3Server --> PhoneBrowser : websocket accepted
|
||||
```
|
||||
|
||||
### Phone user with private network
|
||||
|
||||
This is operationally similar to the tunnel flow, but the access endpoint is on a private network such as Tailscale.
|
||||
|
||||
The auth flow should stay the same.
|
||||
|
||||
```text
|
||||
Participants:
|
||||
DesktopUser = user at the host machine
|
||||
T3Server = T3 server
|
||||
PrivateNet = tailscale / private LAN
|
||||
PhoneBrowser = mobile browser
|
||||
|
||||
DesktopUser -> T3Server : enable private-network access
|
||||
T3Server -> T3Server : switch policy to RemoteReachablePolicy
|
||||
DesktopUser -> T3Server : issue one-time pairing token
|
||||
T3Server --> DesktopUser : pairing URL / QR
|
||||
|
||||
DesktopUser -> PhoneBrowser : open private-network URL
|
||||
PhoneBrowser -> PrivateNet : GET http(s)://private-host/pair?token=...
|
||||
PrivateNet -> T3Server : route request
|
||||
T3Server -> T3Server : validate one-time token
|
||||
T3Server -> T3Server : create mobile browser session
|
||||
T3Server --> PhoneBrowser : Set-Cookie: session=...
|
||||
T3Server --> PhoneBrowser : redirect to app
|
||||
|
||||
PhoneBrowser -> PrivateNet : GET /ws + authenticated cookie
|
||||
PrivateNet -> T3Server : websocket upgrade
|
||||
T3Server --> PhoneBrowser : websocket accepted
|
||||
```
|
||||
|
||||
### Desktop user adding new SSH hosts
|
||||
|
||||
SSH should be treated as launch and reachability plumbing, not as the long-term auth model.
|
||||
|
||||
The desktop app uses SSH to start or reach the remote server, then the renderer pairs against that server using the same bootstrap/session split as every other environment.
|
||||
|
||||
```text
|
||||
Participants:
|
||||
DesktopUser = local desktop user
|
||||
DesktopMain = desktop app
|
||||
SSH = ssh transport/session
|
||||
RemoteHost = remote machine
|
||||
RemoteT3 = remote T3 server
|
||||
Frontend = desktop renderer
|
||||
|
||||
DesktopUser -> DesktopMain : add SSH host
|
||||
DesktopMain -> SSH : connect to remote host
|
||||
SSH -> RemoteHost : probe environment / verify t3 availability
|
||||
DesktopMain -> SSH : run remote launch command
|
||||
SSH -> RemoteHost : t3 remote launch --json
|
||||
RemoteHost -> RemoteT3 : start or reuse server
|
||||
RemoteT3 --> RemoteHost : port + environment metadata
|
||||
RemoteHost --> SSH : launch result JSON
|
||||
SSH --> DesktopMain : remote server details
|
||||
|
||||
DesktopMain -> SSH : establish local port forward
|
||||
SSH --> DesktopMain : localhost:FORWARDED_PORT ready
|
||||
|
||||
note over RemoteT3 : policy = RemoteReachablePolicy
|
||||
note over DesktopMain,RemoteT3 : desktop may use a trusted bootstrap flow here
|
||||
|
||||
Frontend -> DesktopMain : request bootstrap for selected environment
|
||||
DesktopMain --> Frontend : short-lived bootstrap grant
|
||||
|
||||
Frontend -> RemoteT3 : POST /api/auth/bootstrap via forwarded port
|
||||
RemoteT3 -> RemoteT3 : validate bootstrap grant
|
||||
RemoteT3 -> RemoteT3 : create browser session
|
||||
RemoteT3 --> Frontend : Set-Cookie: session=...
|
||||
|
||||
Frontend -> RemoteT3 : GET /ws + authenticated cookie
|
||||
RemoteT3 --> Frontend : websocket accepted
|
||||
```
|
||||
|
||||
## Storage decisions
|
||||
|
||||
### Server secrets
|
||||
|
||||
Use a `ServerSecretStore` abstraction.
|
||||
|
||||
Preferred order (use a layer for each, resolve on startup):
|
||||
|
||||
1. OS secure storage if available
|
||||
2. hardened filesystem fallback if not
|
||||
|
||||
The filesystem fallback should store only opaque signing material with strict file permissions. It should not store user passwords or reusable third-party credentials.
|
||||
|
||||
### Client credentials
|
||||
|
||||
Client-side credential persistence should prefer secure storage when available:
|
||||
|
||||
- desktop: OS keychain / secure store
|
||||
- mobile: platform secure storage
|
||||
- browser: cookie session for browser auth
|
||||
|
||||
This concern should stay in the client shell/runtime layer, not the server auth layer.
|
||||
|
||||
## What to build now
|
||||
|
||||
These are the parts worth building before remote environments ship:
|
||||
|
||||
1. `ServerAuth` service boundary.
|
||||
2. route classification and route guards.
|
||||
3. `ServerSecretStore` abstraction.
|
||||
4. bootstrap vs session credential split.
|
||||
5. browser session cookie codec as one session method.
|
||||
6. explicit auth capabilities/config surfaced in contracts.
|
||||
|
||||
Even if only one pairing flow is used initially, these seams will keep future remote and mobile work contained.
|
||||
|
||||
## What to add as part of first remote-capable auth
|
||||
|
||||
1. Browser pairing flow using one-time bootstrap token and cookie session.
|
||||
2. Desktop-managed auto-bootstrap for the local desktop-managed environment.
|
||||
3. Auth-required defaults for any non-loopback or explicitly published server.
|
||||
4. Explicit environment auth policy selection instead of scattered `if (host !== localhost)` checks.
|
||||
|
||||
## What to defer
|
||||
|
||||
- passkeys / WebAuthn
|
||||
- iCloud Keychain / Face ID-specific UX
|
||||
- multi-user permissions
|
||||
- collaboration roles
|
||||
- OAuth / SSO
|
||||
- polished session management UI
|
||||
- complex device approval flows
|
||||
|
||||
These can all sit on top of the same bootstrap/session/service split.
|
||||
|
||||
## Relationship to future remote environments
|
||||
|
||||
Remote access is one reason this auth model matters, but the auth model should not be remote-shaped.
|
||||
|
||||
Keep the design focused on:
|
||||
|
||||
- one T3 server
|
||||
- one auth policy
|
||||
- multiple credential types
|
||||
- multiple future access methods
|
||||
|
||||
That keeps the server auth model stable even as access methods expand later.
|
||||
|
||||
## Recommended implementation order
|
||||
|
||||
### Phase 1
|
||||
|
||||
- Introduce route auth classes.
|
||||
- Add `ServerAuth` and `AuthRouteGuards`.
|
||||
- Move existing `authToken` check behind `ServerAuth`.
|
||||
- Require auth for all privileged HTTP routes as well as WebSocket.
|
||||
|
||||
### Phase 2
|
||||
|
||||
- Add `ServerSecretStore` service with platform-specific layer implementations.
|
||||
- `layerOSXKeychain`, `layer
|
||||
- Add bootstrap/session split.
|
||||
- Add browser session cookie support.
|
||||
- Add one-time bootstrap exchange endpoint.
|
||||
|
||||
### Phase 3
|
||||
|
||||
- Add desktop bootstrap flow on top of the same services.
|
||||
- Make desktop-managed local environments default to bootstrap-only pairing.
|
||||
- Surface auth capabilities in shared contracts and renderer bootstrap.
|
||||
|
||||
### Phase 4
|
||||
|
||||
- Add non-browser bearer session support if mobile/native needs it.
|
||||
- Add richer policy modes for remote-reachable environments.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- No privileged HTTP or WebSocket path bypasses auth policy.
|
||||
- Local desktop-managed flows still avoid a visible login screen.
|
||||
- Non-loopback or published environments require explicit authenticated pairing by default.
|
||||
- Bootstrap and session credentials are distinct in code and in behavior.
|
||||
- Auth logic is centralized in Effect services/layers rather than route-local branching.
|
||||
@@ -0,0 +1,89 @@
|
||||
# Replace React Query With AtomRpc + Atom State
|
||||
|
||||
## Summary
|
||||
- Use `effect/unstable/reactivity/AtomRpc` over the existing `WsRpcGroup`; stop wrapping RPC in promises via [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts) and [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts).
|
||||
- Keep Zustand for orchestration read model and UI state.
|
||||
- Keep a narrow `desktopBridge` adapter for dialogs, menus, external links, theme, and updater APIs.
|
||||
- Do not introduce Suspense in this migration. Atom-backed hooks should keep returning `data`, `error`, `isLoading|isPending`, `refresh`, and `mutateAsync`-style surfaces so component churn stays low.
|
||||
|
||||
## Target Architecture
|
||||
- Extract the websocket `RpcClient.Protocol` layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) into `rpc/protocol.ts`.
|
||||
- Define one `AtomRpc.Service` for `WsRpcGroup` in `rpc/client.ts`.
|
||||
- Add `rpc/invalidation.ts` with explicit scoped invalidation keys: `git:${cwd}`, `project:${cwd}`, `checkpoint:${threadId}`, `server-config`.
|
||||
- Add `platform/desktopBridge.ts` as the only browser/desktop facade.
|
||||
- Remove from web by the end: [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts), [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts), [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts), [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx), [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts), and all `*ReactQuery.ts` modules.
|
||||
|
||||
## Phase 1: Infrastructure First
|
||||
1. Extract the shared websocket RPC protocol layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) without changing behavior.
|
||||
2. Build the AtomRpc client on top of that layer.
|
||||
3. Add one temporary `runRpc` helper for imperative handlers that still want `Promise` ergonomics; it must call the AtomRpc service directly and must not reintroduce a facade object.
|
||||
4. Replace manual registry wiring with one app-level registry provider based on `@effect/atom-react`.
|
||||
5. Land this as a no-behavior-change PR.
|
||||
|
||||
## Phase 2: Replace `wsNativeApi`-Owned Push State
|
||||
1. Migrate welcome/config/provider/settings state first, because it is already atom-shaped and is the lowest-risk way to delete `wsNativeApi` responsibilities.
|
||||
2. Replace [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts) with `rpc/serverState.ts`, updated directly from `subscribeServerLifecycle` and `subscribeServerConfig`.
|
||||
3. Keep the current hook names for one PR: `useServerConfig`, `useServerSettings`, `useServerProviders`, `useServerKeybindings`, `useServerWelcomeSubscription`, `useServerConfigUpdatedSubscription`.
|
||||
4. Move bootstrap side effects out of [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx) into a new root bootstrap component mounted from [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
|
||||
5. Delete the `server.getConfig()` fallback logic from [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts); snapshot fetch now lives beside the stream atoms.
|
||||
|
||||
## Phase 3: Replace React Query Domain By Domain
|
||||
1. Replace [gitReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/gitReactQuery.ts) first.
|
||||
2. Add `rpc/gitAtoms.ts` and `rpc/useGit.ts` with `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, and `useGitMutation`.
|
||||
3. Mutation settlement must invalidate scoped keys, not a global cache. `checkout`, `pull`, `init`, `createWorktree`, `removeWorktree`, `preparePullRequestThread`, and stacked actions invalidate `git:${cwd}`. Worktree create/remove also invalidates `project:${cwd}`.
|
||||
4. Replace [projectReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/projectReactQuery.ts) second. `useProjectSearchEntries` must preserve current “keep previous results while loading” behavior.
|
||||
5. Replace [providerReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/providerReactQuery.ts) third. Preserve current checkpoint error normalization and retry/backoff semantics inside the atom effect. Invalidate by `checkpoint:${threadId}`.
|
||||
6. Defer the desktop updater until the last phase.
|
||||
|
||||
## Phase 4: Move Root Invalidation Off `queryClient`
|
||||
1. In [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx), remove `QueryClient` usage and replace the throttled `invalidateQueries` block with throttled invalidation helpers.
|
||||
2. Keep Zustand orchestration/event application unchanged.
|
||||
3. Map current effects exactly:
|
||||
- git or checkpoint-affecting orchestration events touch `checkpoint:${threadId}`
|
||||
- file creation/deletion/restoration touches `project:${cwd}`
|
||||
- config-affecting server events touch `server-config`
|
||||
|
||||
## Phase 5: Remove Imperative `NativeApi` Usage
|
||||
1. Create narrow modules instead of a replacement mega-facade:
|
||||
- `rpc/orchestrationActions.ts`
|
||||
- `rpc/terminalActions.ts`
|
||||
- `rpc/gitActions.ts`
|
||||
- `rpc/projectActions.ts`
|
||||
- `platform/desktopBridge.ts`
|
||||
2. Migrate direct [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) callers by domain, not file-by-file: git-heavy components first, then orchestration/thread actions, then shell/dialog helpers.
|
||||
3. After the last caller is gone, delete [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) and the `window.nativeApi` fallback entirely.
|
||||
4. In the final cleanup PR, remove `NativeApi` from [ipc.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/packages/contracts/src/ipc.ts) if nothing outside web still needs it.
|
||||
|
||||
## Phase 6: Remove React Query Completely
|
||||
1. Delete `@tanstack/react-query` from `apps/web/package.json`.
|
||||
2. Remove `QueryClientProvider` and router context from [router.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/router.ts) and [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
|
||||
3. Replace [desktopUpdateReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/desktopUpdateReactQuery.ts) with a writable atom plus `desktopBridge.onUpdateState`.
|
||||
4. Delete the old query-option tests.
|
||||
|
||||
## Public Interfaces And Types
|
||||
- Preserve the current server-state hook names during the transition.
|
||||
- Add permanent domain hooks: `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, `useProjectSearchEntries`, `useCheckpointDiff`, `useDesktopUpdateState`.
|
||||
- Do not expose raw AtomRpc clients to components.
|
||||
- Do not add Suspense as part of this migration.
|
||||
- Final boundary is direct RPC for server features plus `desktopBridge` for local desktop features.
|
||||
|
||||
## Test Plan
|
||||
- Add unit tests for `rpc/serverState.ts`: snapshot bootstrapping, stream replay, provider/settings updates.
|
||||
- Add unit tests for git/project/checkpoint hooks: loading, error mapping, retry behavior, invalidation, keep-previous-result behavior.
|
||||
- Update the browser harness in [wsRpcHarness.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/test/wsRpcHarness.ts) to assert direct RPC + atom behavior instead of `__resetNativeApiForTests`.
|
||||
- Replace [wsNativeApi.test.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.test.ts), `gitReactQuery.test.ts`, `providerReactQuery.test.ts`, and `desktopUpdateReactQuery.test.ts` with equivalent atom-backed coverage.
|
||||
- Acceptance scenarios:
|
||||
- welcome still bootstraps snapshot and navigation
|
||||
- keybindings toast still responds to config stream updates
|
||||
- git status/branches refresh after checkout/pull/worktree actions
|
||||
- PR resolve dialog keeps cached result while typing
|
||||
- `@` path search refreshes after file mutations and orchestration events
|
||||
- diff panel refreshes when checkpoints arrive
|
||||
- desktop updater still reflects push events and button actions
|
||||
|
||||
## Assumptions And Defaults
|
||||
- Zustand stays in scope; only `react-query` is being removed.
|
||||
- `desktopBridge` remains the only non-RPC boundary.
|
||||
- The migration lands as 5-6 small PRs, each green independently.
|
||||
- Invalidations are explicit and scoped; do not recreate a global cache client abstraction.
|
||||
- Orchestration recovery/order logic stays as-is; only the data-fetching and mutation layer changes.
|
||||
@@ -2,18 +2,42 @@
|
||||
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
|
||||
|
||||
## How to use
|
||||
## Installation
|
||||
|
||||
> [!WARNING]
|
||||
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
|
||||
> T3 Code currently supports Codex and Claude.
|
||||
> Install and authenticate at least one provider before use:
|
||||
>
|
||||
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
|
||||
> - Claude: install Claude Code and run `claude auth login`
|
||||
|
||||
### Run without installing
|
||||
|
||||
```bash
|
||||
npx t3
|
||||
```
|
||||
|
||||
You can also just install the desktop app. It's cooler.
|
||||
### Desktop app
|
||||
|
||||
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
|
||||
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
|
||||
|
||||
#### Windows (`winget`)
|
||||
|
||||
```bash
|
||||
winget install T3Tools.T3Code
|
||||
```
|
||||
|
||||
#### macOS (Homebrew)
|
||||
|
||||
```bash
|
||||
brew install --cask t3-code
|
||||
```
|
||||
|
||||
#### Arch Linux (AUR)
|
||||
|
||||
```bash
|
||||
yay -S t3code-bin
|
||||
```
|
||||
|
||||
## Some notes
|
||||
|
||||
@@ -21,6 +45,8 @@ We are very very early in this project. Expect bugs.
|
||||
|
||||
We are not accepting contributions yet.
|
||||
|
||||
Observability guide: [docs/observability.md](./docs/observability.md)
|
||||
|
||||
## If you REALLY want to contribute still.... read this first
|
||||
|
||||
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
|
||||
|
||||
@@ -1,68 +1,87 @@
|
||||
# Remote Access Setup
|
||||
# Remote Access
|
||||
|
||||
Use this when you want to open T3 Code from another device (phone, tablet, another laptop).
|
||||
Use this when you want to connect to a T3 Code server from another device such as a phone, tablet, or separate desktop app.
|
||||
|
||||
## CLI ↔ Env option map
|
||||
## Recommended Setup
|
||||
|
||||
The T3 Code CLI accepts the following configuration options, available either as CLI flags or environment variables:
|
||||
Use a trusted private network that meshes your devices together, such as a tailnet.
|
||||
|
||||
| CLI flag | Env var | Notes |
|
||||
| ----------------------- | --------------------- | ------------------------------------------------------------------------------------ |
|
||||
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
|
||||
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
|
||||
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
|
||||
| `--base-dir <path>` | `T3CODE_HOME` | Base directory. |
|
||||
| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
|
||||
| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
|
||||
| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. Use this for standard CLI and remote-server flows. |
|
||||
| `--bootstrap-fd <fd>` | `T3CODE_BOOTSTRAP_FD` | Read a one-shot bootstrap envelope from an inherited file descriptor during startup. |
|
||||
That gives you:
|
||||
|
||||
> TIP: Use the `--help` flag to see all available options and their descriptions.
|
||||
- a stable address to connect to
|
||||
- transport security at the network layer
|
||||
- less exposure than opening the server to the public internet
|
||||
|
||||
## Security First
|
||||
## Enabling Network Access
|
||||
|
||||
- Always set `--auth-token` before exposing the server outside localhost.
|
||||
- When you control the process launcher, prefer sending the auth token in a JSON envelope via `--bootstrap-fd <fd>`.
|
||||
With `--bootstrap-fd <fd>`, the launcher starts the server first, then sends a one-shot JSON envelope over the inherited file descriptor. This allows the auth token to be delivered without putting it in process environment or command line arguments.
|
||||
- Treat the token like a password.
|
||||
- Prefer binding to trusted interfaces (LAN IP or Tailnet IP) instead of opening all interfaces unless needed.
|
||||
There are two ways to expose your server for remote connections: from the desktop app or from the CLI.
|
||||
|
||||
## 1) Build + run server for remote access
|
||||
### Option 1: Desktop App
|
||||
|
||||
Remote access should use the built web app (not local Vite redirect mode).
|
||||
If you are already running the desktop app and want to make it reachable from other devices:
|
||||
|
||||
1. Open **Settings** → **Connections**.
|
||||
2. Under **Manage Local Backend**, toggle **Network access** on. This will restart the app and run the backend on all network interfaces.
|
||||
3. The settings panel will show the address the server is reachable at (e.g. `http://192.168.x.y:3773`).
|
||||
4. Use **Create Link** to generate a pairing link you can share with another device.
|
||||
|
||||
### Option 2: Headless Server (CLI)
|
||||
|
||||
Use this when you want to run the server without a GUI, for example on a remote machine over SSH.
|
||||
|
||||
Run the server with `t3 serve`.
|
||||
|
||||
```bash
|
||||
bun run build
|
||||
TOKEN="$(openssl rand -hex 24)"
|
||||
bun run --cwd apps/server start -- --host 0.0.0.0 --port 3773 --auth-token "$TOKEN" --no-browser
|
||||
npx t3 serve --host "$(tailscale ip -4)"
|
||||
```
|
||||
|
||||
Then open on your phone:
|
||||
`t3 serve` starts the server without opening a browser and prints:
|
||||
|
||||
`http://<your-machine-ip>:3773`
|
||||
- a connection string
|
||||
- a pairing token
|
||||
- a pairing URL
|
||||
- a QR code for the pairing URL
|
||||
|
||||
Example:
|
||||
From there, connect from another device in either of these ways:
|
||||
|
||||
`http://192.168.1.42:3773`
|
||||
- scan the QR code on your phone
|
||||
- in the desktop app, enter the full pairing URL
|
||||
- in the desktop app, enter the host and token separately
|
||||
|
||||
Notes:
|
||||
Use `t3 serve --help` for the full flag reference. It supports the same general startup options as the normal server command, including an optional `cwd` argument.
|
||||
|
||||
- `--host 0.0.0.0` listens on all IPv4 interfaces.
|
||||
- `--no-browser` prevents local auto-open, which is usually better for headless/remote sessions.
|
||||
- Ensure your OS firewall allows inbound TCP on the selected port.
|
||||
> Note
|
||||
> The GUIs do not currently support adding projects on remote environments.
|
||||
> For now, use `t3 project ...` on the server machine instead.
|
||||
> Full GUI support for remote project management is coming soon.
|
||||
|
||||
## 2) Tailnet / Tailscale access
|
||||
## How Pairing Works
|
||||
|
||||
If you use Tailscale, you can bind directly to your Tailnet address.
|
||||
The remote device does not need a long-lived secret up front.
|
||||
|
||||
```bash
|
||||
TAILNET_IP="$(tailscale ip -4)"
|
||||
TOKEN="$(openssl rand -hex 24)"
|
||||
bun run --cwd apps/server start -- --host "$(tailscale ip -4)" --port 3773 --auth-token "$TOKEN" --no-browser
|
||||
```
|
||||
Instead:
|
||||
|
||||
Open from any device in your tailnet:
|
||||
1. `t3 serve` issues a one-time owner pairing token.
|
||||
2. The remote device exchanges that token with the server.
|
||||
3. The server creates an authenticated session for that device.
|
||||
|
||||
`http://<tailnet-ip>:3773`
|
||||
After pairing, future access is session-based. You do not need to keep reusing the original token unless you are pairing a new device.
|
||||
|
||||
You can also bind `--host 0.0.0.0` and connect through the Tailnet IP, but binding directly to the Tailnet IP limits exposure.
|
||||
## Managing Access Later
|
||||
|
||||
Use `t3 auth` to manage access after the initial pairing flow.
|
||||
|
||||
Typical uses:
|
||||
|
||||
- issue additional pairing credentials
|
||||
- inspect active sessions
|
||||
- revoke old pairing links or sessions
|
||||
|
||||
Use `t3 auth --help` and the nested subcommand help pages for the full reference.
|
||||
|
||||
## Security Notes
|
||||
|
||||
- Treat pairing URLs and pairing tokens like passwords.
|
||||
- Prefer binding `--host` to a trusted private address, such as a Tailnet IP, instead of exposing the server broadly.
|
||||
- Anyone with a valid pairing credential can create a session until that credential expires or is revoked.
|
||||
- Use `t3 auth` to revoke credentials or sessions you no longer trust.
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.14",
|
||||
"version": "0.0.17",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
@@ -24,8 +24,7 @@
|
||||
"@types/node": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
"wait-on": "^8.0.2"
|
||||
"vitest": "catalog:"
|
||||
},
|
||||
"productName": "T3 Code (Alpha)"
|
||||
}
|
||||
@@ -1,27 +1,39 @@
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { watch } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import waitOn from "wait-on";
|
||||
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
import { waitForResources } from "./wait-for-resources.mjs";
|
||||
|
||||
const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
|
||||
if (!devServerUrl) {
|
||||
throw new Error("VITE_DEV_SERVER_URL is required for desktop development.");
|
||||
}
|
||||
|
||||
const devServer = new URL(devServerUrl);
|
||||
const port = Number.parseInt(devServer.port, 10);
|
||||
if (!Number.isInteger(port) || port <= 0) {
|
||||
throw new Error(`VITE_DEV_SERVER_URL must include an explicit port: ${devServerUrl}`);
|
||||
}
|
||||
|
||||
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
|
||||
const devServerUrl = `http://localhost:${port}`;
|
||||
const requiredFiles = [
|
||||
"dist-electron/main.js",
|
||||
"dist-electron/preload.js",
|
||||
"../server/dist/index.mjs",
|
||||
"../server/dist/bin.mjs",
|
||||
];
|
||||
const watchedDirectories = [
|
||||
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
|
||||
{ directory: "../server/dist", files: new Set(["index.mjs"]) },
|
||||
{ directory: "../server/dist", files: new Set(["bin.mjs"]) },
|
||||
];
|
||||
const forcedShutdownTimeoutMs = 1_500;
|
||||
const restartDebounceMs = 120;
|
||||
const childTreeGracePeriodMs = 1_200;
|
||||
|
||||
await waitOn({
|
||||
resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
|
||||
await waitForResources({
|
||||
baseDir: desktopDir,
|
||||
files: requiredFiles,
|
||||
tcpHost: devServer.hostname,
|
||||
tcpPort: port,
|
||||
});
|
||||
|
||||
const childEnv = { ...process.env };
|
||||
@@ -60,10 +72,7 @@ function startApp() {
|
||||
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
|
||||
{
|
||||
cwd: desktopDir,
|
||||
env: {
|
||||
...childEnv,
|
||||
VITE_DEV_SERVER_URL: devServerUrl,
|
||||
},
|
||||
env: childEnv,
|
||||
stdio: "inherit",
|
||||
},
|
||||
);
|
||||
|
||||
@@ -18,7 +18,7 @@ import { fileURLToPath } from "node:url";
|
||||
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_BUNDLE_ID = "com.t3tools.t3code";
|
||||
const APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
|
||||
const LAUNCHER_VERSION = 1;
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import * as FileSystem from "node:fs/promises";
|
||||
import * as Net from "node:net";
|
||||
import * as Path from "node:path";
|
||||
import * as Timers from "node:timers/promises";
|
||||
|
||||
const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"];
|
||||
|
||||
async function fileExists(filePath) {
|
||||
try {
|
||||
await FileSystem.access(filePath);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) {
|
||||
return new Promise((resolveReady) => {
|
||||
const socket = Net.createConnection({ host, port });
|
||||
let settled = false;
|
||||
|
||||
const finish = (ready) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
settled = true;
|
||||
socket.removeAllListeners();
|
||||
socket.destroy();
|
||||
resolveReady(ready);
|
||||
};
|
||||
|
||||
socket.once("connect", () => {
|
||||
finish(true);
|
||||
});
|
||||
socket.once("timeout", () => {
|
||||
finish(false);
|
||||
});
|
||||
socket.once("error", () => {
|
||||
finish(false);
|
||||
});
|
||||
socket.setTimeout(connectTimeoutMs);
|
||||
});
|
||||
}
|
||||
|
||||
async function resolvePendingResources({ baseDir, files, tcpPort, tcpHosts, connectTimeoutMs }) {
|
||||
const pendingFiles = [];
|
||||
|
||||
for (const relativeFilePath of files) {
|
||||
const ready = await fileExists(Path.resolve(baseDir, relativeFilePath));
|
||||
if (!ready) {
|
||||
pendingFiles.push(relativeFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
let tcpReady = false;
|
||||
for (const host of tcpHosts) {
|
||||
tcpReady = await tcpPortIsReady({
|
||||
host,
|
||||
port: tcpPort,
|
||||
connectTimeoutMs,
|
||||
});
|
||||
if (tcpReady) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
pendingFiles,
|
||||
tcpReady,
|
||||
};
|
||||
}
|
||||
|
||||
export async function waitForResources({
|
||||
baseDir,
|
||||
files = [],
|
||||
intervalMs = 100,
|
||||
timeoutMs = 120_000,
|
||||
tcpHost,
|
||||
tcpPort,
|
||||
connectTimeoutMs = 500,
|
||||
}) {
|
||||
if (!Number.isInteger(tcpPort) || tcpPort <= 0) {
|
||||
throw new TypeError("waitForResources requires a positive integer tcpPort");
|
||||
}
|
||||
|
||||
const startedAt = Date.now();
|
||||
const tcpHosts = tcpHost ? [tcpHost] : defaultTcpHosts;
|
||||
|
||||
while (true) {
|
||||
const { pendingFiles, tcpReady } = await resolvePendingResources({
|
||||
baseDir,
|
||||
files,
|
||||
tcpPort,
|
||||
tcpHosts,
|
||||
connectTimeoutMs,
|
||||
});
|
||||
|
||||
if (pendingFiles.length === 0 && tcpReady) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Date.now() - startedAt >= timeoutMs) {
|
||||
const pendingResources = [];
|
||||
if (!tcpReady) {
|
||||
pendingResources.push(tcpHost ? `tcp:${tcpHost}:${tcpPort}` : `tcp:${tcpPort}`);
|
||||
}
|
||||
for (const filePath of pendingFiles) {
|
||||
pendingResources.push(`file:${filePath}`);
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`Timed out waiting for desktop dev resources after ${timeoutMs}ms: ${pendingResources.join(", ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
await Timers.setTimeout(intervalMs);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { resolveDesktopBackendPort } from "./backendPort";
|
||||
|
||||
describe("resolveDesktopBackendPort", () => {
|
||||
it("returns the starting port when it is available", async () => {
|
||||
const canListenOnHost = vi.fn(async (port: number) => port === 3773);
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
startPort: 3773,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).resolves.toBe(3773);
|
||||
|
||||
expect(canListenOnHost).toHaveBeenCalledTimes(1);
|
||||
expect(canListenOnHost).toHaveBeenCalledWith(3773, "127.0.0.1");
|
||||
});
|
||||
|
||||
it("increments sequentially until it finds an available port", async () => {
|
||||
const canListenOnHost = vi.fn(async (port: number) => port === 3775);
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
startPort: 3773,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).resolves.toBe(3775);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[3773, "127.0.0.1"],
|
||||
[3774, "127.0.0.1"],
|
||||
[3775, "127.0.0.1"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("treats wildcard-bound ports as unavailable even when loopback probing succeeds", async () => {
|
||||
const canListenOnHost = vi.fn(async (port: number, host: string) => {
|
||||
if (port === 3773 && host === "127.0.0.1") return true;
|
||||
if (port === 3773 && host === "0.0.0.0") return false;
|
||||
return port === 3774;
|
||||
});
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
requiredHosts: ["0.0.0.0"],
|
||||
startPort: 3773,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).resolves.toBe(3774);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[3773, "127.0.0.1"],
|
||||
[3773, "0.0.0.0"],
|
||||
[3774, "127.0.0.1"],
|
||||
[3774, "0.0.0.0"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("checks overlapping hosts sequentially to avoid self-interference", async () => {
|
||||
let inFlightCount = 0;
|
||||
const canListenOnHost = vi.fn(async (_port: number, _host: string) => {
|
||||
inFlightCount += 1;
|
||||
const overlapped = inFlightCount > 1;
|
||||
await Promise.resolve();
|
||||
inFlightCount -= 1;
|
||||
return !overlapped;
|
||||
});
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
requiredHosts: ["0.0.0.0", "::"],
|
||||
startPort: 3773,
|
||||
maxPort: 3773,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).resolves.toBe(3773);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[3773, "127.0.0.1"],
|
||||
[3773, "0.0.0.0"],
|
||||
[3773, "::"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("fails when the scan range is exhausted", async () => {
|
||||
const canListenOnHost = vi.fn(async () => false);
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
startPort: 65534,
|
||||
maxPort: 65535,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
"No desktop backend port is available on hosts 127.0.0.1 between 65534 and 65535",
|
||||
);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[65534, "127.0.0.1"],
|
||||
[65535, "127.0.0.1"],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
export const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
|
||||
const MAX_TCP_PORT = 65_535;
|
||||
|
||||
export interface ResolveDesktopBackendPortOptions {
|
||||
readonly host: string;
|
||||
readonly startPort?: number;
|
||||
readonly maxPort?: number;
|
||||
readonly requiredHosts?: ReadonlyArray<string>;
|
||||
readonly canListenOnHost?: (port: number, host: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
const defaultCanListenOnHost = async (port: number, host: string): Promise<boolean> =>
|
||||
Effect.service(NetService).pipe(
|
||||
Effect.flatMap((net) => net.canListenOnHost(port, host)),
|
||||
Effect.provide(NetService.layer),
|
||||
Effect.runPromise,
|
||||
);
|
||||
|
||||
const isValidPort = (port: number): boolean =>
|
||||
Number.isInteger(port) && port >= 1 && port <= MAX_TCP_PORT;
|
||||
|
||||
const normalizeHosts = (
|
||||
host: string,
|
||||
requiredHosts: ReadonlyArray<string>,
|
||||
): ReadonlyArray<string> =>
|
||||
Array.from(
|
||||
new Set(
|
||||
[host, ...requiredHosts]
|
||||
.map((candidate) => candidate.trim())
|
||||
.filter((candidate) => candidate.length > 0),
|
||||
),
|
||||
);
|
||||
|
||||
async function canListenOnAllHosts(
|
||||
port: number,
|
||||
hosts: ReadonlyArray<string>,
|
||||
canListenOnHost: (port: number, host: string) => Promise<boolean>,
|
||||
): Promise<boolean> {
|
||||
for (const candidateHost of hosts) {
|
||||
if (!(await canListenOnHost(port, candidateHost))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function resolveDesktopBackendPort({
|
||||
host,
|
||||
startPort = DEFAULT_DESKTOP_BACKEND_PORT,
|
||||
maxPort = MAX_TCP_PORT,
|
||||
requiredHosts = [],
|
||||
canListenOnHost = defaultCanListenOnHost,
|
||||
}: ResolveDesktopBackendPortOptions): Promise<number> {
|
||||
if (!isValidPort(startPort)) {
|
||||
throw new Error(`Invalid desktop backend start port: ${startPort}`);
|
||||
}
|
||||
|
||||
if (!isValidPort(maxPort)) {
|
||||
throw new Error(`Invalid desktop backend max port: ${maxPort}`);
|
||||
}
|
||||
|
||||
if (maxPort < startPort) {
|
||||
throw new Error(`Desktop backend max port ${maxPort} is below start port ${startPort}`);
|
||||
}
|
||||
|
||||
const hostsToCheck = normalizeHosts(host, requiredHosts);
|
||||
|
||||
// Keep desktop startup predictable across app restarts by probing upward from
|
||||
// the same preferred port instead of picking a fresh ephemeral port.
|
||||
for (let port = startPort; port <= maxPort; port += 1) {
|
||||
if (await canListenOnAllHosts(port, hostsToCheck, canListenOnHost)) {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`No desktop backend port is available on hosts ${hostsToCheck.join(", ")} between ${startPort} and ${maxPort}`,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
BackendReadinessAbortedError,
|
||||
isBackendReadinessAborted,
|
||||
waitForHttpReady,
|
||||
} from "./backendReadiness";
|
||||
|
||||
describe("waitForHttpReady", () => {
|
||||
it("returns once the backend reports a successful session endpoint", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response(null, { status: 503 }))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 }));
|
||||
|
||||
await waitForHttpReady("http://127.0.0.1:3773", {
|
||||
fetchImpl,
|
||||
timeoutMs: 1_000,
|
||||
intervalMs: 0,
|
||||
});
|
||||
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("retries after a readiness request stalls past the per-request timeout", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockImplementationOnce(
|
||||
(_input, init) =>
|
||||
new Promise((_resolve, reject) => {
|
||||
init?.signal?.addEventListener(
|
||||
"abort",
|
||||
() => {
|
||||
reject(new Error("request timed out"));
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
}) as ReturnType<typeof fetch>,
|
||||
)
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 }));
|
||||
|
||||
await waitForHttpReady("http://127.0.0.1:3773", {
|
||||
fetchImpl,
|
||||
timeoutMs: 100,
|
||||
intervalMs: 0,
|
||||
requestTimeoutMs: 1,
|
||||
});
|
||||
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("aborts an in-flight readiness wait", async () => {
|
||||
const controller = new AbortController();
|
||||
const fetchImpl = vi.fn<typeof fetch>().mockImplementation(
|
||||
() =>
|
||||
new Promise((_resolve, reject) => {
|
||||
controller.signal.addEventListener(
|
||||
"abort",
|
||||
() => {
|
||||
reject(new BackendReadinessAbortedError());
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
}) as ReturnType<typeof fetch>,
|
||||
);
|
||||
|
||||
const waitPromise = waitForHttpReady("http://127.0.0.1:3773", {
|
||||
fetchImpl,
|
||||
timeoutMs: 1_000,
|
||||
intervalMs: 0,
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
controller.abort();
|
||||
|
||||
await expect(waitPromise).rejects.toBeInstanceOf(BackendReadinessAbortedError);
|
||||
});
|
||||
|
||||
it("recognizes aborted readiness errors", () => {
|
||||
expect(isBackendReadinessAborted(new BackendReadinessAbortedError())).toBe(true);
|
||||
expect(isBackendReadinessAborted(new Error("nope"))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
export interface WaitForHttpReadyOptions {
|
||||
readonly timeoutMs?: number;
|
||||
readonly intervalMs?: number;
|
||||
readonly requestTimeoutMs?: number;
|
||||
readonly fetchImpl?: typeof fetch;
|
||||
readonly signal?: AbortSignal;
|
||||
}
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
|
||||
import {
|
||||
EnvironmentId,
|
||||
type ClientSettings,
|
||||
type PersistedSavedEnvironmentRecord,
|
||||
} from "@t3tools/contracts";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
readClientSettings,
|
||||
readSavedEnvironmentRegistry,
|
||||
readSavedEnvironmentSecret,
|
||||
removeSavedEnvironmentSecret,
|
||||
writeClientSettings,
|
||||
writeSavedEnvironmentRegistry,
|
||||
writeSavedEnvironmentSecret,
|
||||
type DesktopSecretStorage,
|
||||
} from "./clientPersistence";
|
||||
|
||||
const tempDirectories: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const directory of tempDirectories.splice(0)) {
|
||||
fs.rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function makeTempPath(fileName: string): string {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "t3-client-persistence-test-"));
|
||||
tempDirectories.push(directory);
|
||||
return path.join(directory, fileName);
|
||||
}
|
||||
|
||||
function makeSecretStorage(available: boolean): DesktopSecretStorage {
|
||||
return {
|
||||
isEncryptionAvailable: () => available,
|
||||
encryptString: (value) => Buffer.from(`enc:${value}`, "utf8"),
|
||||
decryptString: (value) => {
|
||||
const decoded = value.toString("utf8");
|
||||
if (!decoded.startsWith("enc:")) {
|
||||
throw new Error("invalid secret");
|
||||
}
|
||||
return decoded.slice("enc:".length);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const clientSettings: ClientSettings = {
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
diffWordWrap: true,
|
||||
sidebarProjectSortOrder: "manual",
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
timestampFormat: "24-hour",
|
||||
};
|
||||
|
||||
const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
label: "Remote environment",
|
||||
httpBaseUrl: "https://remote.example.com/",
|
||||
wsBaseUrl: "wss://remote.example.com/",
|
||||
createdAt: "2026-04-09T00:00:00.000Z",
|
||||
lastConnectedAt: "2026-04-09T01:00:00.000Z",
|
||||
};
|
||||
|
||||
describe("clientPersistence", () => {
|
||||
it("persists and reloads client settings", () => {
|
||||
const settingsPath = makeTempPath("client-settings.json");
|
||||
|
||||
writeClientSettings(settingsPath, clientSettings);
|
||||
|
||||
expect(readClientSettings(settingsPath)).toEqual(clientSettings);
|
||||
});
|
||||
|
||||
it("persists and reloads saved environment metadata", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
expect(readSavedEnvironmentRegistry(registryPath)).toEqual([savedRegistryRecord]);
|
||||
});
|
||||
|
||||
it("persists encrypted saved environment secrets when encryption is available", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
const secretStorage = makeSecretStorage(true);
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
expect(
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "bearer-token",
|
||||
secretStorage,
|
||||
}),
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
readSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secretStorage,
|
||||
}),
|
||||
).toBe("bearer-token");
|
||||
|
||||
expect(JSON.parse(fs.readFileSync(registryPath, "utf8"))).toEqual({
|
||||
records: [
|
||||
{
|
||||
...savedRegistryRecord,
|
||||
encryptedBearerToken: Buffer.from("enc:bearer-token", "utf8").toString("base64"),
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves existing secrets when encryption is unavailable", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
const availableSecretStorage = makeSecretStorage(true);
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "bearer-token",
|
||||
secretStorage: availableSecretStorage,
|
||||
});
|
||||
|
||||
expect(
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "next-token",
|
||||
secretStorage: makeSecretStorage(false),
|
||||
}),
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
readSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secretStorage: availableSecretStorage,
|
||||
}),
|
||||
).toBe("bearer-token");
|
||||
});
|
||||
|
||||
it("removes saved environment secrets", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
const secretStorage = makeSecretStorage(true);
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "bearer-token",
|
||||
secretStorage,
|
||||
});
|
||||
|
||||
removeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
});
|
||||
|
||||
expect(
|
||||
readSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secretStorage,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("treats malformed secrets documents as empty", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
fs.writeFileSync(registryPath, "{}\n", "utf8");
|
||||
|
||||
expect(
|
||||
readSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secretStorage: makeSecretStorage(true),
|
||||
}),
|
||||
).toBeNull();
|
||||
|
||||
expect(() =>
|
||||
removeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it("returns false when writing a secret without metadata", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
|
||||
expect(
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "bearer-token",
|
||||
secretStorage: makeSecretStorage(true),
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("preserves encrypted secrets when metadata is rewritten", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
const secretStorage = makeSecretStorage(true);
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "bearer-token",
|
||||
secretStorage,
|
||||
});
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
expect(readSavedEnvironmentRegistry(registryPath)).toEqual([savedRegistryRecord]);
|
||||
expect(
|
||||
readSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secretStorage,
|
||||
}),
|
||||
).toBe("bearer-token");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,216 @@
|
||||
import * as FS from "node:fs";
|
||||
import * as Path from "node:path";
|
||||
|
||||
import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
|
||||
import { Predicate } from "effect";
|
||||
|
||||
interface ClientSettingsDocument {
|
||||
readonly settings: ClientSettings;
|
||||
}
|
||||
|
||||
interface PersistedSavedEnvironmentStorageRecord extends PersistedSavedEnvironmentRecord {
|
||||
readonly encryptedBearerToken?: string;
|
||||
}
|
||||
|
||||
interface SavedEnvironmentRegistryDocument {
|
||||
readonly records: readonly PersistedSavedEnvironmentStorageRecord[];
|
||||
}
|
||||
|
||||
export interface DesktopSecretStorage {
|
||||
readonly isEncryptionAvailable: () => boolean;
|
||||
readonly encryptString: (value: string) => Buffer;
|
||||
readonly decryptString: (value: Buffer) => string;
|
||||
}
|
||||
|
||||
function readJsonFile<T>(filePath: string): T | null {
|
||||
try {
|
||||
if (!FS.existsSync(filePath)) {
|
||||
return null;
|
||||
}
|
||||
return JSON.parse(FS.readFileSync(filePath, "utf8")) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeJsonFile(filePath: string, value: unknown): void {
|
||||
const directory = Path.dirname(filePath);
|
||||
const tempPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
|
||||
FS.mkdirSync(directory, { recursive: true });
|
||||
FS.writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, "utf8");
|
||||
FS.renameSync(tempPath, filePath);
|
||||
}
|
||||
|
||||
function isPersistedSavedEnvironmentStorageRecord(
|
||||
value: unknown,
|
||||
): value is PersistedSavedEnvironmentStorageRecord {
|
||||
return (
|
||||
Predicate.isObject(value) &&
|
||||
typeof value.environmentId === "string" &&
|
||||
typeof value.label === "string" &&
|
||||
typeof value.httpBaseUrl === "string" &&
|
||||
typeof value.wsBaseUrl === "string" &&
|
||||
typeof value.createdAt === "string" &&
|
||||
(value.lastConnectedAt === null || typeof value.lastConnectedAt === "string") &&
|
||||
(value.encryptedBearerToken === undefined || typeof value.encryptedBearerToken === "string")
|
||||
);
|
||||
}
|
||||
|
||||
function readSavedEnvironmentRegistryDocument(filePath: string): SavedEnvironmentRegistryDocument {
|
||||
const parsed = readJsonFile<SavedEnvironmentRegistryDocument>(filePath);
|
||||
if (!Predicate.isObject(parsed)) {
|
||||
return { records: [] };
|
||||
}
|
||||
|
||||
return {
|
||||
records: Array.isArray(parsed.records)
|
||||
? parsed.records.filter(isPersistedSavedEnvironmentStorageRecord)
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
function toPersistedSavedEnvironmentRecord(
|
||||
record: PersistedSavedEnvironmentStorageRecord,
|
||||
): PersistedSavedEnvironmentRecord {
|
||||
return {
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
httpBaseUrl: record.httpBaseUrl,
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
createdAt: record.createdAt,
|
||||
lastConnectedAt: record.lastConnectedAt,
|
||||
};
|
||||
}
|
||||
|
||||
export function readClientSettings(settingsPath: string): ClientSettings | null {
|
||||
return readJsonFile<ClientSettingsDocument>(settingsPath)?.settings ?? null;
|
||||
}
|
||||
|
||||
export function writeClientSettings(settingsPath: string, settings: ClientSettings): void {
|
||||
writeJsonFile(settingsPath, { settings } satisfies ClientSettingsDocument);
|
||||
}
|
||||
|
||||
export function readSavedEnvironmentRegistry(
|
||||
registryPath: string,
|
||||
): readonly PersistedSavedEnvironmentRecord[] {
|
||||
return readSavedEnvironmentRegistryDocument(registryPath).records.map((record) =>
|
||||
toPersistedSavedEnvironmentRecord(record),
|
||||
);
|
||||
}
|
||||
|
||||
export function writeSavedEnvironmentRegistry(
|
||||
registryPath: string,
|
||||
records: readonly PersistedSavedEnvironmentRecord[],
|
||||
): void {
|
||||
const currentDocument = readSavedEnvironmentRegistryDocument(registryPath);
|
||||
const encryptedBearerTokenById = new Map(
|
||||
currentDocument.records.flatMap((record) =>
|
||||
record.encryptedBearerToken
|
||||
? [[record.environmentId, record.encryptedBearerToken] as const]
|
||||
: [],
|
||||
),
|
||||
);
|
||||
writeJsonFile(registryPath, {
|
||||
records: records.map((record) => {
|
||||
const encryptedBearerToken = encryptedBearerTokenById.get(record.environmentId);
|
||||
return encryptedBearerToken
|
||||
? {
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
httpBaseUrl: record.httpBaseUrl,
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
createdAt: record.createdAt,
|
||||
lastConnectedAt: record.lastConnectedAt,
|
||||
encryptedBearerToken,
|
||||
}
|
||||
: record;
|
||||
}),
|
||||
} satisfies SavedEnvironmentRegistryDocument);
|
||||
}
|
||||
|
||||
export function readSavedEnvironmentSecret(input: {
|
||||
readonly registryPath: string;
|
||||
readonly environmentId: string;
|
||||
readonly secretStorage: DesktopSecretStorage;
|
||||
}): string | null {
|
||||
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
|
||||
const encoded = document.records.find(
|
||||
(record) => record.environmentId === input.environmentId,
|
||||
)?.encryptedBearerToken;
|
||||
if (!encoded) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!input.secretStorage.isEncryptionAvailable()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return input.secretStorage.decryptString(Buffer.from(encoded, "base64"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function writeSavedEnvironmentSecret(input: {
|
||||
readonly registryPath: string;
|
||||
readonly environmentId: string;
|
||||
readonly secret: string;
|
||||
readonly secretStorage: DesktopSecretStorage;
|
||||
}): boolean {
|
||||
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
|
||||
|
||||
if (!input.secretStorage.isEncryptionAvailable()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let found = false;
|
||||
|
||||
writeJsonFile(input.registryPath, {
|
||||
records: document.records.map((record) => {
|
||||
if (record.environmentId !== input.environmentId) {
|
||||
return record;
|
||||
}
|
||||
|
||||
found = true;
|
||||
const encryptedBearerToken = input.secretStorage
|
||||
.encryptString(input.secret)
|
||||
.toString("base64");
|
||||
return {
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
httpBaseUrl: record.httpBaseUrl,
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
createdAt: record.createdAt,
|
||||
lastConnectedAt: record.lastConnectedAt,
|
||||
encryptedBearerToken,
|
||||
} satisfies PersistedSavedEnvironmentStorageRecord;
|
||||
}),
|
||||
} satisfies SavedEnvironmentRegistryDocument);
|
||||
return found;
|
||||
}
|
||||
|
||||
export function removeSavedEnvironmentSecret(input: {
|
||||
readonly registryPath: string;
|
||||
readonly environmentId: string;
|
||||
}): void {
|
||||
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
|
||||
if (
|
||||
!document.records.some(
|
||||
(record) =>
|
||||
record.environmentId === input.environmentId && record.encryptedBearerToken !== undefined,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
writeJsonFile(input.registryPath, {
|
||||
records: document.records.map((record) => {
|
||||
if (record.environmentId !== input.environmentId) {
|
||||
return record;
|
||||
}
|
||||
|
||||
return toPersistedSavedEnvironmentRecord(record);
|
||||
}),
|
||||
} satisfies SavedEnvironmentRegistryDocument);
|
||||
}
|
||||
@@ -14,7 +14,7 @@ export async function showDesktopConfirmDialog(
|
||||
const options = {
|
||||
type: "question" as const,
|
||||
buttons: ["No", "Yes"],
|
||||
defaultId: CONFIRM_BUTTON_INDEX,
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
noLink: true,
|
||||
message: normalizedMessage,
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
DEFAULT_DESKTOP_SETTINGS,
|
||||
readDesktopSettings,
|
||||
setDesktopServerExposurePreference,
|
||||
writeDesktopSettings,
|
||||
} from "./desktopSettings";
|
||||
|
||||
const tempDirectories: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const directory of tempDirectories.splice(0)) {
|
||||
fs.rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function makeSettingsPath() {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "t3-desktop-settings-test-"));
|
||||
tempDirectories.push(directory);
|
||||
return path.join(directory, "desktop-settings.json");
|
||||
}
|
||||
|
||||
describe("desktopSettings", () => {
|
||||
it("returns defaults when no settings file exists", () => {
|
||||
expect(readDesktopSettings(makeSettingsPath())).toEqual(DEFAULT_DESKTOP_SETTINGS);
|
||||
});
|
||||
|
||||
it("persists and reloads the configured server exposure mode", () => {
|
||||
const settingsPath = makeSettingsPath();
|
||||
|
||||
writeDesktopSettings(settingsPath, {
|
||||
serverExposureMode: "network-accessible",
|
||||
});
|
||||
|
||||
expect(readDesktopSettings(settingsPath)).toEqual({
|
||||
serverExposureMode: "network-accessible",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves the requested network-accessible preference across temporary fallback", () => {
|
||||
expect(
|
||||
setDesktopServerExposurePreference(
|
||||
{
|
||||
serverExposureMode: "local-only",
|
||||
},
|
||||
"network-accessible",
|
||||
),
|
||||
).toEqual({
|
||||
serverExposureMode: "network-accessible",
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to defaults when the settings file is malformed", () => {
|
||||
const settingsPath = makeSettingsPath();
|
||||
fs.writeFileSync(settingsPath, "{not-json", "utf8");
|
||||
|
||||
expect(readDesktopSettings(settingsPath)).toEqual(DEFAULT_DESKTOP_SETTINGS);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import * as FS from "node:fs";
|
||||
import * as Path from "node:path";
|
||||
import type { DesktopServerExposureMode } from "@t3tools/contracts";
|
||||
|
||||
export interface DesktopSettings {
|
||||
readonly serverExposureMode: DesktopServerExposureMode;
|
||||
}
|
||||
|
||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
serverExposureMode: "local-only",
|
||||
};
|
||||
|
||||
export function setDesktopServerExposurePreference(
|
||||
settings: DesktopSettings,
|
||||
requestedMode: DesktopServerExposureMode,
|
||||
): DesktopSettings {
|
||||
return settings.serverExposureMode === requestedMode
|
||||
? settings
|
||||
: {
|
||||
...settings,
|
||||
serverExposureMode: requestedMode,
|
||||
};
|
||||
}
|
||||
|
||||
export function readDesktopSettings(settingsPath: string): DesktopSettings {
|
||||
try {
|
||||
if (!FS.existsSync(settingsPath)) {
|
||||
return DEFAULT_DESKTOP_SETTINGS;
|
||||
}
|
||||
|
||||
const raw = FS.readFileSync(settingsPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as {
|
||||
readonly serverExposureMode?: unknown;
|
||||
};
|
||||
|
||||
return {
|
||||
serverExposureMode:
|
||||
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
|
||||
};
|
||||
} catch {
|
||||
return DEFAULT_DESKTOP_SETTINGS;
|
||||
}
|
||||
}
|
||||
|
||||
export function writeDesktopSettings(settingsPath: string, settings: DesktopSettings): void {
|
||||
const directory = Path.dirname(settingsPath);
|
||||
const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`;
|
||||
FS.mkdirSync(directory, { recursive: true });
|
||||
FS.writeFileSync(tempPath, `${JSON.stringify(settings, null, 2)}\n`, "utf8");
|
||||
FS.renameSync(tempPath, settingsPath);
|
||||
}
|
||||
+543
-49
@@ -7,27 +7,51 @@ import * as Path from "node:path";
|
||||
import {
|
||||
app,
|
||||
BrowserWindow,
|
||||
clipboard,
|
||||
dialog,
|
||||
ipcMain,
|
||||
Menu,
|
||||
nativeImage,
|
||||
nativeTheme,
|
||||
protocol,
|
||||
safeStorage,
|
||||
shell,
|
||||
} from "electron";
|
||||
import type { MenuItemConstructorOptions } from "electron";
|
||||
import * as Effect from "effect/Effect";
|
||||
import type {
|
||||
ClientSettings,
|
||||
DesktopTheme,
|
||||
DesktopServerExposureMode,
|
||||
DesktopServerExposureState,
|
||||
PersistedSavedEnvironmentRecord,
|
||||
DesktopUpdateActionResult,
|
||||
DesktopUpdateCheckResult,
|
||||
DesktopUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import { autoUpdater } from "electron-updater";
|
||||
|
||||
import type { ContextMenuItem } from "@t3tools/contracts";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
|
||||
import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort";
|
||||
import {
|
||||
DEFAULT_DESKTOP_SETTINGS,
|
||||
readDesktopSettings,
|
||||
setDesktopServerExposurePreference,
|
||||
writeDesktopSettings,
|
||||
} from "./desktopSettings";
|
||||
import {
|
||||
readClientSettings,
|
||||
readSavedEnvironmentRegistry,
|
||||
readSavedEnvironmentSecret,
|
||||
removeSavedEnvironmentSecret,
|
||||
writeClientSettings,
|
||||
writeSavedEnvironmentRegistry,
|
||||
writeSavedEnvironmentSecret,
|
||||
} from "./clientPersistence";
|
||||
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness";
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
import { resolveDesktopServerExposure } from "./serverExposure";
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment";
|
||||
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
|
||||
import {
|
||||
@@ -56,14 +80,29 @@ const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
|
||||
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
||||
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
|
||||
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
|
||||
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
|
||||
const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
|
||||
const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
|
||||
const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
|
||||
const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
|
||||
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
|
||||
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
|
||||
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
|
||||
const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
|
||||
const STATE_DIR = Path.join(BASE_DIR, "userdata");
|
||||
const DESKTOP_SETTINGS_PATH = Path.join(STATE_DIR, "desktop-settings.json");
|
||||
const CLIENT_SETTINGS_PATH = Path.join(STATE_DIR, "client-settings.json");
|
||||
const SAVED_ENVIRONMENT_REGISTRY_PATH = Path.join(STATE_DIR, "saved-environments.json");
|
||||
const DESKTOP_SCHEME = "t3";
|
||||
const ROOT_DIR = Path.resolve(__dirname, "../../..");
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_USER_MODEL_ID = "com.t3tools.t3code";
|
||||
const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop";
|
||||
const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code";
|
||||
const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";
|
||||
const LEGACY_USER_DATA_DIR_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i;
|
||||
@@ -72,18 +111,29 @@ const LOG_DIR = Path.join(STATE_DIR, "logs");
|
||||
const LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||
const LOG_FILE_MAX_FILES = 10;
|
||||
const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
|
||||
const SERVER_SETTINGS_PATH = Path.join(STATE_DIR, "settings.json");
|
||||
const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
|
||||
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
|
||||
const DESKTOP_UPDATE_CHANNEL = "latest";
|
||||
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
|
||||
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
|
||||
const DESKTOP_REQUIRED_PORT_PROBE_HOSTS = ["0.0.0.0", "::"] as const;
|
||||
|
||||
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
|
||||
type LinuxDesktopNamedApp = Electron.App & {
|
||||
setDesktopName?: (desktopName: string) => void;
|
||||
};
|
||||
|
||||
let mainWindow: BrowserWindow | null = null;
|
||||
let backendProcess: ChildProcess.ChildProcess | null = null;
|
||||
let backendPort = 0;
|
||||
let backendAuthToken = "";
|
||||
let backendBindHost = DESKTOP_LOOPBACK_HOST;
|
||||
let backendBootstrapToken = "";
|
||||
let backendHttpUrl = "";
|
||||
let backendWsUrl = "";
|
||||
let backendEndpointUrl: string | null = null;
|
||||
let backendAdvertisedHost: string | null = null;
|
||||
let backendReadinessAbortController: AbortController | null = null;
|
||||
let restartAttempt = 0;
|
||||
let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let isQuitting = false;
|
||||
@@ -92,8 +142,12 @@ let aboutCommitHashCache: string | null | undefined;
|
||||
let desktopLogSink: RotatingFileSink | null = null;
|
||||
let backendLogSink: RotatingFileSink | null = null;
|
||||
let restoreStdIoCapture: (() => void) | null = null;
|
||||
let backendObservabilitySettings = readPersistedBackendObservabilitySettings();
|
||||
let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH);
|
||||
let desktopServerExposureMode: DesktopServerExposureMode = desktopSettings.serverExposureMode;
|
||||
|
||||
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
|
||||
const expectedBackendExitChildren = new WeakSet<ChildProcess.ChildProcess>();
|
||||
const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
|
||||
platform: process.platform,
|
||||
processArch: process.arch,
|
||||
@@ -114,17 +168,143 @@ function sanitizeLogValue(value: string): string {
|
||||
return value.replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
function readPersistedBackendObservabilitySettings(): {
|
||||
readonly otlpTracesUrl: string | undefined;
|
||||
readonly otlpMetricsUrl: string | undefined;
|
||||
} {
|
||||
try {
|
||||
if (!FS.existsSync(SERVER_SETTINGS_PATH)) {
|
||||
return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
|
||||
}
|
||||
return parsePersistedServerObservabilitySettings(FS.readFileSync(SERVER_SETTINGS_PATH, "utf8"));
|
||||
} catch (error) {
|
||||
console.warn("[desktop] failed to read persisted backend observability settings", error);
|
||||
return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
|
||||
}
|
||||
}
|
||||
|
||||
function resolveConfiguredDesktopBackendPort(rawPort: string | undefined): number | undefined {
|
||||
if (!rawPort) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const parsedPort = Number.parseInt(rawPort, 10);
|
||||
if (!Number.isInteger(parsedPort) || parsedPort < 1 || parsedPort > 65_535) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return parsedPort;
|
||||
}
|
||||
|
||||
function resolveDesktopDevServerUrl(): string {
|
||||
const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
|
||||
if (!devServerUrl) {
|
||||
throw new Error("VITE_DEV_SERVER_URL is required in desktop development.");
|
||||
}
|
||||
|
||||
return devServerUrl;
|
||||
}
|
||||
|
||||
function backendChildEnv(): NodeJS.ProcessEnv {
|
||||
const env = { ...process.env };
|
||||
delete env.T3CODE_PORT;
|
||||
delete env.T3CODE_AUTH_TOKEN;
|
||||
delete env.T3CODE_MODE;
|
||||
delete env.T3CODE_NO_BROWSER;
|
||||
delete env.T3CODE_HOST;
|
||||
delete env.T3CODE_DESKTOP_WS_URL;
|
||||
delete env.T3CODE_DESKTOP_LAN_ACCESS;
|
||||
delete env.T3CODE_DESKTOP_LAN_HOST;
|
||||
return env;
|
||||
}
|
||||
|
||||
function getDesktopServerExposureState(): DesktopServerExposureState {
|
||||
return {
|
||||
mode: desktopServerExposureMode,
|
||||
endpointUrl: backendEndpointUrl,
|
||||
advertisedHost: backendAdvertisedHost,
|
||||
};
|
||||
}
|
||||
|
||||
function getDesktopSecretStorage() {
|
||||
return {
|
||||
isEncryptionAvailable: () => safeStorage.isEncryptionAvailable(),
|
||||
encryptString: (value: string) => safeStorage.encryptString(value),
|
||||
decryptString: (value: Buffer) => safeStorage.decryptString(value),
|
||||
} as const;
|
||||
}
|
||||
|
||||
function resolveAdvertisedHostOverride(): string | undefined {
|
||||
const override = process.env.T3CODE_DESKTOP_LAN_HOST?.trim();
|
||||
return override && override.length > 0 ? override : undefined;
|
||||
}
|
||||
|
||||
async function applyDesktopServerExposureMode(
|
||||
mode: DesktopServerExposureMode,
|
||||
options?: { readonly persist?: boolean; readonly rejectIfUnavailable?: boolean },
|
||||
): Promise<DesktopServerExposureState> {
|
||||
const advertisedHostOverride = resolveAdvertisedHostOverride();
|
||||
const requestedMode = mode;
|
||||
let exposure = resolveDesktopServerExposure({
|
||||
mode,
|
||||
port: backendPort,
|
||||
networkInterfaces: OS.networkInterfaces(),
|
||||
...(advertisedHostOverride ? { advertisedHostOverride } : {}),
|
||||
});
|
||||
|
||||
if (requestedMode === "network-accessible" && exposure.endpointUrl === null) {
|
||||
if (options?.rejectIfUnavailable) {
|
||||
throw new Error("No reachable network address is available for this desktop right now.");
|
||||
}
|
||||
exposure = resolveDesktopServerExposure({
|
||||
mode: "local-only",
|
||||
port: backendPort,
|
||||
networkInterfaces: OS.networkInterfaces(),
|
||||
...(advertisedHostOverride ? { advertisedHostOverride } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
desktopServerExposureMode = exposure.mode;
|
||||
desktopSettings = setDesktopServerExposurePreference(desktopSettings, requestedMode);
|
||||
backendBindHost = exposure.bindHost;
|
||||
backendHttpUrl = exposure.localHttpUrl;
|
||||
backendWsUrl = exposure.localWsUrl;
|
||||
backendEndpointUrl = exposure.endpointUrl;
|
||||
backendAdvertisedHost = exposure.advertisedHost;
|
||||
|
||||
if (options?.persist) {
|
||||
writeDesktopSettings(DESKTOP_SETTINGS_PATH, desktopSettings);
|
||||
}
|
||||
|
||||
return getDesktopServerExposureState();
|
||||
}
|
||||
|
||||
function relaunchDesktopApp(reason: string): void {
|
||||
writeDesktopLogHeader(`desktop relaunch requested reason=${reason}`);
|
||||
setImmediate(() => {
|
||||
isQuitting = true;
|
||||
clearUpdatePollTimer();
|
||||
cancelBackendReadinessWait();
|
||||
void stopBackendAndWaitForExit()
|
||||
.catch((error) => {
|
||||
writeDesktopLogHeader(
|
||||
`desktop relaunch backend shutdown warning message=${formatErrorMessage(error)}`,
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
restoreStdIoCapture?.();
|
||||
if (isDevelopment) {
|
||||
app.exit(75);
|
||||
return;
|
||||
}
|
||||
app.relaunch({
|
||||
execPath: process.execPath,
|
||||
args: process.argv.slice(1),
|
||||
});
|
||||
app.exit(0);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function writeDesktopLogHeader(message: string): void {
|
||||
if (!desktopLogSink) return;
|
||||
desktopLogSink.write(`[${logTimestamp()}] [${logScope("desktop")}] ${message}\n`);
|
||||
@@ -172,6 +352,27 @@ function getSafeTheme(rawTheme: unknown): DesktopTheme | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function waitForBackendHttpReady(baseUrl: string): Promise<void> {
|
||||
cancelBackendReadinessWait();
|
||||
const controller = new AbortController();
|
||||
backendReadinessAbortController = controller;
|
||||
|
||||
try {
|
||||
await waitForHttpReady(baseUrl, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
} finally {
|
||||
if (backendReadinessAbortController === controller) {
|
||||
backendReadinessAbortController = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function cancelBackendReadinessWait(): void {
|
||||
backendReadinessAbortController?.abort();
|
||||
backendReadinessAbortController = null;
|
||||
}
|
||||
|
||||
function writeDesktopStreamChunk(
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: unknown,
|
||||
@@ -261,6 +462,10 @@ function captureBackendOutput(child: ChildProcess.ChildProcess): void {
|
||||
|
||||
initializePackagedLogging();
|
||||
|
||||
if (process.platform === "linux") {
|
||||
app.commandLine.appendSwitch("class", LINUX_WM_CLASS);
|
||||
}
|
||||
|
||||
function getDestructiveMenuIcon(): Electron.NativeImage | undefined {
|
||||
if (process.platform !== "darwin") return undefined;
|
||||
if (destructiveMenuIconCache !== undefined) {
|
||||
@@ -287,10 +492,12 @@ let updatePollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let updateStartupTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let updateCheckInFlight = false;
|
||||
let updateDownloadInFlight = false;
|
||||
let updateInstallInFlight = false;
|
||||
let updaterConfigured = false;
|
||||
let updateState: DesktopUpdateState = initialUpdateState();
|
||||
|
||||
function resolveUpdaterErrorContext(): DesktopUpdateErrorContext {
|
||||
if (updateInstallInFlight) return "install";
|
||||
if (updateDownloadInFlight) return "download";
|
||||
if (updateCheckInFlight) return "check";
|
||||
return updateState.errorContext;
|
||||
@@ -386,7 +593,7 @@ function resolveAboutCommitHash(): string | null {
|
||||
}
|
||||
|
||||
function resolveBackendEntry(): string {
|
||||
return Path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
|
||||
return Path.join(resolveAppRoot(), "apps/server/dist/bin.mjs");
|
||||
}
|
||||
|
||||
function resolveBackendCwd(): string {
|
||||
@@ -510,10 +717,7 @@ function dispatchMenuAction(action: string): void {
|
||||
const send = () => {
|
||||
if (targetWindow.isDestroyed()) return;
|
||||
targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
|
||||
if (!targetWindow.isVisible()) {
|
||||
targetWindow.show();
|
||||
}
|
||||
targetWindow.focus();
|
||||
revealWindow(targetWindow);
|
||||
};
|
||||
|
||||
if (targetWindow.webContents.isLoadingMainFrame()) {
|
||||
@@ -525,12 +729,15 @@ function dispatchMenuAction(action: string): void {
|
||||
}
|
||||
|
||||
function handleCheckForUpdatesMenuClick(): void {
|
||||
const hasUpdateFeedConfig =
|
||||
readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES);
|
||||
const disabledReason = getAutoUpdateDisabledReason({
|
||||
isDevelopment,
|
||||
isPackaged: app.isPackaged,
|
||||
platform: process.platform,
|
||||
appImage: process.env.APPIMAGE,
|
||||
disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
|
||||
hasUpdateFeedConfig,
|
||||
});
|
||||
if (disabledReason) {
|
||||
console.info("[desktop-updater] Manual update check requested, but updates are disabled.");
|
||||
@@ -711,6 +918,10 @@ function configureAppIdentity(): void {
|
||||
app.setAppUserModelId(APP_USER_MODEL_ID);
|
||||
}
|
||||
|
||||
if (process.platform === "linux") {
|
||||
(app as LinuxDesktopNamedApp).setDesktopName?.(LINUX_DESKTOP_ENTRY_NAME);
|
||||
}
|
||||
|
||||
if (process.platform === "darwin" && app.dock) {
|
||||
const iconPath = resolveIconPath("png");
|
||||
if (iconPath) {
|
||||
@@ -730,6 +941,26 @@ function clearUpdatePollTimer(): void {
|
||||
}
|
||||
}
|
||||
|
||||
function revealWindow(window: BrowserWindow): void {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.isMinimized()) {
|
||||
window.restore();
|
||||
}
|
||||
|
||||
if (!window.isVisible()) {
|
||||
window.show();
|
||||
}
|
||||
|
||||
if (process.platform === "darwin") {
|
||||
app.focus({ steal: true });
|
||||
}
|
||||
|
||||
window.focus();
|
||||
}
|
||||
|
||||
function emitUpdateState(): void {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (window.isDestroyed()) continue;
|
||||
@@ -743,6 +974,8 @@ function setUpdateState(patch: Partial<DesktopUpdateState>): void {
|
||||
}
|
||||
|
||||
function shouldEnableAutoUpdates(): boolean {
|
||||
const hasUpdateFeedConfig =
|
||||
readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES);
|
||||
return (
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment,
|
||||
@@ -750,17 +983,18 @@ function shouldEnableAutoUpdates(): boolean {
|
||||
platform: process.platform,
|
||||
appImage: process.env.APPIMAGE,
|
||||
disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
|
||||
hasUpdateFeedConfig,
|
||||
}) === null
|
||||
);
|
||||
}
|
||||
|
||||
async function checkForUpdates(reason: string): Promise<void> {
|
||||
if (isQuitting || !updaterConfigured || updateCheckInFlight) return;
|
||||
async function checkForUpdates(reason: string): Promise<boolean> {
|
||||
if (isQuitting || !updaterConfigured || updateCheckInFlight) return false;
|
||||
if (updateState.status === "downloading" || updateState.status === "downloaded") {
|
||||
console.info(
|
||||
`[desktop-updater] Skipping update check (${reason}) while status=${updateState.status}.`,
|
||||
);
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
updateCheckInFlight = true;
|
||||
setUpdateState(reduceDesktopUpdateStateOnCheckStart(updateState, new Date().toISOString()));
|
||||
@@ -768,12 +1002,14 @@ async function checkForUpdates(reason: string): Promise<void> {
|
||||
|
||||
try {
|
||||
await autoUpdater.checkForUpdates();
|
||||
return true;
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
setUpdateState(
|
||||
reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()),
|
||||
);
|
||||
console.error(`[desktop-updater] Failed to check for updates: ${message}`);
|
||||
return true;
|
||||
} finally {
|
||||
updateCheckInFlight = false;
|
||||
}
|
||||
@@ -807,13 +1043,22 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed
|
||||
}
|
||||
|
||||
isQuitting = true;
|
||||
updateInstallInFlight = true;
|
||||
clearUpdatePollTimer();
|
||||
try {
|
||||
await stopBackendAndWaitForExit();
|
||||
autoUpdater.quitAndInstall();
|
||||
return { accepted: true, completed: true };
|
||||
// Destroy all windows before launching the NSIS installer to avoid the installer finding live windows it needs to close.
|
||||
for (const win of BrowserWindow.getAllWindows()) {
|
||||
win.destroy();
|
||||
}
|
||||
// `quitAndInstall()` only starts the handoff to the updater. The actual
|
||||
// install may still fail asynchronously, so keep the action incomplete
|
||||
// until we either quit or receive an updater error.
|
||||
autoUpdater.quitAndInstall(true, true);
|
||||
return { accepted: true, completed: false };
|
||||
} catch (error: unknown) {
|
||||
const message = formatErrorMessage(error);
|
||||
updateInstallInFlight = false;
|
||||
isQuitting = false;
|
||||
setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
|
||||
console.error(`[desktop-updater] Failed to install update: ${message}`);
|
||||
@@ -822,17 +1067,6 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed
|
||||
}
|
||||
|
||||
function configureAutoUpdater(): void {
|
||||
const enabled = shouldEnableAutoUpdates();
|
||||
setUpdateState({
|
||||
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
|
||||
enabled,
|
||||
status: enabled ? "idle" : "disabled",
|
||||
});
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
updaterConfigured = true;
|
||||
|
||||
const githubToken =
|
||||
process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || "";
|
||||
if (githubToken) {
|
||||
@@ -850,6 +1084,24 @@ 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.autoInstallOnAppQuit = false;
|
||||
// Keep alpha branding, but force all installs onto the stable update track.
|
||||
@@ -886,6 +1138,13 @@ function configureAutoUpdater(): void {
|
||||
});
|
||||
autoUpdater.on("error", (error) => {
|
||||
const message = formatErrorMessage(error);
|
||||
if (updateInstallInFlight) {
|
||||
updateInstallInFlight = false;
|
||||
isQuitting = false;
|
||||
setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
|
||||
console.error(`[desktop-updater] Updater error: ${message}`);
|
||||
return;
|
||||
}
|
||||
if (!updateCheckInFlight && !updateDownloadInFlight) {
|
||||
setUpdateState({
|
||||
status: "error",
|
||||
@@ -946,6 +1205,7 @@ function scheduleBackendRestart(reason: string): void {
|
||||
function startBackend(): void {
|
||||
if (isQuitting || backendProcess) return;
|
||||
|
||||
backendObservabilitySettings = readPersistedBackendObservabilitySettings();
|
||||
const backendEntry = resolveBackendEntry();
|
||||
if (!FS.existsSync(backendEntry)) {
|
||||
scheduleBackendRestart(`missing server entry at ${backendEntry}`);
|
||||
@@ -973,7 +1233,14 @@ function startBackend(): void {
|
||||
noBrowser: true,
|
||||
port: backendPort,
|
||||
t3Home: BASE_DIR,
|
||||
authToken: backendAuthToken,
|
||||
host: backendBindHost,
|
||||
desktopBootstrapToken: backendBootstrapToken,
|
||||
...(backendObservabilitySettings.otlpTracesUrl
|
||||
? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl }
|
||||
: {}),
|
||||
...(backendObservabilitySettings.otlpMetricsUrl
|
||||
? { otlpMetricsUrl: backendObservabilitySettings.otlpMetricsUrl }
|
||||
: {}),
|
||||
})}\n`,
|
||||
);
|
||||
bootstrapStream.end();
|
||||
@@ -1000,27 +1267,33 @@ function startBackend(): void {
|
||||
});
|
||||
|
||||
child.on("error", (error) => {
|
||||
const wasExpected = expectedBackendExitChildren.has(child);
|
||||
if (backendProcess === child) {
|
||||
backendProcess = null;
|
||||
}
|
||||
closeBackendSession(`pid=${child.pid ?? "unknown"} error=${error.message}`);
|
||||
if (wasExpected) {
|
||||
return;
|
||||
}
|
||||
scheduleBackendRestart(error.message);
|
||||
});
|
||||
|
||||
child.on("exit", (code, signal) => {
|
||||
const wasExpected = expectedBackendExitChildren.has(child);
|
||||
if (backendProcess === child) {
|
||||
backendProcess = null;
|
||||
}
|
||||
closeBackendSession(
|
||||
`pid=${child.pid ?? "unknown"} code=${code ?? "null"} signal=${signal ?? "null"}`,
|
||||
);
|
||||
if (isQuitting) return;
|
||||
if (isQuitting || wasExpected) return;
|
||||
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
|
||||
scheduleBackendRestart(reason);
|
||||
});
|
||||
}
|
||||
|
||||
function stopBackend(): void {
|
||||
cancelBackendReadinessWait();
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
restartTimer = null;
|
||||
@@ -1031,6 +1304,7 @@ function stopBackend(): void {
|
||||
if (!child) return;
|
||||
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
expectedBackendExitChildren.add(child);
|
||||
child.kill("SIGTERM");
|
||||
setTimeout(() => {
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
@@ -1041,6 +1315,7 @@ function stopBackend(): void {
|
||||
}
|
||||
|
||||
async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
|
||||
cancelBackendReadinessWait();
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
restartTimer = null;
|
||||
@@ -1051,6 +1326,7 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
|
||||
if (!child) return;
|
||||
const backendChild = child;
|
||||
if (backendChild.exitCode !== null || backendChild.signalCode !== null) return;
|
||||
expectedBackendExitChildren.add(backendChild);
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
let settled = false;
|
||||
@@ -1092,9 +1368,116 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
|
||||
}
|
||||
|
||||
function registerIpcHandlers(): void {
|
||||
ipcMain.removeAllListeners(GET_WS_URL_CHANNEL);
|
||||
ipcMain.on(GET_WS_URL_CHANNEL, (event) => {
|
||||
event.returnValue = backendWsUrl;
|
||||
ipcMain.removeAllListeners(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
|
||||
ipcMain.on(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL, (event) => {
|
||||
event.returnValue = {
|
||||
label: "Local environment",
|
||||
httpBaseUrl: backendHttpUrl || null,
|
||||
wsBaseUrl: backendWsUrl || null,
|
||||
bootstrapToken: backendBootstrapToken || undefined,
|
||||
} as const;
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(GET_CLIENT_SETTINGS_CHANNEL);
|
||||
ipcMain.handle(GET_CLIENT_SETTINGS_CHANNEL, async () => readClientSettings(CLIENT_SETTINGS_PATH));
|
||||
|
||||
ipcMain.removeHandler(SET_CLIENT_SETTINGS_CHANNEL);
|
||||
ipcMain.handle(SET_CLIENT_SETTINGS_CHANNEL, async (_event, rawSettings: unknown) => {
|
||||
if (typeof rawSettings !== "object" || rawSettings === null) {
|
||||
throw new Error("Invalid client settings payload.");
|
||||
}
|
||||
|
||||
writeClientSettings(CLIENT_SETTINGS_PATH, rawSettings as ClientSettings);
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL);
|
||||
ipcMain.handle(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, async () =>
|
||||
readSavedEnvironmentRegistry(SAVED_ENVIRONMENT_REGISTRY_PATH),
|
||||
);
|
||||
|
||||
ipcMain.removeHandler(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL);
|
||||
ipcMain.handle(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, async (_event, rawRecords: unknown) => {
|
||||
if (!Array.isArray(rawRecords)) {
|
||||
throw new Error("Invalid saved environment registry payload.");
|
||||
}
|
||||
|
||||
writeSavedEnvironmentRegistry(
|
||||
SAVED_ENVIRONMENT_REGISTRY_PATH,
|
||||
rawRecords as readonly PersistedSavedEnvironmentRecord[],
|
||||
);
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(GET_SAVED_ENVIRONMENT_SECRET_CHANNEL);
|
||||
ipcMain.handle(
|
||||
GET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
|
||||
async (_event, rawEnvironmentId: unknown) => {
|
||||
if (typeof rawEnvironmentId !== "string" || rawEnvironmentId.trim().length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return readSavedEnvironmentSecret({
|
||||
registryPath: SAVED_ENVIRONMENT_REGISTRY_PATH,
|
||||
environmentId: rawEnvironmentId,
|
||||
secretStorage: getDesktopSecretStorage(),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
ipcMain.removeHandler(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL);
|
||||
ipcMain.handle(
|
||||
SET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
|
||||
async (_event, rawEnvironmentId: unknown, rawSecret: unknown) => {
|
||||
if (typeof rawEnvironmentId !== "string" || rawEnvironmentId.trim().length === 0) {
|
||||
throw new Error("Invalid saved environment id.");
|
||||
}
|
||||
if (typeof rawSecret !== "string" || rawSecret.trim().length === 0) {
|
||||
throw new Error("Invalid saved environment secret.");
|
||||
}
|
||||
|
||||
return writeSavedEnvironmentSecret({
|
||||
registryPath: SAVED_ENVIRONMENT_REGISTRY_PATH,
|
||||
environmentId: rawEnvironmentId,
|
||||
secret: rawSecret,
|
||||
secretStorage: getDesktopSecretStorage(),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
ipcMain.removeHandler(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL);
|
||||
ipcMain.handle(
|
||||
REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL,
|
||||
async (_event, rawEnvironmentId: unknown) => {
|
||||
if (typeof rawEnvironmentId !== "string" || rawEnvironmentId.trim().length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
removeSavedEnvironmentSecret({
|
||||
registryPath: SAVED_ENVIRONMENT_REGISTRY_PATH,
|
||||
environmentId: rawEnvironmentId,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
ipcMain.removeHandler(GET_SERVER_EXPOSURE_STATE_CHANNEL);
|
||||
ipcMain.handle(GET_SERVER_EXPOSURE_STATE_CHANNEL, async () => getDesktopServerExposureState());
|
||||
|
||||
ipcMain.removeHandler(SET_SERVER_EXPOSURE_MODE_CHANNEL);
|
||||
ipcMain.handle(SET_SERVER_EXPOSURE_MODE_CHANNEL, async (_event, rawMode: unknown) => {
|
||||
if (rawMode !== "local-only" && rawMode !== "network-accessible") {
|
||||
throw new Error("Invalid desktop server exposure input.");
|
||||
}
|
||||
|
||||
const nextMode = rawMode as DesktopServerExposureMode;
|
||||
if (nextMode === desktopServerExposureMode) {
|
||||
return getDesktopServerExposureState();
|
||||
}
|
||||
|
||||
const nextState = await applyDesktopServerExposureMode(nextMode, {
|
||||
persist: true,
|
||||
rejectIfUnavailable: true,
|
||||
});
|
||||
relaunchDesktopApp(`serverExposureMode=${nextMode}`);
|
||||
return nextState;
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
|
||||
@@ -1141,6 +1524,7 @@ function registerIpcHandlers(): void {
|
||||
id: item.id,
|
||||
label: item.label,
|
||||
destructive: item.destructive === true,
|
||||
disabled: item.disabled === true,
|
||||
}));
|
||||
if (normalizedItems.length === 0) {
|
||||
return null;
|
||||
@@ -1171,6 +1555,7 @@ function registerIpcHandlers(): void {
|
||||
}
|
||||
const itemOption: MenuItemConstructorOptions = {
|
||||
label: item.label,
|
||||
enabled: !item.disabled,
|
||||
click: () => resolve(item.id),
|
||||
};
|
||||
if (item.destructive) {
|
||||
@@ -1236,6 +1621,21 @@ function registerIpcHandlers(): void {
|
||||
state: updateState,
|
||||
} satisfies DesktopUpdateActionResult;
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(UPDATE_CHECK_CHANNEL);
|
||||
ipcMain.handle(UPDATE_CHECK_CHANNEL, async () => {
|
||||
if (!updaterConfigured) {
|
||||
return {
|
||||
checked: false,
|
||||
state: updateState,
|
||||
} satisfies DesktopUpdateCheckResult;
|
||||
}
|
||||
const checked = await checkForUpdates("web-ui");
|
||||
return {
|
||||
checked,
|
||||
state: updateState,
|
||||
} satisfies DesktopUpdateCheckResult;
|
||||
});
|
||||
}
|
||||
|
||||
function getIconOption(): { icon: string } | Record<string, never> {
|
||||
@@ -1245,14 +1645,19 @@ function getIconOption(): { icon: string } | Record<string, never> {
|
||||
return iconPath ? { icon: iconPath } : {};
|
||||
}
|
||||
|
||||
function getInitialWindowBackgroundColor(): string {
|
||||
return nativeTheme.shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
|
||||
}
|
||||
|
||||
function createWindow(): BrowserWindow {
|
||||
const window = new BrowserWindow({
|
||||
width: 1100,
|
||||
height: 780,
|
||||
minWidth: 840,
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
show: isDevelopment,
|
||||
autoHideMenuBar: true,
|
||||
backgroundColor: getInitialWindowBackgroundColor(),
|
||||
...getIconOption(),
|
||||
title: APP_DISPLAY_NAME,
|
||||
titleBarStyle: "hiddenInset",
|
||||
@@ -1283,6 +1688,22 @@ function createWindow(): BrowserWindow {
|
||||
menuTemplate.push({ type: "separator" });
|
||||
}
|
||||
|
||||
const externalUrl = getSafeExternalUrl(params.linkURL);
|
||||
if (externalUrl) {
|
||||
menuTemplate.push(
|
||||
{ label: "Copy Link", click: () => clipboard.writeText(params.linkURL) },
|
||||
{ type: "separator" },
|
||||
);
|
||||
}
|
||||
|
||||
if (params.mediaType === "image") {
|
||||
menuTemplate.push({
|
||||
label: "Copy Image",
|
||||
click: () => window.webContents.copyImageAt(params.x, params.y),
|
||||
});
|
||||
menuTemplate.push({ type: "separator" });
|
||||
}
|
||||
|
||||
menuTemplate.push(
|
||||
{ role: "cut", enabled: params.editFlags.canCut },
|
||||
{ role: "copy", enabled: params.editFlags.canCopy },
|
||||
@@ -1309,15 +1730,20 @@ function createWindow(): BrowserWindow {
|
||||
window.setTitle(APP_DISPLAY_NAME);
|
||||
emitUpdateState();
|
||||
});
|
||||
window.once("ready-to-show", () => {
|
||||
window.show();
|
||||
});
|
||||
if (!isDevelopment) {
|
||||
window.once("ready-to-show", () => {
|
||||
revealWindow(window);
|
||||
});
|
||||
}
|
||||
|
||||
if (isDevelopment) {
|
||||
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
|
||||
void window.loadURL(resolveDesktopDevServerUrl());
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
setImmediate(() => {
|
||||
revealWindow(window);
|
||||
});
|
||||
} else {
|
||||
void window.loadURL(`${DESKTOP_SCHEME}://app/index.html`);
|
||||
void window.loadURL(resolveDesktopWindowUrl());
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
@@ -1329,6 +1755,14 @@ function createWindow(): BrowserWindow {
|
||||
return window;
|
||||
}
|
||||
|
||||
function resolveDesktopWindowUrl(): string {
|
||||
if (backendHttpUrl) {
|
||||
return backendHttpUrl;
|
||||
}
|
||||
|
||||
return `${DESKTOP_SCHEME}://app`;
|
||||
}
|
||||
|
||||
// Override Electron's userData path before the `ready` event so that
|
||||
// Chromium session data uses a filesystem-friendly directory name.
|
||||
// Must be called synchronously at the top level — before `app.whenReady()`.
|
||||
@@ -1338,29 +1772,82 @@ configureAppIdentity();
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
writeDesktopLogHeader("bootstrap start");
|
||||
backendPort = await Effect.service(NetService).pipe(
|
||||
Effect.flatMap((net) => net.reserveLoopbackPort()),
|
||||
Effect.provide(NetService.layer),
|
||||
Effect.runPromise,
|
||||
const configuredBackendPort = resolveConfiguredDesktopBackendPort(process.env.T3CODE_PORT);
|
||||
if (isDevelopment && configuredBackendPort === undefined) {
|
||||
throw new Error("T3CODE_PORT is required in desktop development.");
|
||||
}
|
||||
|
||||
backendPort =
|
||||
configuredBackendPort ??
|
||||
(await resolveDesktopBackendPort({
|
||||
host: DESKTOP_LOOPBACK_HOST,
|
||||
startPort: DEFAULT_DESKTOP_BACKEND_PORT,
|
||||
requiredHosts: DESKTOP_REQUIRED_PORT_PROBE_HOSTS,
|
||||
}));
|
||||
writeDesktopLogHeader(
|
||||
configuredBackendPort === undefined
|
||||
? `selected backend port via sequential scan startPort=${DEFAULT_DESKTOP_BACKEND_PORT} port=${backendPort}`
|
||||
: `using configured backend port port=${backendPort}`,
|
||||
);
|
||||
writeDesktopLogHeader(`reserved backend port via NetService port=${backendPort}`);
|
||||
backendAuthToken = Crypto.randomBytes(24).toString("hex");
|
||||
const baseUrl = `ws://127.0.0.1:${backendPort}`;
|
||||
backendWsUrl = `${baseUrl}/?token=${encodeURIComponent(backendAuthToken)}`;
|
||||
writeDesktopLogHeader(`bootstrap resolved websocket endpoint baseUrl=${baseUrl}`);
|
||||
backendBootstrapToken = Crypto.randomBytes(24).toString("hex");
|
||||
if (desktopSettings.serverExposureMode !== DEFAULT_DESKTOP_SETTINGS.serverExposureMode) {
|
||||
writeDesktopLogHeader(
|
||||
`bootstrap restoring persisted server exposure mode mode=${desktopSettings.serverExposureMode}`,
|
||||
);
|
||||
}
|
||||
const serverExposureState = await applyDesktopServerExposureMode(
|
||||
desktopSettings.serverExposureMode,
|
||||
{
|
||||
persist: desktopSettings.serverExposureMode !== DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
|
||||
},
|
||||
);
|
||||
writeDesktopLogHeader(`bootstrap resolved backend endpoint baseUrl=${backendHttpUrl}`);
|
||||
if (serverExposureState.endpointUrl) {
|
||||
writeDesktopLogHeader(
|
||||
`bootstrap enabled network access endpointUrl=${serverExposureState.endpointUrl}`,
|
||||
);
|
||||
} else if (desktopSettings.serverExposureMode === "network-accessible") {
|
||||
writeDesktopLogHeader(
|
||||
"bootstrap fell back to local-only because no advertised network host was available",
|
||||
);
|
||||
}
|
||||
|
||||
registerIpcHandlers();
|
||||
writeDesktopLogHeader("bootstrap ipc handlers registered");
|
||||
startBackend();
|
||||
writeDesktopLogHeader("bootstrap backend start requested");
|
||||
|
||||
if (isDevelopment) {
|
||||
mainWindow = createWindow();
|
||||
writeDesktopLogHeader("bootstrap main window created");
|
||||
void waitForBackendHttpReady(backendHttpUrl)
|
||||
.then(() => {
|
||||
writeDesktopLogHeader("bootstrap backend ready");
|
||||
})
|
||||
.catch((error) => {
|
||||
if (isBackendReadinessAborted(error)) {
|
||||
return;
|
||||
}
|
||||
writeDesktopLogHeader(
|
||||
`bootstrap backend readiness warning message=${formatErrorMessage(error)}`,
|
||||
);
|
||||
console.warn("[desktop] backend readiness check timed out during dev bootstrap", error);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await waitForBackendHttpReady(backendHttpUrl);
|
||||
writeDesktopLogHeader("bootstrap backend ready");
|
||||
mainWindow = createWindow();
|
||||
writeDesktopLogHeader("bootstrap main window created");
|
||||
}
|
||||
|
||||
app.on("before-quit", () => {
|
||||
isQuitting = true;
|
||||
updateInstallInFlight = false;
|
||||
writeDesktopLogHeader("before-quit received");
|
||||
clearUpdatePollTimer();
|
||||
cancelBackendReadinessWait();
|
||||
stopBackend();
|
||||
restoreStdIoCapture?.();
|
||||
});
|
||||
@@ -1374,13 +1861,19 @@ app
|
||||
registerDesktopProtocol();
|
||||
configureAutoUpdater();
|
||||
void bootstrap().catch((error) => {
|
||||
if (isBackendReadinessAborted(error) && isQuitting) {
|
||||
return;
|
||||
}
|
||||
handleFatalStartupError("bootstrap", error);
|
||||
});
|
||||
|
||||
app.on("activate", () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
mainWindow = createWindow();
|
||||
const existingWindow = mainWindow ?? BrowserWindow.getAllWindows()[0];
|
||||
if (existingWindow) {
|
||||
revealWindow(existingWindow);
|
||||
return;
|
||||
}
|
||||
mainWindow = createWindow();
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
@@ -1388,7 +1881,7 @@ app
|
||||
});
|
||||
|
||||
app.on("window-all-closed", () => {
|
||||
if (process.platform !== "darwin") {
|
||||
if (process.platform !== "darwin" && !isQuitting) {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
@@ -1399,6 +1892,7 @@ if (process.platform !== "win32") {
|
||||
isQuitting = true;
|
||||
writeDesktopLogHeader("SIGINT received");
|
||||
clearUpdatePollTimer();
|
||||
cancelBackendReadinessWait();
|
||||
stopBackend();
|
||||
restoreStdIoCapture?.();
|
||||
app.quit();
|
||||
|
||||
@@ -9,15 +9,41 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
||||
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
|
||||
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
|
||||
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
|
||||
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
|
||||
const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
|
||||
const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
|
||||
const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
|
||||
const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
|
||||
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
|
||||
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
|
||||
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
|
||||
|
||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
getWsUrl: () => {
|
||||
const result = ipcRenderer.sendSync(GET_WS_URL_CHANNEL);
|
||||
return typeof result === "string" ? result : null;
|
||||
getLocalEnvironmentBootstrap: () => {
|
||||
const result = ipcRenderer.sendSync(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
|
||||
if (typeof result !== "object" || result === null) {
|
||||
return null;
|
||||
}
|
||||
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
|
||||
},
|
||||
getClientSettings: () => ipcRenderer.invoke(GET_CLIENT_SETTINGS_CHANNEL),
|
||||
setClientSettings: (settings) => ipcRenderer.invoke(SET_CLIENT_SETTINGS_CHANNEL, settings),
|
||||
getSavedEnvironmentRegistry: () => ipcRenderer.invoke(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL),
|
||||
setSavedEnvironmentRegistry: (records) =>
|
||||
ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, records),
|
||||
getSavedEnvironmentSecret: (environmentId) =>
|
||||
ipcRenderer.invoke(GET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
|
||||
setSavedEnvironmentSecret: (environmentId, secret) =>
|
||||
ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId, secret),
|
||||
removeSavedEnvironmentSecret: (environmentId) =>
|
||||
ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
|
||||
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
|
||||
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
|
||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
|
||||
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
||||
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
|
||||
@@ -35,6 +61,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
};
|
||||
},
|
||||
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
|
||||
checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL),
|
||||
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
|
||||
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
|
||||
onUpdateState: (listener) => {
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure";
|
||||
|
||||
describe("resolveLanAdvertisedHost", () => {
|
||||
it("prefers an explicit host override", () => {
|
||||
expect(
|
||||
resolveLanAdvertisedHost(
|
||||
{
|
||||
en0: [
|
||||
{
|
||||
address: "192.168.1.44",
|
||||
family: "IPv4",
|
||||
internal: false,
|
||||
netmask: "255.255.255.0",
|
||||
cidr: "192.168.1.44/24",
|
||||
mac: "00:00:00:00:00:00",
|
||||
},
|
||||
],
|
||||
},
|
||||
"10.0.0.9",
|
||||
),
|
||||
).toBe("10.0.0.9");
|
||||
});
|
||||
|
||||
it("returns the first usable non-internal IPv4 address", () => {
|
||||
expect(
|
||||
resolveLanAdvertisedHost(
|
||||
{
|
||||
lo0: [
|
||||
{
|
||||
address: "127.0.0.1",
|
||||
family: "IPv4",
|
||||
internal: true,
|
||||
netmask: "255.0.0.0",
|
||||
cidr: "127.0.0.1/8",
|
||||
mac: "00:00:00:00:00:00",
|
||||
},
|
||||
],
|
||||
en0: [
|
||||
{
|
||||
address: "192.168.1.44",
|
||||
family: "IPv4",
|
||||
internal: false,
|
||||
netmask: "255.255.255.0",
|
||||
cidr: "192.168.1.44/24",
|
||||
mac: "00:00:00:00:00:00",
|
||||
},
|
||||
],
|
||||
},
|
||||
undefined,
|
||||
),
|
||||
).toBe("192.168.1.44");
|
||||
});
|
||||
|
||||
it("returns null when no usable network address is available", () => {
|
||||
expect(
|
||||
resolveLanAdvertisedHost(
|
||||
{
|
||||
lo0: [
|
||||
{
|
||||
address: "127.0.0.1",
|
||||
family: "IPv4",
|
||||
internal: true,
|
||||
netmask: "255.0.0.0",
|
||||
cidr: "127.0.0.1/8",
|
||||
mac: "00:00:00:00:00:00",
|
||||
},
|
||||
],
|
||||
},
|
||||
undefined,
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDesktopServerExposure", () => {
|
||||
it("keeps the desktop server loopback-only when local-only mode is selected", () => {
|
||||
expect(
|
||||
resolveDesktopServerExposure({
|
||||
mode: "local-only",
|
||||
port: 3773,
|
||||
networkInterfaces: {},
|
||||
}),
|
||||
).toEqual({
|
||||
mode: "local-only",
|
||||
bindHost: "127.0.0.1",
|
||||
localHttpUrl: "http://127.0.0.1:3773",
|
||||
localWsUrl: "ws://127.0.0.1:3773",
|
||||
endpointUrl: null,
|
||||
advertisedHost: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("binds to all interfaces in network-accessible mode", () => {
|
||||
expect(
|
||||
resolveDesktopServerExposure({
|
||||
mode: "network-accessible",
|
||||
port: 3773,
|
||||
networkInterfaces: {
|
||||
en0: [
|
||||
{
|
||||
address: "192.168.1.44",
|
||||
family: "IPv4",
|
||||
internal: false,
|
||||
netmask: "255.255.255.0",
|
||||
cidr: "192.168.1.44/24",
|
||||
mac: "00:00:00:00:00:00",
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
mode: "network-accessible",
|
||||
bindHost: "0.0.0.0",
|
||||
localHttpUrl: "http://127.0.0.1:3773",
|
||||
localWsUrl: "ws://127.0.0.1:3773",
|
||||
endpointUrl: "http://192.168.1.44:3773",
|
||||
advertisedHost: "192.168.1.44",
|
||||
});
|
||||
});
|
||||
|
||||
it("stays network-accessible even when no LAN address is currently detectable", () => {
|
||||
expect(
|
||||
resolveDesktopServerExposure({
|
||||
mode: "network-accessible",
|
||||
port: 3773,
|
||||
networkInterfaces: {},
|
||||
}),
|
||||
).toEqual({
|
||||
mode: "network-accessible",
|
||||
bindHost: "0.0.0.0",
|
||||
localHttpUrl: "http://127.0.0.1:3773",
|
||||
localWsUrl: "ws://127.0.0.1:3773",
|
||||
endpointUrl: null,
|
||||
advertisedHost: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import type { NetworkInterfaceInfo } from "node:os";
|
||||
import type { DesktopServerExposureMode } from "@t3tools/contracts";
|
||||
|
||||
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
|
||||
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
|
||||
|
||||
export interface DesktopServerExposure {
|
||||
readonly mode: DesktopServerExposureMode;
|
||||
readonly bindHost: string;
|
||||
readonly localHttpUrl: string;
|
||||
readonly localWsUrl: string;
|
||||
readonly endpointUrl: string | null;
|
||||
readonly advertisedHost: string | null;
|
||||
}
|
||||
|
||||
const normalizeOptionalHost = (value: string | undefined): string | undefined => {
|
||||
const normalized = value?.trim();
|
||||
return normalized && normalized.length > 0 ? normalized : undefined;
|
||||
};
|
||||
|
||||
const isUsableLanIpv4Address = (address: string): boolean =>
|
||||
!address.startsWith("127.") && !address.startsWith("169.254.");
|
||||
|
||||
export function resolveLanAdvertisedHost(
|
||||
networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>,
|
||||
explicitHost: string | undefined,
|
||||
): string | null {
|
||||
const normalizedExplicitHost = normalizeOptionalHost(explicitHost);
|
||||
if (normalizedExplicitHost) {
|
||||
return normalizedExplicitHost;
|
||||
}
|
||||
|
||||
for (const interfaceAddresses of Object.values(networkInterfaces)) {
|
||||
if (!interfaceAddresses) continue;
|
||||
|
||||
for (const address of interfaceAddresses) {
|
||||
if (address.internal) continue;
|
||||
if (address.family !== "IPv4") continue;
|
||||
if (!isUsableLanIpv4Address(address.address)) continue;
|
||||
return address.address;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveDesktopServerExposure(input: {
|
||||
readonly mode: DesktopServerExposureMode;
|
||||
readonly port: number;
|
||||
readonly networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>;
|
||||
readonly advertisedHostOverride?: string;
|
||||
}): DesktopServerExposure {
|
||||
const localHttpUrl = `http://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
|
||||
const localWsUrl = `ws://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
|
||||
|
||||
if (input.mode === "local-only") {
|
||||
return {
|
||||
mode: input.mode,
|
||||
bindHost: DESKTOP_LOOPBACK_HOST,
|
||||
localHttpUrl,
|
||||
localWsUrl,
|
||||
endpointUrl: null,
|
||||
advertisedHost: null,
|
||||
};
|
||||
}
|
||||
|
||||
const advertisedHost = resolveLanAdvertisedHost(
|
||||
input.networkInterfaces,
|
||||
input.advertisedHostOverride,
|
||||
);
|
||||
|
||||
return {
|
||||
mode: input.mode,
|
||||
bindHost: DESKTOP_LAN_BIND_HOST,
|
||||
localHttpUrl,
|
||||
localWsUrl,
|
||||
endpointUrl: advertisedHost ? `http://${advertisedHost}:${input.port}` : null,
|
||||
advertisedHost,
|
||||
};
|
||||
}
|
||||
@@ -62,14 +62,13 @@ describe("syncShellEnvironment", () => {
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
||||
});
|
||||
|
||||
it("does nothing outside macOS", () => {
|
||||
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/inherited.sock",
|
||||
};
|
||||
const readEnvironment = vi.fn(() => ({
|
||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
||||
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||
}));
|
||||
|
||||
@@ -78,8 +77,29 @@ describe("syncShellEnvironment", () => {
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
||||
expect(env.PATH).toBe("/home/linuxbrew/.linuxbrew/bin:/usr/bin");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
|
||||
});
|
||||
|
||||
it("does nothing outside macOS and linux", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "C:/Program Files/Git/bin/bash.exe",
|
||||
PATH: "C:\\Windows\\System32",
|
||||
SSH_AUTH_SOCK: "/tmp/inherited.sock",
|
||||
};
|
||||
const readEnvironment = vi.fn(() => ({
|
||||
PATH: "/usr/local/bin:/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||
}));
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "win32",
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).not.toHaveBeenCalled();
|
||||
expect(env.PATH).toBe("/usr/bin");
|
||||
expect(env.PATH).toBe("C:\\Windows\\System32");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,8 @@
|
||||
import { readEnvironmentFromLoginShell, ShellEnvironmentReader } from "@t3tools/shared/shell";
|
||||
import {
|
||||
readEnvironmentFromLoginShell,
|
||||
resolveLoginShell,
|
||||
ShellEnvironmentReader,
|
||||
} from "@t3tools/shared/shell";
|
||||
|
||||
export function syncShellEnvironment(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
@@ -7,10 +11,13 @@ export function syncShellEnvironment(
|
||||
readEnvironment?: ShellEnvironmentReader;
|
||||
} = {},
|
||||
): void {
|
||||
if ((options.platform ?? process.platform) !== "darwin") return;
|
||||
const platform = options.platform ?? process.platform;
|
||||
if (platform !== "darwin" && platform !== "linux") return;
|
||||
|
||||
try {
|
||||
const shell = env.SHELL ?? "/bin/zsh";
|
||||
const shell = resolveLoginShell(platform, env.SHELL);
|
||||
if (!shell) return;
|
||||
|
||||
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
|
||||
@@ -71,10 +71,37 @@ describe("getAutoUpdateDisabledReason", () => {
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
hasUpdateFeedConfig: true,
|
||||
}),
|
||||
).toContain("packaged production builds");
|
||||
});
|
||||
|
||||
it("reports packaged local builds without an update feed as disabled", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment: false,
|
||||
isPackaged: true,
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
hasUpdateFeedConfig: false,
|
||||
}),
|
||||
).toContain("no update feed");
|
||||
});
|
||||
|
||||
it("allows packaged builds with an update feed", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment: false,
|
||||
isPackaged: true,
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
hasUpdateFeedConfig: true,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("reports env-disabled auto updates", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
@@ -83,6 +110,7 @@ describe("getAutoUpdateDisabledReason", () => {
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: true,
|
||||
hasUpdateFeedConfig: true,
|
||||
}),
|
||||
).toContain("T3CODE_DISABLE_AUTO_UPDATE");
|
||||
});
|
||||
@@ -95,6 +123,7 @@ describe("getAutoUpdateDisabledReason", () => {
|
||||
platform: "linux",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
hasUpdateFeedConfig: true,
|
||||
}),
|
||||
).toContain("AppImage");
|
||||
});
|
||||
|
||||
@@ -34,7 +34,11 @@ export function getAutoUpdateDisabledReason(args: {
|
||||
platform: NodeJS.Platform;
|
||||
appImage?: string | undefined;
|
||||
disabledByEnv: boolean;
|
||||
hasUpdateFeedConfig: boolean;
|
||||
}): string | null {
|
||||
if (!args.hasUpdateFeedConfig) {
|
||||
return "Automatic updates are not available because no update feed is configured.";
|
||||
}
|
||||
if (args.isDevelopment || !args.isPackaged) {
|
||||
return "Automatic updates are only available in packaged production builds.";
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
---
|
||||
import Layout from "../layouts/Layout.astro";
|
||||
import { RELEASES_URL } from "../lib/releases";
|
||||
---
|
||||
|
||||
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
|
||||
@@ -17,11 +18,11 @@ import Layout from "../layouts/Layout.astro";
|
||||
<h2 class="platform-name">macOS</h2>
|
||||
</div>
|
||||
<div class="download-cards">
|
||||
<a class="download-card" data-asset="arm64.dmg" href="#">
|
||||
<a class="download-card" data-asset="arm64.dmg" href={RELEASES_URL}>
|
||||
<span class="card-arch">Apple Silicon (arm64)</span>
|
||||
<span class="card-format">.dmg</span>
|
||||
</a>
|
||||
<a class="download-card" data-asset="x64.dmg" href="#">
|
||||
<a class="download-card" data-asset="x64.dmg" href={RELEASES_URL}>
|
||||
<span class="card-arch">Intel (x64)</span>
|
||||
<span class="card-format">.dmg</span>
|
||||
</a>
|
||||
@@ -35,7 +36,7 @@ import Layout from "../layouts/Layout.astro";
|
||||
<h2 class="platform-name">Windows</h2>
|
||||
</div>
|
||||
<div class="download-cards">
|
||||
<a class="download-card" data-asset="x64.exe" href="#">
|
||||
<a class="download-card" data-asset="x64.exe" href={RELEASES_URL}>
|
||||
<span class="card-arch">Windows 10, 11</span>
|
||||
<span class="card-format">.exe</span>
|
||||
</a>
|
||||
@@ -49,7 +50,7 @@ import Layout from "../layouts/Layout.astro";
|
||||
<h2 class="platform-name">Linux</h2>
|
||||
</div>
|
||||
<div class="download-cards">
|
||||
<a class="download-card" data-asset="x86_64.AppImage" href="#">
|
||||
<a class="download-card" data-asset="x86_64.AppImage" href={RELEASES_URL}>
|
||||
<span class="card-arch">x86_64</span>
|
||||
<span class="card-format">AppImage</span>
|
||||
</a>
|
||||
|
||||
@@ -26,6 +26,7 @@ import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore
|
||||
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
|
||||
import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
|
||||
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
|
||||
import { GitStatusBroadcaster } from "../src/git/Services/GitStatusBroadcaster.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
|
||||
@@ -38,16 +39,18 @@ import { ProjectionPendingApprovalRepository } from "../src/persistence/Services
|
||||
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
|
||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
|
||||
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
|
||||
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
|
||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
|
||||
import { RepositoryIdentityResolverLive } from "../src/project/Layers/RepositoryIdentityResolver.ts";
|
||||
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
|
||||
import { RuntimeReceiptBusLive } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
|
||||
import { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
|
||||
import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
|
||||
import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
|
||||
import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
|
||||
@@ -67,6 +70,8 @@ import {
|
||||
type TestProviderAdapterHarness,
|
||||
} from "./TestProviderAdapter.integration.ts";
|
||||
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
|
||||
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
|
||||
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
return execFileSync("git", args, {
|
||||
@@ -123,7 +128,7 @@ function waitFor<A, E>(
|
||||
read: Effect.Effect<A, E>,
|
||||
predicate: (value: A) => boolean,
|
||||
description: string,
|
||||
timeoutMs = 10_000,
|
||||
timeoutMs = 40_000,
|
||||
): Effect.Effect<A, never> {
|
||||
const RETRY_SIGNAL = "wait_for_retry";
|
||||
const retryIntervalMs = 10;
|
||||
@@ -286,40 +291,73 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
);
|
||||
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
|
||||
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
orchestrationLayer,
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
projectionSnapshotQueryLayer,
|
||||
orchestrationLayer.pipe(Layer.provide(projectionSnapshotQueryLayer)),
|
||||
ProjectionCheckpointRepositoryLive,
|
||||
ProjectionPendingApprovalRepositoryLive,
|
||||
checkpointStoreLayer,
|
||||
providerLayer,
|
||||
RuntimeReceiptBusLive,
|
||||
RuntimeReceiptBusTest,
|
||||
);
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest();
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(serverSettingsLayer),
|
||||
);
|
||||
const gitCoreLayer = Layer.succeed(GitCore, {
|
||||
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
|
||||
Effect.succeed({ branch: input.newBranch }),
|
||||
} as unknown as GitCoreShape);
|
||||
const textGenerationLayer = Layer.succeed(TextGeneration, {
|
||||
generateBranchName: () => Effect.succeed({ branch: null }),
|
||||
generateBranchName: () => Effect.succeed({ branch: "update" }),
|
||||
generateThreadTitle: () => Effect.succeed({ title: "New thread" }),
|
||||
} as unknown as TextGenerationShape);
|
||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
Layer.provideMerge(serverSettingsLayer),
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(GitStatusBroadcaster, {
|
||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||
refreshLocalStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: true,
|
||||
branch: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
refreshStatus: () => Effect.die("refreshStatus should not be called in this test"),
|
||||
streamStatus: () => Stream.empty,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
WorkspaceEntriesLive.pipe(
|
||||
Layer.provide(WorkspacePathsLive),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(WorkspacePathsLive),
|
||||
);
|
||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeIngestionLayer),
|
||||
Layer.provideMerge(providerCommandReactorLayer),
|
||||
Layer.provideMerge(checkpointReactorLayer),
|
||||
);
|
||||
const layer = orchestrationReactorLayer.pipe(
|
||||
const layer = Layer.empty.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(orchestrationReactorLayer),
|
||||
Layer.provide(persistenceLayer),
|
||||
Layer.provideMerge(RepositoryIdentityResolverLive),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
@@ -354,10 +392,10 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
|
||||
const scope = yield* Scope.make("sequential");
|
||||
yield* tryRuntimePromise("start OrchestrationReactor", () =>
|
||||
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
|
||||
runtime.runPromise(reactor.start().pipe(Scope.provide(scope))),
|
||||
).pipe(Effect.orDie);
|
||||
const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
|
||||
yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
|
||||
yield* Stream.runForEach(runtimeReceiptBus.streamEventsForTest, (receipt) =>
|
||||
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
|
||||
).pipe(Effect.forkIn(scope));
|
||||
yield* Effect.sleep(10);
|
||||
@@ -400,7 +438,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
) =>
|
||||
waitFor(
|
||||
pendingApprovalRepository
|
||||
.getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })
|
||||
.getByRequestId({ requestId: ApprovalRequestId.make(requestId) })
|
||||
.pipe(
|
||||
Effect.map((row) =>
|
||||
Option.match(row, {
|
||||
|
||||
@@ -289,7 +289,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
|
||||
state.turnCount += 1;
|
||||
const turnCount = state.turnCount;
|
||||
const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
|
||||
const turnId = TurnId.make(`turn-${turnCount}`);
|
||||
|
||||
const response = state.queuedResponses.shift();
|
||||
if (!response) {
|
||||
@@ -307,7 +307,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
...(fixtureEvent as Record<string, unknown>),
|
||||
eventId: randomUUID(),
|
||||
provider,
|
||||
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
|
||||
sessionId: RuntimeSessionId.make(String(input.threadId)),
|
||||
createdAt: nowIso(),
|
||||
};
|
||||
rawEvent.threadId = state.snapshot.threadId;
|
||||
@@ -363,7 +363,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
if (deferredTurnCompletedEvents.length === 0) {
|
||||
yield* emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe(randomUUID()),
|
||||
eventId: EventId.make(randomUUID()),
|
||||
provider,
|
||||
createdAt: nowIso(),
|
||||
threadId: state.snapshot.threadId,
|
||||
@@ -472,6 +472,15 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
sessions.clear();
|
||||
});
|
||||
|
||||
const compactThread: ProviderAdapterShape<ProviderAdapterError>["compactThread"] = (threadId) =>
|
||||
readThread(threadId).pipe(
|
||||
Effect.map((snapshot) => {
|
||||
const latestTurn = snapshot.turns.at(-1);
|
||||
const latestItem = latestTurn?.items.at(-1);
|
||||
return typeof latestItem === "string" ? latestItem : null;
|
||||
}),
|
||||
);
|
||||
|
||||
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
|
||||
provider,
|
||||
capabilities: {
|
||||
@@ -486,6 +495,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
listSessions,
|
||||
hasSession,
|
||||
readThread,
|
||||
compactThread,
|
||||
rollbackThread,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromQueue(runtimeEvents),
|
||||
|
||||
@@ -5,14 +5,14 @@ const PROVIDER = "codex" as const;
|
||||
const SESSION_ID = "fixture-session";
|
||||
const THREAD_ID = "fixture-thread";
|
||||
const TURN_ID = "fixture-turn";
|
||||
const REQUEST_ID = RuntimeRequestId.makeUnsafe("req-1");
|
||||
const REQUEST_ID = RuntimeRequestId.make("req-1");
|
||||
|
||||
function baseEvent(
|
||||
eventId: string,
|
||||
createdAt: string,
|
||||
): Pick<LegacyProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
|
||||
return {
|
||||
eventId: EventId.makeUnsafe(eventId),
|
||||
eventId: EventId.make(eventId),
|
||||
provider: PROVIDER,
|
||||
sessionId: SESSION_ID,
|
||||
createdAt,
|
||||
|
||||
@@ -30,14 +30,13 @@ import type {
|
||||
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asApprovalRequestId = (value: string): ApprovalRequestId =>
|
||||
ApprovalRequestId.makeUnsafe(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.make(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asEventId = (value: string): EventId => EventId.make(value);
|
||||
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
|
||||
|
||||
const PROJECT_ID = asProjectId("project-1");
|
||||
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
|
||||
const THREAD_ID = ThreadId.make("thread-1");
|
||||
const FIXTURE_TURN_ID = "fixture-turn";
|
||||
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
|
||||
type IntegrationProvider = ProviderKind;
|
||||
@@ -57,7 +56,7 @@ function waitForSync<A>(
|
||||
read: () => A,
|
||||
predicate: (value: A) => boolean,
|
||||
description: string,
|
||||
timeoutMs = 3000,
|
||||
timeoutMs = 10_000,
|
||||
): Effect.Effect<A, never> {
|
||||
return Effect.gen(function* () {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
@@ -112,7 +111,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
commandId: CommandId.make("cmd-project-create"),
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
@@ -125,7 +124,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
commandId: CommandId.make("cmd-thread-create"),
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
@@ -150,7 +149,7 @@ const startTurn = (input: {
|
||||
}) =>
|
||||
input.harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe(input.commandId),
|
||||
commandId: CommandId.make(input.commandId),
|
||||
threadId: THREAD_ID,
|
||||
message: {
|
||||
messageId: asMessageId(input.messageId),
|
||||
@@ -261,7 +260,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create-real-codex"),
|
||||
commandId: CommandId.make("cmd-project-create-real-codex"),
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
@@ -274,7 +273,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-real-codex"),
|
||||
commandId: CommandId.make("cmd-thread-create-real-codex"),
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
@@ -291,7 +290,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-real-codex-1"),
|
||||
threadId: THREAD_ID,
|
||||
message: {
|
||||
messageId: asMessageId("msg-real-codex-1"),
|
||||
@@ -318,7 +317,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-2"),
|
||||
commandId: CommandId.make("cmd-turn-start-real-codex-2"),
|
||||
threadId: THREAD_ID,
|
||||
message: {
|
||||
messageId: asMessageId("msg-real-codex-2"),
|
||||
@@ -583,7 +582,7 @@ it.live("tracks approval requests and resolves pending approvals on user respons
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.makeUnsafe("cmd-approval-respond"),
|
||||
commandId: CommandId.make("cmd-approval-respond"),
|
||||
threadId: THREAD_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
decision: "accept",
|
||||
@@ -815,7 +814,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert"),
|
||||
commandId: CommandId.make("cmd-checkpoint-revert"),
|
||||
threadId: THREAD_ID,
|
||||
turnCount: 1,
|
||||
createdAt: nowIso(),
|
||||
@@ -875,7 +874,7 @@ it.live(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-no-session"),
|
||||
commandId: CommandId.make("cmd-checkpoint-revert-no-session"),
|
||||
threadId: THREAD_ID,
|
||||
turnCount: 0,
|
||||
createdAt: nowIso(),
|
||||
@@ -1119,7 +1118,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
|
||||
commandId: CommandId.make("cmd-claude-approval-respond"),
|
||||
threadId: THREAD_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
decision: "accept",
|
||||
@@ -1192,7 +1191,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.interrupt",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
|
||||
commandId: CommandId.make("cmd-turn-interrupt-claude"),
|
||||
threadId: THREAD_ID,
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
@@ -1309,7 +1308,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
|
||||
commandId: CommandId.make("cmd-checkpoint-revert-claude"),
|
||||
threadId: THREAD_ID,
|
||||
turnCount: 1,
|
||||
createdAt: nowIso(),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ProviderRuntimeEvent } 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 { it, assert } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
|
||||
@@ -12,6 +13,7 @@ import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
} from "../src/provider/Services/ProviderService.ts";
|
||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
|
||||
@@ -60,6 +62,7 @@ const makeIntegrationFixture = Effect.gen(function* () {
|
||||
const shared = Layer.mergeAll(
|
||||
directoryLayer,
|
||||
Layer.succeed(ProviderAdapterRegistry, registry),
|
||||
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
|
||||
AnalyticsService.layerTest,
|
||||
).pipe(Layer.provide(SqlitePersistenceMemory));
|
||||
|
||||
@@ -83,6 +86,7 @@ const collectEventsDuring = <A, E, R>(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
yield* Effect.sleep("50 millis");
|
||||
yield* action;
|
||||
|
||||
return yield* Effect.forEach(
|
||||
@@ -101,7 +105,6 @@ const runTurn = (input: {
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
yield* input.harness.queueTurnResponse(input.threadId, input.response);
|
||||
|
||||
return yield* collectEventsDuring(
|
||||
input.provider.streamEvents,
|
||||
input.response.events.length,
|
||||
@@ -113,21 +116,18 @@ const runTurn = (input: {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("replays typed runtime fixture events", () =>
|
||||
it.live("replays typed runtime fixture events", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-typed"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-typed"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
|
||||
threadId: ThreadId.make("thread-integration-typed"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
const observedEvents = yield* runTurn({
|
||||
@@ -146,7 +146,7 @@ it.effect("replays typed runtime fixture events", () =>
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("replays file-changing fixture turn events", () =>
|
||||
it.live("replays file-changing fixture turn events", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const { join } = yield* Path.Path;
|
||||
@@ -154,15 +154,12 @@ it.effect("replays file-changing fixture turn events", () =>
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-tools"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-tools"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
|
||||
threadId: ThreadId.make("thread-integration-tools"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
const observedEvents = yield* runTurn({
|
||||
@@ -185,7 +182,7 @@ it.effect("replays file-changing fixture turn events", () =>
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("runs multi-turn tool/approval flow", () =>
|
||||
it.live("runs multi-turn tool/approval flow", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const { join } = yield* Path.Path;
|
||||
@@ -193,15 +190,12 @@ it.effect("runs multi-turn tool/approval flow", () =>
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-multi"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-multi"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
|
||||
threadId: ThreadId.make("thread-integration-multi"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
const firstTurnEvents = yield* runTurn({
|
||||
@@ -239,7 +233,7 @@ it.effect("runs multi-turn tool/approval flow", () =>
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("rolls back provider conversation state only", () =>
|
||||
it.live("rolls back provider conversation state only", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const { join } = yield* Path.Path;
|
||||
@@ -247,15 +241,12 @@ it.effect("rolls back provider conversation state only", () =>
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-rollback"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-rollback"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
|
||||
threadId: ThreadId.make("thread-integration-rollback"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
yield* runTurn({
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.14",
|
||||
"version": "0.0.17",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -8,29 +8,29 @@
|
||||
"directory": "apps/server"
|
||||
},
|
||||
"bin": {
|
||||
"t3": "./dist/index.mjs"
|
||||
"t3": "./dist/bin.mjs"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "bun run src/index.ts",
|
||||
"dev": "bun run src/bin.ts",
|
||||
"build": "node scripts/cli.ts build",
|
||||
"start": "node dist/index.mjs",
|
||||
"start": "node dist/bin.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
|
||||
"@effect/platform-bun": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/sql-sqlite-bun": "catalog:",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"effect": "catalog:",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0"
|
||||
"open": "^10.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
@@ -40,7 +40,6 @@
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/bun": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"@types/ws": "^8.5.13",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
|
||||
@@ -14,6 +14,22 @@ import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog
|
||||
import rootPackageJson from "../../../package.json" with { type: "json" };
|
||||
import serverPackageJson from "../package.json" with { type: "json" };
|
||||
|
||||
interface PackageJson {
|
||||
name: string;
|
||||
repository: {
|
||||
type: string;
|
||||
url: string;
|
||||
directory: string;
|
||||
};
|
||||
bin: Record<string, string>;
|
||||
type: string;
|
||||
version: string;
|
||||
engines: Record<string, string>;
|
||||
files: string[];
|
||||
dependencies: Record<string, string>;
|
||||
overrides: Record<string, string>;
|
||||
}
|
||||
|
||||
class CliError extends Data.TaggedError("CliError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
@@ -177,7 +193,7 @@ const publishCmd = Command.make(
|
||||
const backupPath = `${packageJsonPath}.bak`;
|
||||
|
||||
// Assert build assets exist
|
||||
for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
|
||||
for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) {
|
||||
const abs = path.join(serverDir, relPath);
|
||||
if (!(yield* fs.exists(abs))) {
|
||||
return yield* new CliError({
|
||||
@@ -192,7 +208,7 @@ const publishCmd = Command.make(
|
||||
// Resolve catalog dependencies before any file mutations. If this throws,
|
||||
// acquire fails and no release hook runs, so filesystem must still be untouched.
|
||||
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
|
||||
const pkg = {
|
||||
const pkg: PackageJson = {
|
||||
name: serverPackageJson.name,
|
||||
repository: serverPackageJson.repository,
|
||||
bin: serverPackageJson.bin,
|
||||
@@ -200,7 +216,8 @@ const publishCmd = Command.make(
|
||||
version,
|
||||
engines: serverPackageJson.engines,
|
||||
files: serverPackageJson.files,
|
||||
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
|
||||
dependencies: serverPackageJson.dependencies,
|
||||
overrides: rootPackageJson.overrides,
|
||||
};
|
||||
|
||||
pkg.dependencies = resolveCatalogDependencies(
|
||||
@@ -208,6 +225,11 @@ const publishCmd = Command.make(
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"apps/server dependencies",
|
||||
);
|
||||
pkg.overrides = resolveCatalogDependencies(
|
||||
pkg.overrides,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"root overrides",
|
||||
);
|
||||
|
||||
const original = yield* fs.readFileString(packageJsonPath);
|
||||
yield* fs.writeFileString(backupPath, original);
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import { ServerConfigShape } from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
|
||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
||||
import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { AuthControlPlane } from "../Services/AuthControlPlane.ts";
|
||||
import { makeAuthControlPlane } from "./AuthControlPlane.ts";
|
||||
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
|
||||
|
||||
const makeServerConfigLayer = (
|
||||
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
||||
) =>
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
return {
|
||||
...config,
|
||||
...overrides,
|
||||
} satisfies ServerConfigShape;
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-control-plane-test-" })),
|
||||
);
|
||||
|
||||
const makeAuthControlPlaneLayer = (
|
||||
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
||||
) =>
|
||||
Layer.effect(AuthControlPlane, makeAuthControlPlane).pipe(
|
||||
Layer.provideMerge(BootstrapCredentialServiceLive),
|
||||
Layer.provideMerge(SessionCredentialServiceLive),
|
||||
Layer.provideMerge(ServerSecretStoreLive),
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
Layer.provide(makeServerConfigLayer(overrides)),
|
||||
);
|
||||
|
||||
it.layer(NodeServices.layer)("AuthControlPlane", (it) => {
|
||||
it.effect("creates, lists, and revokes client pairing links", () =>
|
||||
Effect.gen(function* () {
|
||||
const authControlPlane = yield* AuthControlPlane;
|
||||
|
||||
const created = yield* authControlPlane.createPairingLink({
|
||||
role: "client",
|
||||
subject: "one-time-token",
|
||||
label: "CI phone",
|
||||
});
|
||||
const listedBeforeRevoke = yield* authControlPlane.listPairingLinks({ role: "client" });
|
||||
const revoked = yield* authControlPlane.revokePairingLink(created.id);
|
||||
const listedAfterRevoke = yield* authControlPlane.listPairingLinks({ role: "client" });
|
||||
|
||||
expect(created.role).toBe("client");
|
||||
expect(created.credential.length).toBeGreaterThan(0);
|
||||
expect(listedBeforeRevoke).toHaveLength(1);
|
||||
expect(listedBeforeRevoke[0]?.id).toBe(created.id);
|
||||
expect(listedBeforeRevoke[0]?.label).toBe("CI phone");
|
||||
expect(listedBeforeRevoke[0]?.credential).toBe(created.credential);
|
||||
expect(revoked).toBe(true);
|
||||
expect(listedAfterRevoke).toHaveLength(0);
|
||||
}).pipe(Effect.provide(makeAuthControlPlaneLayer())),
|
||||
);
|
||||
|
||||
it.effect("issues bearer sessions and lists them without exposing raw tokens", () =>
|
||||
Effect.gen(function* () {
|
||||
const authControlPlane = yield* AuthControlPlane;
|
||||
const sessionCredentials = yield* SessionCredentialService;
|
||||
|
||||
const issued = yield* authControlPlane.issueSession({
|
||||
label: "deploy-bot",
|
||||
});
|
||||
const verified = yield* sessionCredentials.verify(issued.token);
|
||||
const listedBeforeRevoke = yield* authControlPlane.listSessions();
|
||||
const revoked = yield* authControlPlane.revokeSession(issued.sessionId);
|
||||
const listedAfterRevoke = yield* authControlPlane.listSessions();
|
||||
|
||||
expect(issued.method).toBe("bearer-session-token");
|
||||
expect(issued.role).toBe("owner");
|
||||
expect(issued.client.deviceType).toBe("bot");
|
||||
expect(issued.client.label).toBe("deploy-bot");
|
||||
expect(verified.sessionId).toBe(issued.sessionId);
|
||||
expect(verified.role).toBe("owner");
|
||||
expect(verified.method).toBe("bearer-session-token");
|
||||
expect(listedBeforeRevoke).toHaveLength(1);
|
||||
expect(listedBeforeRevoke[0]?.sessionId).toBe(issued.sessionId);
|
||||
expect("token" in (listedBeforeRevoke[0] ?? {})).toBe(false);
|
||||
expect(revoked).toBe(true);
|
||||
expect(listedAfterRevoke).toHaveLength(0);
|
||||
}).pipe(Effect.provide(makeAuthControlPlaneLayer())),
|
||||
);
|
||||
|
||||
it.effect("surfaces lastConnectedAt through the listed session view", () =>
|
||||
Effect.gen(function* () {
|
||||
const authControlPlane = yield* AuthControlPlane;
|
||||
const sessionCredentials = yield* SessionCredentialService;
|
||||
|
||||
const issued = yield* authControlPlane.issueSession({
|
||||
label: "remote-ipad",
|
||||
});
|
||||
const beforeConnect = yield* authControlPlane.listSessions();
|
||||
yield* sessionCredentials.markConnected(issued.sessionId);
|
||||
const afterConnect = yield* authControlPlane.listSessions();
|
||||
|
||||
expect(beforeConnect[0]?.lastConnectedAt).toBeNull();
|
||||
expect(afterConnect[0]?.lastConnectedAt).not.toBeNull();
|
||||
}).pipe(Effect.provide(makeAuthControlPlaneLayer())),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,176 @@
|
||||
import type { AuthClientSession, AuthPairingLink } from "@t3tools/contracts";
|
||||
import { DateTime, Effect, Layer } from "effect";
|
||||
|
||||
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
|
||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
||||
import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
|
||||
import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
|
||||
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "../../persistence/Layers/Sqlite.ts";
|
||||
import {
|
||||
AuthControlPlane,
|
||||
AuthControlPlaneError,
|
||||
AuthControlPlaneShape,
|
||||
DEFAULT_SESSION_SUBJECT,
|
||||
IssuedBearerSession,
|
||||
IssuedPairingLink,
|
||||
} from "../Services/AuthControlPlane.ts";
|
||||
|
||||
const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {
|
||||
if (left.role !== right.role) {
|
||||
return left.role === "owner" ? -1 : 1;
|
||||
}
|
||||
if (left.connected !== right.connected) {
|
||||
return left.connected ? -1 : 1;
|
||||
}
|
||||
return right.issuedAt.epochMilliseconds - left.issuedAt.epochMilliseconds;
|
||||
};
|
||||
|
||||
const toAuthControlPlaneError =
|
||||
(message: string) =>
|
||||
(cause: unknown): AuthControlPlaneError =>
|
||||
new AuthControlPlaneError({
|
||||
message,
|
||||
cause,
|
||||
});
|
||||
|
||||
export const makeAuthControlPlane = Effect.gen(function* () {
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
const sessions = yield* SessionCredentialService;
|
||||
|
||||
const createPairingLink: AuthControlPlaneShape["createPairingLink"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const createdAt = yield* DateTime.now;
|
||||
const issued = yield* bootstrapCredentials.issueOneTimeToken({
|
||||
role: input?.role ?? "client",
|
||||
subject: input?.subject ?? "one-time-token",
|
||||
...(input?.ttl ? { ttl: input.ttl } : {}),
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
});
|
||||
return {
|
||||
id: issued.id,
|
||||
credential: issued.credential,
|
||||
role: input?.role ?? "client",
|
||||
subject: input?.subject ?? "one-time-token",
|
||||
...(issued.label ? { label: issued.label } : {}),
|
||||
createdAt: DateTime.toUtc(createdAt),
|
||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
||||
} satisfies IssuedPairingLink;
|
||||
}).pipe(Effect.mapError(toAuthControlPlaneError("Failed to create pairing link.")));
|
||||
|
||||
const listPairingLinks: AuthControlPlaneShape["listPairingLinks"] = (input) =>
|
||||
bootstrapCredentials.listActive().pipe(
|
||||
Effect.map((pairingLinks) =>
|
||||
pairingLinks
|
||||
.filter((pairingLink) => (input?.role ? pairingLink.role === input.role : true))
|
||||
.filter((pairingLink) => !input?.excludeSubjects?.includes(pairingLink.subject))
|
||||
.map((pairingLink) =>
|
||||
pairingLink.label
|
||||
? ({
|
||||
id: pairingLink.id,
|
||||
credential: pairingLink.credential,
|
||||
role: pairingLink.role,
|
||||
subject: pairingLink.subject,
|
||||
label: pairingLink.label,
|
||||
createdAt: pairingLink.createdAt,
|
||||
expiresAt: pairingLink.expiresAt,
|
||||
} satisfies AuthPairingLink)
|
||||
: ({
|
||||
id: pairingLink.id,
|
||||
credential: pairingLink.credential,
|
||||
role: pairingLink.role,
|
||||
subject: pairingLink.subject,
|
||||
createdAt: pairingLink.createdAt,
|
||||
expiresAt: pairingLink.expiresAt,
|
||||
} satisfies AuthPairingLink),
|
||||
)
|
||||
.toSorted(
|
||||
(left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
|
||||
),
|
||||
),
|
||||
Effect.mapError(toAuthControlPlaneError("Failed to list pairing links.")),
|
||||
);
|
||||
|
||||
const revokePairingLink: AuthControlPlaneShape["revokePairingLink"] = (id) =>
|
||||
bootstrapCredentials
|
||||
.revoke(id)
|
||||
.pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke pairing link.")));
|
||||
|
||||
const issueSession: AuthControlPlaneShape["issueSession"] = (input) =>
|
||||
sessions
|
||||
.issue({
|
||||
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
|
||||
method: "bearer-session-token",
|
||||
role: input?.role ?? "owner",
|
||||
client: {
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
deviceType: "bot",
|
||||
},
|
||||
...(input?.ttl ? { ttl: input.ttl } : {}),
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap((issued) => {
|
||||
if (issued.method !== "bearer-session-token") {
|
||||
return Effect.fail(
|
||||
new AuthControlPlaneError({
|
||||
message: "CLI session issuance produced an unexpected session method.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed({
|
||||
sessionId: issued.sessionId,
|
||||
token: issued.token,
|
||||
method: "bearer-session-token" as const,
|
||||
role: issued.role,
|
||||
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
|
||||
client: issued.client,
|
||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
||||
} satisfies IssuedBearerSession);
|
||||
}),
|
||||
Effect.mapError(toAuthControlPlaneError("Failed to issue session token.")),
|
||||
);
|
||||
|
||||
const listSessions: AuthControlPlaneShape["listSessions"] = () =>
|
||||
sessions.listActive().pipe(
|
||||
Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)),
|
||||
Effect.mapError(toAuthControlPlaneError("Failed to list sessions.")),
|
||||
);
|
||||
|
||||
const revokeSession: AuthControlPlaneShape["revokeSession"] = (sessionId) =>
|
||||
sessions
|
||||
.revoke(sessionId)
|
||||
.pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke session.")));
|
||||
|
||||
const revokeOtherSessionsExcept: AuthControlPlaneShape["revokeOtherSessionsExcept"] = (
|
||||
sessionId,
|
||||
) =>
|
||||
sessions
|
||||
.revokeAllExcept(sessionId)
|
||||
.pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke other sessions.")));
|
||||
|
||||
return {
|
||||
createPairingLink,
|
||||
listPairingLinks,
|
||||
revokePairingLink,
|
||||
issueSession,
|
||||
listSessions,
|
||||
revokeSession,
|
||||
revokeOtherSessionsExcept,
|
||||
} satisfies AuthControlPlaneShape;
|
||||
});
|
||||
|
||||
export const AuthCoreLive = Layer.mergeAll(
|
||||
BootstrapCredentialServiceLive,
|
||||
SessionCredentialServiceLive,
|
||||
);
|
||||
|
||||
export const AuthStorageLive = Layer.mergeAll(ServerSecretStoreLive, SqlitePersistenceLayerLive);
|
||||
|
||||
export const AuthRuntimeLive = AuthCoreLive.pipe(Layer.provideMerge(AuthStorageLive));
|
||||
|
||||
export const AuthControlPlaneLive = Layer.effect(AuthControlPlane, makeAuthControlPlane);
|
||||
|
||||
export const AuthControlPlaneRuntimeLive = AuthControlPlaneLive.pipe(
|
||||
Layer.provideMerge(AuthRuntimeLive),
|
||||
);
|
||||
@@ -0,0 +1,151 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Duration, Effect, Layer } from "effect";
|
||||
import { TestClock } from "effect/testing";
|
||||
|
||||
import type { ServerConfigShape } from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
|
||||
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
|
||||
|
||||
const makeServerConfigLayer = (
|
||||
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
||||
) =>
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
return {
|
||||
...config,
|
||||
...overrides,
|
||||
} satisfies ServerConfigShape;
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-bootstrap-test-" })),
|
||||
);
|
||||
|
||||
const makeBootstrapCredentialLayer = (
|
||||
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
||||
) =>
|
||||
BootstrapCredentialServiceLive.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
Layer.provide(makeServerConfigLayer(overrides)),
|
||||
);
|
||||
|
||||
it.layer(NodeServices.layer)("BootstrapCredentialServiceLive", (it) => {
|
||||
it.effect("issues pairing tokens in a short manual-entry format", () =>
|
||||
Effect.gen(function* () {
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
const issued = yield* bootstrapCredentials.issueOneTimeToken();
|
||||
|
||||
expect(issued.credential).toMatch(/^[23456789ABCDEFGHJKLMNPQRSTUVWXYZ]{12}$/);
|
||||
}).pipe(Effect.provide(makeBootstrapCredentialLayer())),
|
||||
);
|
||||
|
||||
it.effect("issues one-time bootstrap tokens that can only be consumed once", () =>
|
||||
Effect.gen(function* () {
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
const issued = yield* bootstrapCredentials.issueOneTimeToken({ label: "Julius iPhone" });
|
||||
const first = yield* bootstrapCredentials.consume(issued.credential);
|
||||
const second = yield* Effect.flip(bootstrapCredentials.consume(issued.credential));
|
||||
|
||||
expect(first.method).toBe("one-time-token");
|
||||
expect(first.role).toBe("client");
|
||||
expect(first.subject).toBe("one-time-token");
|
||||
expect(first.label).toBe("Julius iPhone");
|
||||
expect(issued.label).toBe("Julius iPhone");
|
||||
expect(second._tag).toBe("BootstrapCredentialError");
|
||||
expect(second.message).toContain("Unknown bootstrap credential");
|
||||
}).pipe(Effect.provide(makeBootstrapCredentialLayer())),
|
||||
);
|
||||
|
||||
it.effect("atomically consumes a one-time token when multiple requests race", () =>
|
||||
Effect.gen(function* () {
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
const token = yield* bootstrapCredentials.issueOneTimeToken();
|
||||
const results = yield* Effect.all(
|
||||
Array.from({ length: 8 }, () =>
|
||||
Effect.result(bootstrapCredentials.consume(token.credential)),
|
||||
),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
);
|
||||
|
||||
const successes = results.filter((result) => result._tag === "Success");
|
||||
const failures = results.filter((result) => result._tag === "Failure");
|
||||
|
||||
expect(successes).toHaveLength(1);
|
||||
expect(failures).toHaveLength(7);
|
||||
for (const failure of failures) {
|
||||
expect(failure.failure._tag).toBe("BootstrapCredentialError");
|
||||
expect(failure.failure.message).toContain("Unknown bootstrap credential");
|
||||
}
|
||||
}).pipe(Effect.provide(makeBootstrapCredentialLayer())),
|
||||
);
|
||||
|
||||
it.effect("seeds the desktop bootstrap credential as a one-time grant", () =>
|
||||
Effect.gen(function* () {
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
const first = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
|
||||
const second = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
|
||||
|
||||
expect(first.method).toBe("desktop-bootstrap");
|
||||
expect(first.role).toBe("owner");
|
||||
expect(first.subject).toBe("desktop-bootstrap");
|
||||
expect(second._tag).toBe("BootstrapCredentialError");
|
||||
expect(second.status).toBe(401);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeBootstrapCredentialLayer({
|
||||
desktopBootstrapToken: "desktop-bootstrap-token",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reports seeded desktop bootstrap credentials as expired after their ttl", () =>
|
||||
Effect.gen(function* () {
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
|
||||
yield* TestClock.adjust(Duration.minutes(6));
|
||||
const expired = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
|
||||
|
||||
expect(expired._tag).toBe("BootstrapCredentialError");
|
||||
expect(expired.status).toBe(401);
|
||||
expect(expired.message).toContain("Bootstrap credential expired");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.merge(
|
||||
makeBootstrapCredentialLayer({
|
||||
desktopBootstrapToken: "desktop-bootstrap-token",
|
||||
}),
|
||||
TestClock.layer(),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("lists and revokes active pairing links", () =>
|
||||
Effect.gen(function* () {
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
const first = yield* bootstrapCredentials.issueOneTimeToken();
|
||||
const second = yield* bootstrapCredentials.issueOneTimeToken({ role: "owner" });
|
||||
|
||||
const activeBeforeRevoke = yield* bootstrapCredentials.listActive();
|
||||
expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(first.id);
|
||||
expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(second.id);
|
||||
|
||||
const revoked = yield* bootstrapCredentials.revoke(first.id);
|
||||
const activeAfterRevoke = yield* bootstrapCredentials.listActive();
|
||||
const revokedConsume = yield* Effect.flip(bootstrapCredentials.consume(first.credential));
|
||||
|
||||
expect(revoked).toBe(true);
|
||||
expect(activeAfterRevoke.map((entry) => entry.id)).not.toContain(first.id);
|
||||
expect(activeAfterRevoke.map((entry) => entry.id)).toContain(second.id);
|
||||
expect(revokedConsume.message).toContain("no longer available");
|
||||
expect(revokedConsume.status).toBe(401);
|
||||
}).pipe(Effect.provide(makeBootstrapCredentialLayer())),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,296 @@
|
||||
import type { AuthPairingLink } from "@t3tools/contracts";
|
||||
import { DateTime, Duration, Effect, Layer, PubSub, Ref, Stream } from "effect";
|
||||
import { Option } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { AuthPairingLinkRepositoryLive } from "../../persistence/Layers/AuthPairingLinks.ts";
|
||||
import { AuthPairingLinkRepository } from "../../persistence/Services/AuthPairingLinks.ts";
|
||||
import {
|
||||
BootstrapCredentialError,
|
||||
BootstrapCredentialService,
|
||||
type BootstrapCredentialChange,
|
||||
type BootstrapCredentialServiceShape,
|
||||
type BootstrapGrant,
|
||||
type IssuedBootstrapCredential,
|
||||
} from "../Services/BootstrapCredentialService.ts";
|
||||
|
||||
interface StoredBootstrapGrant extends BootstrapGrant {
|
||||
readonly remainingUses: number | "unbounded";
|
||||
}
|
||||
|
||||
type ConsumeResult =
|
||||
| {
|
||||
readonly _tag: "error";
|
||||
readonly reason: "not-found" | "expired";
|
||||
readonly error: BootstrapCredentialError;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "success";
|
||||
readonly grant: BootstrapGrant;
|
||||
};
|
||||
|
||||
const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
|
||||
const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
|
||||
const PAIRING_TOKEN_LENGTH = 12;
|
||||
|
||||
const generatePairingToken = (): string => {
|
||||
const randomBytes = crypto.getRandomValues(new Uint8Array(PAIRING_TOKEN_LENGTH));
|
||||
|
||||
return Array.from(randomBytes, (value) => PAIRING_TOKEN_ALPHABET[value & 31]).join("");
|
||||
};
|
||||
|
||||
export const makeBootstrapCredentialService = Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
const pairingLinks = yield* AuthPairingLinkRepository;
|
||||
const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
|
||||
const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();
|
||||
|
||||
const invalidBootstrapCredentialError = (message: string) =>
|
||||
new BootstrapCredentialError({
|
||||
message,
|
||||
status: 401,
|
||||
});
|
||||
|
||||
const internalBootstrapCredentialError = (message: string, cause: unknown) =>
|
||||
new BootstrapCredentialError({
|
||||
message,
|
||||
status: 500,
|
||||
cause,
|
||||
});
|
||||
|
||||
const seedGrant = (credential: string, grant: StoredBootstrapGrant) =>
|
||||
Ref.update(seededGrantsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
next.set(credential, grant);
|
||||
return next;
|
||||
});
|
||||
|
||||
const emitUpsert = (pairingLink: AuthPairingLink) =>
|
||||
PubSub.publish(changesPubSub, {
|
||||
type: "pairingLinkUpserted",
|
||||
pairingLink,
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const emitRemoved = (id: string) =>
|
||||
PubSub.publish(changesPubSub, {
|
||||
type: "pairingLinkRemoved",
|
||||
id,
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
if (config.desktopBootstrapToken) {
|
||||
const now = yield* DateTime.now;
|
||||
yield* seedGrant(config.desktopBootstrapToken, {
|
||||
method: "desktop-bootstrap",
|
||||
role: "owner",
|
||||
subject: "desktop-bootstrap",
|
||||
expiresAt: DateTime.add(now, {
|
||||
milliseconds: Duration.toMillis(DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES),
|
||||
}),
|
||||
remainingUses: 1,
|
||||
});
|
||||
}
|
||||
|
||||
const toBootstrapCredentialError = (message: string) => (cause: unknown) =>
|
||||
internalBootstrapCredentialError(message, cause);
|
||||
|
||||
const listActive: BootstrapCredentialServiceShape["listActive"] = () =>
|
||||
Effect.gen(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
const rows = yield* pairingLinks.listActive({ now });
|
||||
|
||||
return rows.map((row) =>
|
||||
row.label
|
||||
? ({
|
||||
id: row.id,
|
||||
credential: row.credential,
|
||||
role: row.role,
|
||||
subject: row.subject,
|
||||
label: row.label,
|
||||
createdAt: row.createdAt,
|
||||
expiresAt: row.expiresAt,
|
||||
} satisfies AuthPairingLink)
|
||||
: ({
|
||||
id: row.id,
|
||||
credential: row.credential,
|
||||
role: row.role,
|
||||
subject: row.subject,
|
||||
createdAt: row.createdAt,
|
||||
expiresAt: row.expiresAt,
|
||||
} satisfies AuthPairingLink),
|
||||
);
|
||||
}).pipe(Effect.mapError(toBootstrapCredentialError("Failed to load active pairing links.")));
|
||||
|
||||
const revoke: BootstrapCredentialServiceShape["revoke"] = (id) =>
|
||||
Effect.gen(function* () {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revoked = yield* pairingLinks.revoke({
|
||||
id,
|
||||
revokedAt,
|
||||
});
|
||||
if (revoked) {
|
||||
yield* emitRemoved(id);
|
||||
}
|
||||
return revoked;
|
||||
}).pipe(Effect.mapError(toBootstrapCredentialError("Failed to revoke pairing link.")));
|
||||
|
||||
const issueOneTimeToken: BootstrapCredentialServiceShape["issueOneTimeToken"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const id = crypto.randomUUID();
|
||||
const credential = generatePairingToken();
|
||||
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
|
||||
const issued: IssuedBootstrapCredential = {
|
||||
id,
|
||||
credential,
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
expiresAt,
|
||||
};
|
||||
yield* pairingLinks.create({
|
||||
id,
|
||||
credential,
|
||||
method: "one-time-token",
|
||||
role: input?.role ?? "client",
|
||||
subject: input?.subject ?? "one-time-token",
|
||||
label: input?.label ?? null,
|
||||
createdAt: now,
|
||||
expiresAt: expiresAt,
|
||||
});
|
||||
yield* emitUpsert({
|
||||
id,
|
||||
credential,
|
||||
role: input?.role ?? "client",
|
||||
subject: input?.subject ?? "one-time-token",
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
createdAt: now,
|
||||
expiresAt,
|
||||
});
|
||||
return issued;
|
||||
}).pipe(Effect.mapError(toBootstrapCredentialError("Failed to issue pairing credential.")));
|
||||
|
||||
const consume: BootstrapCredentialServiceShape["consume"] = (credential) =>
|
||||
Effect.gen(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
const seededResult: ConsumeResult = yield* Ref.modify(
|
||||
seededGrantsRef,
|
||||
(current): readonly [ConsumeResult, Map<string, StoredBootstrapGrant>] => {
|
||||
const grant = current.get(credential);
|
||||
if (!grant) {
|
||||
return [
|
||||
{
|
||||
_tag: "error",
|
||||
reason: "not-found",
|
||||
error: invalidBootstrapCredentialError("Unknown bootstrap credential."),
|
||||
},
|
||||
current,
|
||||
];
|
||||
}
|
||||
|
||||
const next = new Map(current);
|
||||
if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) {
|
||||
next.delete(credential);
|
||||
return [
|
||||
{
|
||||
_tag: "error",
|
||||
reason: "expired",
|
||||
error: invalidBootstrapCredentialError("Bootstrap credential expired."),
|
||||
},
|
||||
next,
|
||||
];
|
||||
}
|
||||
|
||||
const remainingUses = grant.remainingUses;
|
||||
if (typeof remainingUses === "number") {
|
||||
if (remainingUses <= 1) {
|
||||
next.delete(credential);
|
||||
} else {
|
||||
next.set(credential, {
|
||||
...grant,
|
||||
remainingUses: remainingUses - 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
_tag: "success",
|
||||
grant: {
|
||||
method: grant.method,
|
||||
role: grant.role,
|
||||
subject: grant.subject,
|
||||
...(grant.label ? { label: grant.label } : {}),
|
||||
expiresAt: grant.expiresAt,
|
||||
} satisfies BootstrapGrant,
|
||||
},
|
||||
next,
|
||||
];
|
||||
},
|
||||
);
|
||||
|
||||
if (seededResult._tag === "success") {
|
||||
return seededResult.grant;
|
||||
}
|
||||
if (seededResult.reason !== "not-found") {
|
||||
return yield* seededResult.error;
|
||||
}
|
||||
|
||||
const consumed = yield* pairingLinks.consumeAvailable({
|
||||
credential,
|
||||
consumedAt: now,
|
||||
now,
|
||||
});
|
||||
|
||||
if (Option.isSome(consumed)) {
|
||||
yield* emitRemoved(consumed.value.id);
|
||||
return {
|
||||
method: consumed.value.method,
|
||||
role: consumed.value.role,
|
||||
subject: consumed.value.subject,
|
||||
...(consumed.value.label ? { label: consumed.value.label } : {}),
|
||||
expiresAt: consumed.value.expiresAt,
|
||||
} satisfies BootstrapGrant;
|
||||
}
|
||||
|
||||
const matching = yield* pairingLinks.getByCredential({ credential });
|
||||
if (Option.isNone(matching)) {
|
||||
return yield* invalidBootstrapCredentialError("Unknown bootstrap credential.");
|
||||
}
|
||||
|
||||
if (matching.value.revokedAt !== null) {
|
||||
return yield* invalidBootstrapCredentialError(
|
||||
"Bootstrap credential is no longer available.",
|
||||
);
|
||||
}
|
||||
|
||||
if (matching.value.consumedAt !== null) {
|
||||
return yield* invalidBootstrapCredentialError("Unknown bootstrap credential.");
|
||||
}
|
||||
|
||||
if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {
|
||||
return yield* invalidBootstrapCredentialError("Bootstrap credential expired.");
|
||||
}
|
||||
|
||||
return yield* invalidBootstrapCredentialError("Bootstrap credential is no longer available.");
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause instanceof BootstrapCredentialError
|
||||
? cause
|
||||
: internalBootstrapCredentialError("Failed to consume bootstrap credential.", cause),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
issueOneTimeToken,
|
||||
listActive,
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
revoke,
|
||||
consume,
|
||||
} satisfies BootstrapCredentialServiceShape;
|
||||
});
|
||||
|
||||
export const BootstrapCredentialServiceLive = Layer.effect(
|
||||
BootstrapCredentialService,
|
||||
makeBootstrapCredentialService,
|
||||
).pipe(Layer.provideMerge(AuthPairingLinkRepositoryLive));
|
||||
@@ -0,0 +1,182 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import type { ServerConfigShape } from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts";
|
||||
import { ServerAuth, type ServerAuthShape } from "../Services/ServerAuth.ts";
|
||||
import { ServerAuthLive, toBootstrapExchangeAuthError } from "./ServerAuth.ts";
|
||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
||||
|
||||
const makeServerConfigLayer = (overrides?: Partial<ServerConfigShape>) =>
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
return {
|
||||
...config,
|
||||
...overrides,
|
||||
} satisfies ServerConfigShape;
|
||||
}),
|
||||
).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-server-test-" })));
|
||||
|
||||
const makeServerAuthLayer = (overrides?: Partial<ServerConfigShape>) =>
|
||||
ServerAuthLive.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
Layer.provide(ServerSecretStoreLive),
|
||||
Layer.provide(makeServerConfigLayer(overrides)),
|
||||
);
|
||||
|
||||
const makeCookieRequest = (
|
||||
sessionToken: string,
|
||||
): Parameters<ServerAuthShape["authenticateHttpRequest"]>[0] =>
|
||||
({
|
||||
cookies: {
|
||||
t3_session: sessionToken,
|
||||
},
|
||||
headers: {},
|
||||
}) as unknown as Parameters<ServerAuthShape["authenticateHttpRequest"]>[0];
|
||||
|
||||
const requestMetadata = {
|
||||
deviceType: "desktop" as const,
|
||||
os: "macOS",
|
||||
browser: "Chrome",
|
||||
ipAddress: "192.168.1.23",
|
||||
};
|
||||
|
||||
it.layer(NodeServices.layer)("ServerAuthLive", (it) => {
|
||||
it.effect("maps invalid bootstrap credential failures to 401", () =>
|
||||
Effect.sync(() => {
|
||||
const error = toBootstrapExchangeAuthError(
|
||||
new BootstrapCredentialError({
|
||||
message: "Unknown bootstrap credential.",
|
||||
status: 401,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error.status).toBe(401);
|
||||
expect(error.message).toBe("Invalid bootstrap credential.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps unexpected bootstrap failures to 500", () =>
|
||||
Effect.sync(() => {
|
||||
const error = toBootstrapExchangeAuthError(
|
||||
new BootstrapCredentialError({
|
||||
message: "Failed to consume bootstrap credential.",
|
||||
status: 500,
|
||||
cause: new Error("sqlite is unavailable"),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error.status).toBe(500);
|
||||
expect(error.message).toBe("Failed to validate bootstrap credential.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("issues client pairing credentials by default", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverAuth = yield* ServerAuth;
|
||||
|
||||
const pairingCredential = yield* serverAuth.issuePairingCredential();
|
||||
const exchanged = yield* serverAuth.exchangeBootstrapCredential(
|
||||
pairingCredential.credential,
|
||||
requestMetadata,
|
||||
);
|
||||
const verified = yield* serverAuth.authenticateHttpRequest(
|
||||
makeCookieRequest(exchanged.sessionToken),
|
||||
);
|
||||
|
||||
expect(verified.sessionId.length).toBeGreaterThan(0);
|
||||
expect(verified.role).toBe("client");
|
||||
expect(verified.subject).toBe("one-time-token");
|
||||
}).pipe(Effect.provide(makeServerAuthLayer())),
|
||||
);
|
||||
|
||||
it.effect("issues startup pairing URLs that bootstrap owner sessions", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverAuth = yield* ServerAuth;
|
||||
|
||||
const pairingUrl = yield* serverAuth.issueStartupPairingUrl("http://127.0.0.1:3773");
|
||||
const token = new URLSearchParams(new URL(pairingUrl).hash.slice(1)).get("token");
|
||||
const listedPairingLinks = yield* serverAuth.listPairingLinks();
|
||||
expect(token).toBeTruthy();
|
||||
expect(
|
||||
listedPairingLinks.some((pairingLink) => pairingLink.subject === "owner-bootstrap"),
|
||||
).toBe(false);
|
||||
|
||||
const exchanged = yield* serverAuth.exchangeBootstrapCredential(token ?? "", requestMetadata);
|
||||
const verified = yield* serverAuth.authenticateHttpRequest(
|
||||
makeCookieRequest(exchanged.sessionToken),
|
||||
);
|
||||
|
||||
expect(verified.role).toBe("owner");
|
||||
expect(verified.subject).toBe("owner-bootstrap");
|
||||
}).pipe(Effect.provide(makeServerAuthLayer())),
|
||||
);
|
||||
|
||||
it.effect("lists pairing links and revokes other client sessions while keeping the owner", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverAuth = yield* ServerAuth;
|
||||
|
||||
const ownerExchange = yield* serverAuth.exchangeBootstrapCredential(
|
||||
"desktop-bootstrap-token",
|
||||
requestMetadata,
|
||||
);
|
||||
const ownerSession = yield* serverAuth.authenticateHttpRequest(
|
||||
makeCookieRequest(ownerExchange.sessionToken),
|
||||
);
|
||||
const pairingCredential = yield* serverAuth.issuePairingCredential({
|
||||
label: "Julius iPhone",
|
||||
});
|
||||
const listedPairingLinks = yield* serverAuth.listPairingLinks();
|
||||
const clientExchange = yield* serverAuth.exchangeBootstrapCredential(
|
||||
pairingCredential.credential,
|
||||
{
|
||||
...requestMetadata,
|
||||
deviceType: "mobile",
|
||||
os: "iOS",
|
||||
browser: "Safari",
|
||||
ipAddress: "192.168.1.88",
|
||||
},
|
||||
);
|
||||
const clientSession = yield* serverAuth.authenticateHttpRequest(
|
||||
makeCookieRequest(clientExchange.sessionToken),
|
||||
);
|
||||
const clientsBeforeRevoke = yield* serverAuth.listClientSessions(ownerSession.sessionId);
|
||||
const revokedCount = yield* serverAuth.revokeOtherClientSessions(ownerSession.sessionId);
|
||||
const clientsAfterRevoke = yield* serverAuth.listClientSessions(ownerSession.sessionId);
|
||||
|
||||
expect(listedPairingLinks.map((entry) => entry.id)).toContain(pairingCredential.id);
|
||||
expect(listedPairingLinks.find((entry) => entry.id === pairingCredential.id)?.label).toBe(
|
||||
"Julius iPhone",
|
||||
);
|
||||
expect(clientsBeforeRevoke).toHaveLength(2);
|
||||
expect(
|
||||
clientsBeforeRevoke.find((entry) => entry.sessionId === ownerSession.sessionId)?.current,
|
||||
).toBe(true);
|
||||
expect(
|
||||
clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.current,
|
||||
).toBe(false);
|
||||
expect(
|
||||
clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client
|
||||
.label,
|
||||
).toBe("Julius iPhone");
|
||||
expect(
|
||||
clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client
|
||||
.deviceType,
|
||||
).toBe("mobile");
|
||||
expect(revokedCount).toBe(1);
|
||||
expect(clientsAfterRevoke).toHaveLength(1);
|
||||
expect(clientsAfterRevoke[0]?.sessionId).toBe(ownerSession.sessionId);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthLayer({
|
||||
desktopBootstrapToken: "desktop-bootstrap-token",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,395 @@
|
||||
import {
|
||||
type AuthBearerBootstrapResult,
|
||||
type AuthClientSession,
|
||||
type AuthBootstrapResult,
|
||||
type AuthPairingCredentialResult,
|
||||
type AuthSessionState,
|
||||
type AuthWebSocketTokenResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { DateTime, Effect, Layer, Option } from "effect";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
|
||||
import { AuthControlPlane } from "../Services/AuthControlPlane.ts";
|
||||
import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts";
|
||||
import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
|
||||
import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts";
|
||||
import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts";
|
||||
import {
|
||||
ServerAuth,
|
||||
type AuthenticatedSession,
|
||||
AuthError,
|
||||
type ServerAuthShape,
|
||||
} from "../Services/ServerAuth.ts";
|
||||
import {
|
||||
SessionCredentialError,
|
||||
SessionCredentialService,
|
||||
} from "../Services/SessionCredentialService.ts";
|
||||
import { AuthControlPlaneLive, AuthCoreLive } from "./AuthControlPlane.ts";
|
||||
|
||||
type BootstrapExchangeResult = {
|
||||
readonly response: AuthBootstrapResult;
|
||||
readonly sessionToken: string;
|
||||
};
|
||||
|
||||
const AUTHORIZATION_PREFIX = "Bearer ";
|
||||
const WEBSOCKET_TOKEN_QUERY_PARAM = "wsToken";
|
||||
|
||||
export function toBootstrapExchangeAuthError(cause: BootstrapCredentialError): AuthError {
|
||||
if (cause.status === 500) {
|
||||
return new AuthError({
|
||||
message: "Failed to validate bootstrap credential.",
|
||||
status: 500,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
return new AuthError({
|
||||
message: "Invalid bootstrap credential.",
|
||||
status: 401,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {
|
||||
const header = request.headers["authorization"];
|
||||
if (typeof header !== "string" || !header.startsWith(AUTHORIZATION_PREFIX)) {
|
||||
return null;
|
||||
}
|
||||
const token = header.slice(AUTHORIZATION_PREFIX.length).trim();
|
||||
return token.length > 0 ? token : null;
|
||||
}
|
||||
|
||||
export const makeServerAuth = Effect.gen(function* () {
|
||||
const policy = yield* ServerAuthPolicy;
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
const authControlPlane = yield* AuthControlPlane;
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
const authenticateToken = (token: string): Effect.Effect<AuthenticatedSession, AuthError> =>
|
||||
sessions.verify(token).pipe(
|
||||
Effect.tapError((cause: SessionCredentialError) =>
|
||||
Effect.logWarning("Rejected authenticated session credential.").pipe(
|
||||
Effect.annotateLogs({
|
||||
reason: cause.message,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.map((session) => ({
|
||||
sessionId: session.sessionId,
|
||||
subject: session.subject,
|
||||
method: session.method,
|
||||
role: session.role,
|
||||
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
|
||||
})),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Unauthorized request.",
|
||||
status: 401,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const authenticateRequest = (request: HttpServerRequest.HttpServerRequest) => {
|
||||
const cookieToken = request.cookies[sessions.cookieName];
|
||||
const bearerToken = parseBearerToken(request);
|
||||
const credential = cookieToken ?? bearerToken;
|
||||
if (!credential) {
|
||||
return Effect.fail(
|
||||
new AuthError({
|
||||
message: "Authentication required.",
|
||||
status: 401,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return authenticateToken(credential);
|
||||
};
|
||||
|
||||
const getSessionState: ServerAuthShape["getSessionState"] = (request) =>
|
||||
authenticateRequest(request).pipe(
|
||||
Effect.map(
|
||||
(session) =>
|
||||
({
|
||||
authenticated: true,
|
||||
auth: descriptor,
|
||||
role: session.role,
|
||||
sessionMethod: session.method,
|
||||
...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
|
||||
}) satisfies AuthSessionState,
|
||||
),
|
||||
Effect.catchTag("AuthError", () =>
|
||||
Effect.succeed({
|
||||
authenticated: false,
|
||||
auth: descriptor,
|
||||
} satisfies AuthSessionState),
|
||||
),
|
||||
);
|
||||
|
||||
const exchangeBootstrapCredential: ServerAuthShape["exchangeBootstrapCredential"] = (
|
||||
credential,
|
||||
requestMetadata,
|
||||
) =>
|
||||
bootstrapCredentials.consume(credential).pipe(
|
||||
Effect.mapError(toBootstrapExchangeAuthError),
|
||||
Effect.flatMap((grant) =>
|
||||
sessions
|
||||
.issue({
|
||||
method: "browser-session-cookie",
|
||||
subject: grant.subject,
|
||||
role: grant.role,
|
||||
client: {
|
||||
...requestMetadata,
|
||||
...(grant.label ? { label: grant.label } : {}),
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to issue authenticated session.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map(
|
||||
(session) =>
|
||||
({
|
||||
response: {
|
||||
authenticated: true,
|
||||
role: session.role,
|
||||
sessionMethod: session.method,
|
||||
expiresAt: DateTime.toUtc(session.expiresAt),
|
||||
} satisfies AuthBootstrapResult,
|
||||
sessionToken: session.token,
|
||||
}) satisfies BootstrapExchangeResult,
|
||||
),
|
||||
);
|
||||
|
||||
const exchangeBootstrapCredentialForBearerSession: ServerAuthShape["exchangeBootstrapCredentialForBearerSession"] =
|
||||
(credential, requestMetadata) =>
|
||||
bootstrapCredentials.consume(credential).pipe(
|
||||
Effect.mapError(toBootstrapExchangeAuthError),
|
||||
Effect.flatMap((grant) =>
|
||||
sessions
|
||||
.issue({
|
||||
method: "bearer-session-token",
|
||||
subject: grant.subject,
|
||||
role: grant.role,
|
||||
client: {
|
||||
...requestMetadata,
|
||||
...(grant.label ? { label: grant.label } : {}),
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to issue authenticated session.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map(
|
||||
(session) =>
|
||||
({
|
||||
authenticated: true,
|
||||
role: session.role,
|
||||
sessionMethod: "bearer-session-token",
|
||||
expiresAt: DateTime.toUtc(session.expiresAt),
|
||||
sessionToken: session.token,
|
||||
}) satisfies AuthBearerBootstrapResult,
|
||||
),
|
||||
);
|
||||
|
||||
const issuePairingCredential: ServerAuthShape["issuePairingCredential"] = (input) =>
|
||||
authControlPlane
|
||||
.createPairingLink({
|
||||
role: input?.role ?? "client",
|
||||
subject: input?.role === "owner" ? "owner-bootstrap" : "one-time-token",
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to issue pairing credential.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.map(
|
||||
(issued) =>
|
||||
({
|
||||
id: issued.id,
|
||||
credential: issued.credential,
|
||||
...(issued.label ? { label: issued.label } : {}),
|
||||
expiresAt: issued.expiresAt,
|
||||
}) satisfies AuthPairingCredentialResult,
|
||||
),
|
||||
);
|
||||
|
||||
const listPairingLinks: ServerAuthShape["listPairingLinks"] = () =>
|
||||
authControlPlane
|
||||
.listPairingLinks({
|
||||
role: "client",
|
||||
excludeSubjects: ["owner-bootstrap"],
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to load pairing links.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const revokePairingLink: ServerAuthShape["revokePairingLink"] = (id) =>
|
||||
authControlPlane.revokePairingLink(id).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to revoke pairing link.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const listClientSessions: ServerAuthShape["listClientSessions"] = (currentSessionId) =>
|
||||
authControlPlane.listSessions().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to load paired clients.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.map((clientSessions) =>
|
||||
clientSessions.map(
|
||||
(clientSession): AuthClientSession => ({
|
||||
...clientSession,
|
||||
current: clientSession.sessionId === currentSessionId,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const revokeClientSession: ServerAuthShape["revokeClientSession"] = (
|
||||
currentSessionId,
|
||||
targetSessionId,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
if (currentSessionId === targetSessionId) {
|
||||
return yield* new AuthError({
|
||||
message: "Use revoke other clients to keep the current owner session active.",
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
return yield* authControlPlane.revokeSession(targetSessionId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to revoke client session.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const revokeOtherClientSessions: ServerAuthShape["revokeOtherClientSessions"] = (
|
||||
currentSessionId,
|
||||
) =>
|
||||
authControlPlane.revokeOtherSessionsExcept(currentSessionId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to revoke other client sessions.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const issueStartupPairingUrl: ServerAuthShape["issueStartupPairingUrl"] = (baseUrl) =>
|
||||
issuePairingCredential({ role: "owner" }).pipe(
|
||||
Effect.map((issued) => {
|
||||
const url = new URL(baseUrl);
|
||||
url.pathname = "/pair";
|
||||
url.searchParams.delete("token");
|
||||
url.hash = new URLSearchParams([["token", issued.credential]]).toString();
|
||||
return url.toString();
|
||||
}),
|
||||
);
|
||||
|
||||
const issueWebSocketToken: ServerAuthShape["issueWebSocketToken"] = (session) =>
|
||||
sessions.issueWebSocketToken(session.sessionId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to issue websocket token.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.map(
|
||||
(issued) =>
|
||||
({
|
||||
token: issued.token,
|
||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
||||
}) satisfies AuthWebSocketTokenResult,
|
||||
),
|
||||
);
|
||||
|
||||
const authenticateWebSocketUpgrade: ServerAuthShape["authenticateWebSocketUpgrade"] = (request) =>
|
||||
Effect.gen(function* () {
|
||||
const requestUrl = HttpServerRequest.toURL(request);
|
||||
if (Option.isSome(requestUrl)) {
|
||||
const websocketToken = requestUrl.value.searchParams.get(WEBSOCKET_TOKEN_QUERY_PARAM);
|
||||
if (websocketToken && websocketToken.trim().length > 0) {
|
||||
return yield* sessions.verifyWebSocketToken(websocketToken).pipe(
|
||||
Effect.map((session) => ({
|
||||
sessionId: session.sessionId,
|
||||
subject: session.subject,
|
||||
method: session.method,
|
||||
role: session.role,
|
||||
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
|
||||
})),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Unauthorized request.",
|
||||
status: 401,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return yield* authenticateRequest(request);
|
||||
});
|
||||
|
||||
return {
|
||||
getDescriptor: () => Effect.succeed(descriptor),
|
||||
getSessionState,
|
||||
exchangeBootstrapCredential,
|
||||
exchangeBootstrapCredentialForBearerSession,
|
||||
issuePairingCredential,
|
||||
listPairingLinks,
|
||||
revokePairingLink,
|
||||
listClientSessions,
|
||||
revokeClientSession,
|
||||
revokeOtherClientSessions,
|
||||
authenticateHttpRequest: authenticateRequest,
|
||||
authenticateWebSocketUpgrade,
|
||||
issueWebSocketToken,
|
||||
issueStartupPairingUrl,
|
||||
} satisfies ServerAuthShape;
|
||||
});
|
||||
|
||||
export const ServerAuthLive = Layer.effect(ServerAuth, makeServerAuth).pipe(
|
||||
Layer.provideMerge(AuthControlPlaneLive),
|
||||
Layer.provideMerge(AuthCoreLive),
|
||||
Layer.provideMerge(ServerAuthPolicyLive),
|
||||
);
|
||||
@@ -0,0 +1,114 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import type { ServerConfigShape } from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts";
|
||||
import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts";
|
||||
|
||||
const makeServerAuthPolicyLayer = (overrides?: Partial<ServerConfigShape>) =>
|
||||
ServerAuthPolicyLive.pipe(
|
||||
Layer.provide(
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
return {
|
||||
...config,
|
||||
...overrides,
|
||||
} satisfies ServerConfigShape;
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-policy-test-" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {
|
||||
it.effect("uses desktop-managed-local policy for desktop mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* ServerAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.policy).toBe("desktop-managed-local");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]);
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session_3773");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
mode: "desktop",
|
||||
port: 3773,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses remote-reachable policy for desktop mode when bound beyond loopback", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* ServerAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.policy).toBe("remote-reachable");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap", "one-time-token"]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
mode: "desktop",
|
||||
host: "0.0.0.0",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses loopback-browser policy for loopback web hosts", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* ServerAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.policy).toBe("loopback-browser");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
mode: "web",
|
||||
host: "127.0.0.1",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses remote-reachable policy for wildcard web hosts", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* ServerAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.policy).toBe("remote-reachable");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
mode: "web",
|
||||
host: "0.0.0.0",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses remote-reachable policy for non-loopback web hosts", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* ServerAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.policy).toBe("remote-reachable");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
mode: "web",
|
||||
host: "192.168.1.50",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { ServerAuthDescriptor } from "@t3tools/contracts";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerAuthPolicy, type ServerAuthPolicyShape } from "../Services/ServerAuthPolicy.ts";
|
||||
import { resolveSessionCookieName } from "../utils.ts";
|
||||
import { isLoopbackHost, isWildcardHost } from "../../startupAccess.ts";
|
||||
|
||||
export const makeServerAuthPolicy = Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
const isRemoteReachable = isWildcardHost(config.host) || !isLoopbackHost(config.host);
|
||||
|
||||
const policy =
|
||||
config.mode === "desktop"
|
||||
? isRemoteReachable
|
||||
? "remote-reachable"
|
||||
: "desktop-managed-local"
|
||||
: isRemoteReachable
|
||||
? "remote-reachable"
|
||||
: "loopback-browser";
|
||||
|
||||
const bootstrapMethods: ServerAuthDescriptor["bootstrapMethods"] =
|
||||
policy === "desktop-managed-local"
|
||||
? ["desktop-bootstrap"]
|
||||
: config.mode === "desktop" && policy === "remote-reachable"
|
||||
? ["desktop-bootstrap", "one-time-token"]
|
||||
: ["one-time-token"];
|
||||
|
||||
const descriptor: ServerAuthDescriptor = {
|
||||
policy,
|
||||
bootstrapMethods,
|
||||
sessionMethods: ["browser-session-cookie", "bearer-session-token"],
|
||||
sessionCookieName: resolveSessionCookieName({
|
||||
mode: config.mode,
|
||||
port: config.port,
|
||||
}),
|
||||
};
|
||||
|
||||
return {
|
||||
getDescriptor: () => Effect.succeed(descriptor),
|
||||
} satisfies ServerAuthPolicyShape;
|
||||
});
|
||||
|
||||
export const ServerAuthPolicyLive = Layer.effect(ServerAuthPolicy, makeServerAuthPolicy);
|
||||
@@ -0,0 +1,263 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Cause, Deferred, Effect, FileSystem, Layer, Ref } from "effect";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { SecretStoreError, ServerSecretStore } from "../Services/ServerSecretStore.ts";
|
||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
||||
|
||||
const makeServerConfigLayer = () =>
|
||||
ServerConfig.layerTest(process.cwd(), { prefix: "t3-secret-store-test-" });
|
||||
|
||||
const makeServerSecretStoreLayer = () =>
|
||||
Layer.provide(ServerSecretStoreLive, makeServerConfigLayer());
|
||||
|
||||
const PermissionDeniedFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
return {
|
||||
...fileSystem,
|
||||
readFile: (path) =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFile",
|
||||
pathOrDescriptor: path,
|
||||
description: "Permission denied while reading secret file.",
|
||||
}),
|
||||
),
|
||||
} satisfies FileSystem.FileSystem;
|
||||
}),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const makePermissionDeniedSecretStoreLayer = () =>
|
||||
ServerSecretStoreLive.pipe(
|
||||
Layer.provide(makeServerConfigLayer()),
|
||||
Layer.provideMerge(PermissionDeniedFileSystemLayer),
|
||||
);
|
||||
|
||||
const RenameFailureFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
return {
|
||||
...fileSystem,
|
||||
rename: (from, to) =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "rename",
|
||||
pathOrDescriptor: `${String(from)} -> ${String(to)}`,
|
||||
description: "Permission denied while persisting secret file.",
|
||||
}),
|
||||
),
|
||||
} satisfies FileSystem.FileSystem;
|
||||
}),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const makeRenameFailureSecretStoreLayer = () =>
|
||||
ServerSecretStoreLive.pipe(
|
||||
Layer.provide(makeServerConfigLayer()),
|
||||
Layer.provideMerge(RenameFailureFileSystemLayer),
|
||||
);
|
||||
|
||||
const RemoveFailureFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
return {
|
||||
...fileSystem,
|
||||
remove: (path, options) =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "remove",
|
||||
pathOrDescriptor: String(path),
|
||||
description: `Permission denied while removing secret file.${options ? " options-set" : ""}`,
|
||||
}),
|
||||
),
|
||||
} satisfies FileSystem.FileSystem;
|
||||
}),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const makeRemoveFailureSecretStoreLayer = () =>
|
||||
ServerSecretStoreLive.pipe(
|
||||
Layer.provide(makeServerConfigLayer()),
|
||||
Layer.provideMerge(RemoveFailureFileSystemLayer),
|
||||
);
|
||||
|
||||
const ConcurrentReadMissFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const readCountRef = yield* Ref.make(0);
|
||||
const readBarrier = yield* Deferred.make<void>();
|
||||
|
||||
return {
|
||||
...fileSystem,
|
||||
readFile: (path) =>
|
||||
String(path).endsWith("/session-signing-key.bin")
|
||||
? Ref.updateAndGet(readCountRef, (count) => count + 1).pipe(
|
||||
Effect.flatMap((count) => {
|
||||
if (count > 2) {
|
||||
return fileSystem.readFile(path);
|
||||
}
|
||||
return Effect.gen(function* () {
|
||||
if (count === 2) {
|
||||
yield* Deferred.succeed(readBarrier, void 0);
|
||||
}
|
||||
yield* Deferred.await(readBarrier);
|
||||
return yield* Effect.failCause(
|
||||
Cause.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "FileSystem",
|
||||
method: "readFile",
|
||||
pathOrDescriptor: String(path),
|
||||
description: "Secret file does not exist yet.",
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
}),
|
||||
)
|
||||
: fileSystem.readFile(path),
|
||||
} satisfies FileSystem.FileSystem;
|
||||
}),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const makeConcurrentCreateSecretStoreLayer = () =>
|
||||
ServerSecretStoreLive.pipe(
|
||||
Layer.provide(makeServerConfigLayer()),
|
||||
Layer.provideMerge(ConcurrentReadMissFileSystemLayer),
|
||||
);
|
||||
|
||||
it.layer(NodeServices.layer)("ServerSecretStoreLive", (it) => {
|
||||
it.effect("returns null when a secret file does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
|
||||
const secret = yield* secretStore.get("missing-secret");
|
||||
|
||||
expect(secret).toBeNull();
|
||||
}).pipe(Effect.provide(makeServerSecretStoreLayer())),
|
||||
);
|
||||
|
||||
it.effect("reuses an existing secret instead of regenerating it", () =>
|
||||
Effect.gen(function* () {
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
|
||||
const first = yield* secretStore.getOrCreateRandom("session-signing-key", 32);
|
||||
const second = yield* secretStore.getOrCreateRandom("session-signing-key", 32);
|
||||
|
||||
expect(Array.from(second)).toEqual(Array.from(first));
|
||||
}).pipe(Effect.provide(makeServerSecretStoreLayer())),
|
||||
);
|
||||
|
||||
it.effect("returns the persisted secret when concurrent creators race", () =>
|
||||
Effect.gen(function* () {
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
|
||||
const [first, second] = yield* Effect.all(
|
||||
[
|
||||
secretStore.getOrCreateRandom("session-signing-key", 32),
|
||||
secretStore.getOrCreateRandom("session-signing-key", 32),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const persisted = yield* secretStore.get("session-signing-key");
|
||||
|
||||
expect(persisted).not.toBeNull();
|
||||
expect(Array.from(first)).toEqual(Array.from(persisted ?? new Uint8Array()));
|
||||
expect(Array.from(second)).toEqual(Array.from(persisted ?? new Uint8Array()));
|
||||
}).pipe(Effect.provide(makeConcurrentCreateSecretStoreLayer())),
|
||||
);
|
||||
|
||||
it.effect("uses restrictive permissions for the secret directory and files", () =>
|
||||
Effect.gen(function* () {
|
||||
const chmodCalls: Array<{ readonly path: string; readonly mode: number }> = [];
|
||||
const recordingFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
return {
|
||||
...fileSystem,
|
||||
makeDirectory: () => Effect.void,
|
||||
writeFile: () => Effect.void,
|
||||
rename: () => Effect.void,
|
||||
chmod: (path, mode) =>
|
||||
Effect.sync(() => {
|
||||
chmodCalls.push({ path: String(path), mode });
|
||||
}),
|
||||
} satisfies FileSystem.FileSystem;
|
||||
}),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const secretStore = yield* Effect.service(ServerSecretStore).pipe(
|
||||
Effect.provide(
|
||||
ServerSecretStoreLive.pipe(
|
||||
Layer.provide(makeServerConfigLayer()),
|
||||
Layer.provideMerge(recordingFileSystemLayer),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3]));
|
||||
|
||||
expect(chmodCalls.some((call) => call.mode === 0o700 && call.path.endsWith("/secrets"))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(chmodCalls.filter((call) => call.mode === 0o600).length).toBeGreaterThanOrEqual(2);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("propagates read failures other than missing-file errors", () =>
|
||||
Effect.gen(function* () {
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
|
||||
const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32));
|
||||
|
||||
expect(error).toBeInstanceOf(SecretStoreError);
|
||||
expect(error.message).toContain("Failed to read secret session-signing-key.");
|
||||
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
|
||||
expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
|
||||
}).pipe(Effect.provide(makePermissionDeniedSecretStoreLayer())),
|
||||
);
|
||||
|
||||
it.effect("propagates write failures instead of treating them as success", () =>
|
||||
Effect.gen(function* () {
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3])),
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(SecretStoreError);
|
||||
expect(error.message).toContain("Failed to persist secret session-signing-key.");
|
||||
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
|
||||
expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
|
||||
}).pipe(Effect.provide(makeRenameFailureSecretStoreLayer())),
|
||||
);
|
||||
|
||||
it.effect("propagates remove failures other than missing-file errors", () =>
|
||||
Effect.gen(function* () {
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
|
||||
const error = yield* Effect.flip(secretStore.remove("session-signing-key"));
|
||||
|
||||
expect(error).toBeInstanceOf(SecretStoreError);
|
||||
expect(error.message).toContain("Failed to remove secret session-signing-key.");
|
||||
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
|
||||
expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
|
||||
}).pipe(Effect.provide(makeRemoveFailureSecretStoreLayer())),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
import * as Crypto from "node:crypto";
|
||||
|
||||
import { Effect, FileSystem, Layer, Path, Predicate } from "effect";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import {
|
||||
SecretStoreError,
|
||||
ServerSecretStore,
|
||||
type ServerSecretStoreShape,
|
||||
} from "../Services/ServerSecretStore.ts";
|
||||
|
||||
export const makeServerSecretStore = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
|
||||
yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });
|
||||
yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreError({
|
||||
message: `Failed to secure secrets directory ${serverConfig.secretsDir}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
|
||||
|
||||
const isPlatformError = (u: unknown): u is PlatformError.PlatformError =>
|
||||
Predicate.isTagged(u, "PlatformError");
|
||||
|
||||
const get: ServerSecretStoreShape["get"] = (name) =>
|
||||
fileSystem.readFile(resolveSecretPath(name)).pipe(
|
||||
Effect.map((bytes) => Uint8Array.from(bytes)),
|
||||
Effect.catch((cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.succeed(null)
|
||||
: Effect.fail(
|
||||
new SecretStoreError({
|
||||
message: `Failed to read secret ${name}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const set: ServerSecretStoreShape["set"] = (name, value) => {
|
||||
const secretPath = resolveSecretPath(name);
|
||||
const tempPath = `${secretPath}.${Crypto.randomUUID()}.tmp`;
|
||||
return Effect.gen(function* () {
|
||||
yield* fileSystem.writeFile(tempPath, value);
|
||||
yield* fileSystem.chmod(tempPath, 0o600);
|
||||
yield* fileSystem.rename(tempPath, secretPath);
|
||||
yield* fileSystem.chmod(secretPath, 0o600);
|
||||
}).pipe(
|
||||
Effect.catch((cause) =>
|
||||
fileSystem.remove(tempPath).pipe(
|
||||
Effect.ignore,
|
||||
Effect.flatMap(() =>
|
||||
Effect.fail(
|
||||
new SecretStoreError({
|
||||
message: `Failed to persist secret ${name}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const create: ServerSecretStoreShape["set"] = (name, value) => {
|
||||
const secretPath = resolveSecretPath(name);
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const file = yield* fileSystem.open(secretPath, {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
yield* file.writeAll(value);
|
||||
yield* file.sync;
|
||||
yield* fileSystem.chmod(secretPath, 0o600);
|
||||
}),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreError({
|
||||
message: `Failed to persist secret ${name}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const getOrCreateRandom: ServerSecretStoreShape["getOrCreateRandom"] = (name, bytes) =>
|
||||
get(name).pipe(
|
||||
Effect.flatMap((existing) => {
|
||||
if (existing) {
|
||||
return Effect.succeed(existing);
|
||||
}
|
||||
|
||||
const generated = Crypto.randomBytes(bytes);
|
||||
return create(name, generated).pipe(
|
||||
Effect.as(Uint8Array.from(generated)),
|
||||
Effect.catchTag("SecretStoreError", (error) =>
|
||||
isPlatformError(error.cause) && error.cause.reason._tag === "AlreadyExists"
|
||||
? get(name).pipe(
|
||||
Effect.flatMap((created) =>
|
||||
created !== null
|
||||
? Effect.succeed(created)
|
||||
: Effect.fail(
|
||||
new SecretStoreError({
|
||||
message: `Failed to read secret ${name} after concurrent creation.`,
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
: Effect.fail(error),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const remove: ServerSecretStoreShape["remove"] = (name) =>
|
||||
fileSystem.remove(resolveSecretPath(name)).pipe(
|
||||
Effect.catch((cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new SecretStoreError({
|
||||
message: `Failed to remove secret ${name}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
get,
|
||||
set,
|
||||
getOrCreateRandom,
|
||||
remove,
|
||||
} satisfies ServerSecretStoreShape;
|
||||
});
|
||||
|
||||
export const ServerSecretStoreLive = Layer.effect(ServerSecretStore, makeServerSecretStore);
|
||||
@@ -0,0 +1,191 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Duration, Effect, Layer } from "effect";
|
||||
import { TestClock } from "effect/testing";
|
||||
|
||||
import type { ServerConfigShape } from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
|
||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
||||
import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
|
||||
|
||||
const makeServerConfigLayer = (
|
||||
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
||||
) =>
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
return {
|
||||
...config,
|
||||
...overrides,
|
||||
} satisfies ServerConfigShape;
|
||||
}),
|
||||
).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-session-test-" })));
|
||||
|
||||
const makeSessionCredentialLayer = (
|
||||
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
||||
) =>
|
||||
SessionCredentialServiceLive.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
Layer.provide(ServerSecretStoreLive),
|
||||
Layer.provide(makeServerConfigLayer(overrides)),
|
||||
);
|
||||
|
||||
it.layer(NodeServices.layer)("SessionCredentialServiceLive", (it) => {
|
||||
it.effect("issues and verifies signed browser session tokens", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const issued = yield* sessions.issue({
|
||||
subject: "desktop-bootstrap",
|
||||
role: "owner",
|
||||
client: {
|
||||
label: "Desktop app",
|
||||
deviceType: "desktop",
|
||||
os: "macOS",
|
||||
browser: "Electron",
|
||||
ipAddress: "127.0.0.1",
|
||||
},
|
||||
});
|
||||
const verified = yield* sessions.verify(issued.token);
|
||||
|
||||
expect(verified.method).toBe("browser-session-cookie");
|
||||
expect(verified.subject).toBe("desktop-bootstrap");
|
||||
expect(verified.role).toBe("owner");
|
||||
expect(verified.client.label).toBe("Desktop app");
|
||||
expect(verified.client.browser).toBe("Electron");
|
||||
expect(verified.expiresAt?.toString()).toBe(issued.expiresAt.toString());
|
||||
}).pipe(Effect.provide(makeSessionCredentialLayer())),
|
||||
);
|
||||
it.effect("rejects malformed session tokens", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const error = yield* Effect.flip(sessions.verify("not-a-session-token"));
|
||||
|
||||
expect(error._tag).toBe("SessionCredentialError");
|
||||
expect(error.message).toContain("Malformed session token");
|
||||
}).pipe(Effect.provide(makeSessionCredentialLayer())),
|
||||
);
|
||||
it.effect("verifies session tokens against the Effect clock", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const issued = yield* sessions.issue({
|
||||
method: "bearer-session-token",
|
||||
subject: "test-clock",
|
||||
});
|
||||
const verified = yield* sessions.verify(issued.token);
|
||||
|
||||
expect(verified.method).toBe("bearer-session-token");
|
||||
expect(verified.subject).toBe("test-clock");
|
||||
expect(verified.role).toBe("client");
|
||||
}).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))),
|
||||
);
|
||||
|
||||
it.effect("rejects websocket tokens once the parent session has expired", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const issued = yield* sessions.issue({
|
||||
method: "bearer-session-token",
|
||||
subject: "short-lived",
|
||||
ttl: Duration.seconds(1),
|
||||
});
|
||||
const websocket = yield* sessions.issueWebSocketToken(issued.sessionId);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(2));
|
||||
|
||||
const error = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
|
||||
expect(error.message).toContain("expired");
|
||||
}).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))),
|
||||
);
|
||||
|
||||
it.effect("lists active sessions, tracks connectivity, and revokes other sessions", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const owner = yield* sessions.issue({
|
||||
subject: "desktop-bootstrap",
|
||||
role: "owner",
|
||||
client: {
|
||||
label: "Desktop app",
|
||||
deviceType: "desktop",
|
||||
os: "macOS",
|
||||
browser: "Electron",
|
||||
},
|
||||
});
|
||||
const client = yield* sessions.issue({
|
||||
subject: "one-time-token",
|
||||
role: "client",
|
||||
client: {
|
||||
label: "Julius iPhone",
|
||||
deviceType: "mobile",
|
||||
os: "iOS",
|
||||
browser: "Safari",
|
||||
ipAddress: "192.168.1.88",
|
||||
},
|
||||
});
|
||||
|
||||
yield* sessions.markConnected(client.sessionId);
|
||||
const beforeRevoke = yield* sessions.listActive();
|
||||
const revokedCount = yield* sessions.revokeAllExcept(owner.sessionId);
|
||||
const afterRevoke = yield* sessions.listActive();
|
||||
const revokedClient = yield* Effect.flip(sessions.verify(client.token));
|
||||
|
||||
expect(beforeRevoke).toHaveLength(2);
|
||||
expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.connected).toBe(
|
||||
true,
|
||||
);
|
||||
expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.client.label).toBe(
|
||||
"Julius iPhone",
|
||||
);
|
||||
expect(
|
||||
beforeRevoke.find((entry) => entry.sessionId === owner.sessionId)?.client.deviceType,
|
||||
).toBe("desktop");
|
||||
expect(revokedCount).toBe(1);
|
||||
expect(afterRevoke).toHaveLength(1);
|
||||
expect(afterRevoke[0]?.sessionId).toBe(owner.sessionId);
|
||||
expect(revokedClient.message).toContain("revoked");
|
||||
}).pipe(Effect.provide(makeSessionCredentialLayer())),
|
||||
);
|
||||
|
||||
it.effect("persists lastConnectedAt on first connect and updates it after reconnect", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const issued = yield* sessions.issue({
|
||||
subject: "reconnect-test",
|
||||
method: "bearer-session-token",
|
||||
});
|
||||
|
||||
const beforeConnect = yield* sessions.listActive();
|
||||
expect(beforeConnect[0]?.lastConnectedAt).toBeNull();
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
yield* sessions.markConnected(issued.sessionId);
|
||||
const firstConnect = yield* sessions.listActive();
|
||||
const firstConnectedAt = firstConnect[0]?.lastConnectedAt;
|
||||
|
||||
expect(firstConnect[0]?.connected).toBe(true);
|
||||
expect(firstConnectedAt).not.toBeNull();
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
yield* sessions.markConnected(issued.sessionId);
|
||||
const stillConnected = yield* sessions.listActive();
|
||||
|
||||
expect(stillConnected[0]?.lastConnectedAt?.toString()).toBe(firstConnectedAt?.toString());
|
||||
|
||||
yield* sessions.markDisconnected(issued.sessionId);
|
||||
yield* sessions.markDisconnected(issued.sessionId);
|
||||
const afterDisconnect = yield* sessions.listActive();
|
||||
|
||||
expect(afterDisconnect[0]?.connected).toBe(false);
|
||||
expect(afterDisconnect[0]?.lastConnectedAt?.toString()).toBe(firstConnectedAt?.toString());
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
yield* sessions.markConnected(issued.sessionId);
|
||||
const afterReconnect = yield* sessions.listActive();
|
||||
|
||||
expect(afterReconnect[0]?.connected).toBe(true);
|
||||
expect(afterReconnect[0]?.lastConnectedAt).not.toBeNull();
|
||||
expect(afterReconnect[0]?.lastConnectedAt?.toString()).not.toBe(firstConnectedAt?.toString());
|
||||
}).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,500 @@
|
||||
import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "@t3tools/contracts";
|
||||
import { Clock, DateTime, Duration, Effect, Layer, PubSub, Ref, Schema, Stream } from "effect";
|
||||
import { Option } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts";
|
||||
import { AuthSessionRepository } from "../../persistence/Services/AuthSessions.ts";
|
||||
import { ServerSecretStore } from "../Services/ServerSecretStore.ts";
|
||||
import {
|
||||
SessionCredentialError,
|
||||
SessionCredentialService,
|
||||
type IssuedSession,
|
||||
type SessionCredentialChange,
|
||||
type SessionCredentialServiceShape,
|
||||
type VerifiedSession,
|
||||
} from "../Services/SessionCredentialService.ts";
|
||||
import {
|
||||
base64UrlDecodeUtf8,
|
||||
base64UrlEncode,
|
||||
resolveSessionCookieName,
|
||||
signPayload,
|
||||
timingSafeEqualBase64Url,
|
||||
} from "../utils.ts";
|
||||
|
||||
const SIGNING_SECRET_NAME = "server-signing-key";
|
||||
const DEFAULT_SESSION_TTL = Duration.days(30);
|
||||
const DEFAULT_WEBSOCKET_TOKEN_TTL = Duration.minutes(5);
|
||||
|
||||
const SessionClaims = Schema.Struct({
|
||||
v: Schema.Literal(1),
|
||||
kind: Schema.Literal("session"),
|
||||
sid: AuthSessionId,
|
||||
sub: Schema.String,
|
||||
role: Schema.Literals(["owner", "client"]),
|
||||
method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]),
|
||||
iat: Schema.Number,
|
||||
exp: Schema.Number,
|
||||
});
|
||||
type SessionClaims = typeof SessionClaims.Type;
|
||||
|
||||
const WebSocketClaims = Schema.Struct({
|
||||
v: Schema.Literal(1),
|
||||
kind: Schema.Literal("websocket"),
|
||||
sid: AuthSessionId,
|
||||
iat: Schema.Number,
|
||||
exp: Schema.Number,
|
||||
});
|
||||
type WebSocketClaims = typeof WebSocketClaims.Type;
|
||||
|
||||
const decodeSessionClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(SessionClaims));
|
||||
const decodeWebSocketClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(WebSocketClaims));
|
||||
|
||||
function createDefaultClientMetadata(): AuthClientMetadata {
|
||||
return {
|
||||
deviceType: "unknown",
|
||||
};
|
||||
}
|
||||
|
||||
function toClientMetadata(record: {
|
||||
readonly label: string | null;
|
||||
readonly ipAddress: string | null;
|
||||
readonly userAgent: string | null;
|
||||
readonly deviceType: AuthClientMetadata["deviceType"];
|
||||
readonly os: string | null;
|
||||
readonly browser: string | null;
|
||||
}): AuthClientMetadata {
|
||||
return {
|
||||
...(record.label ? { label: record.label } : {}),
|
||||
...(record.ipAddress ? { ipAddress: record.ipAddress } : {}),
|
||||
...(record.userAgent ? { userAgent: record.userAgent } : {}),
|
||||
deviceType: record.deviceType,
|
||||
...(record.os ? { os: record.os } : {}),
|
||||
...(record.browser ? { browser: record.browser } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthClientSession {
|
||||
return {
|
||||
...input,
|
||||
current: false,
|
||||
};
|
||||
}
|
||||
|
||||
export const makeSessionCredentialService = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
const authSessions = yield* AuthSessionRepository;
|
||||
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
|
||||
const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
|
||||
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
|
||||
const cookieName = resolveSessionCookieName({
|
||||
mode: serverConfig.mode,
|
||||
port: serverConfig.port,
|
||||
});
|
||||
|
||||
const toSessionCredentialError = (message: string) => (cause: unknown) =>
|
||||
new SessionCredentialError({
|
||||
message,
|
||||
cause,
|
||||
});
|
||||
|
||||
const emitUpsert = (clientSession: AuthClientSession) =>
|
||||
PubSub.publish(changesPubSub, {
|
||||
type: "clientUpserted",
|
||||
clientSession,
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const emitRemoved = (sessionId: AuthSessionId) =>
|
||||
PubSub.publish(changesPubSub, {
|
||||
type: "clientRemoved",
|
||||
sessionId,
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const loadActiveSession = (sessionId: AuthSessionId) =>
|
||||
Effect.gen(function* () {
|
||||
const row = yield* authSessions.getById({ sessionId });
|
||||
if (Option.isNone(row) || row.value.revokedAt !== null) {
|
||||
return Option.none<AuthClientSession>();
|
||||
}
|
||||
|
||||
const connectedSessions = yield* Ref.get(connectedSessionsRef);
|
||||
return Option.some(
|
||||
toAuthClientSession({
|
||||
sessionId: row.value.sessionId,
|
||||
subject: row.value.subject,
|
||||
role: row.value.role,
|
||||
method: row.value.method,
|
||||
client: toClientMetadata(row.value.client),
|
||||
issuedAt: row.value.issuedAt,
|
||||
expiresAt: row.value.expiresAt,
|
||||
lastConnectedAt: row.value.lastConnectedAt,
|
||||
connected: connectedSessions.has(row.value.sessionId),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const markConnected: SessionCredentialServiceShape["markConnected"] = (sessionId) =>
|
||||
Ref.modify(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
const wasDisconnected = !next.has(sessionId);
|
||||
next.set(sessionId, (next.get(sessionId) ?? 0) + 1);
|
||||
return [wasDisconnected, next] as const;
|
||||
}).pipe(
|
||||
Effect.flatMap((wasDisconnected) =>
|
||||
wasDisconnected
|
||||
? DateTime.now.pipe(
|
||||
Effect.flatMap((lastConnectedAt) =>
|
||||
authSessions.setLastConnectedAt({
|
||||
sessionId,
|
||||
lastConnectedAt,
|
||||
}),
|
||||
),
|
||||
)
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.flatMap(() => loadActiveSession(sessionId)),
|
||||
Effect.flatMap((session) =>
|
||||
Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
|
||||
),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logError("Failed to publish connected-session auth update.").pipe(
|
||||
Effect.annotateLogs({
|
||||
sessionId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const markDisconnected: SessionCredentialServiceShape["markDisconnected"] = (sessionId) =>
|
||||
Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
const remaining = (next.get(sessionId) ?? 0) - 1;
|
||||
if (remaining > 0) {
|
||||
next.set(sessionId, remaining);
|
||||
} else {
|
||||
next.delete(sessionId);
|
||||
}
|
||||
return next;
|
||||
}).pipe(
|
||||
Effect.flatMap(() => loadActiveSession(sessionId)),
|
||||
Effect.flatMap((session) =>
|
||||
Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
|
||||
),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logError("Failed to publish disconnected-session auth update.").pipe(
|
||||
Effect.annotateLogs({
|
||||
sessionId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const issue: SessionCredentialServiceShape["issue"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const sessionId = AuthSessionId.make(crypto.randomUUID());
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
|
||||
});
|
||||
const claims: SessionClaims = {
|
||||
v: 1,
|
||||
kind: "session",
|
||||
sid: sessionId,
|
||||
sub: input?.subject ?? "browser",
|
||||
role: input?.role ?? "client",
|
||||
method: input?.method ?? "browser-session-cookie",
|
||||
iat: issuedAt.epochMilliseconds,
|
||||
exp: expiresAt.epochMilliseconds,
|
||||
};
|
||||
const encodedPayload = base64UrlEncode(JSON.stringify(claims));
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
const client = input?.client ?? createDefaultClientMetadata();
|
||||
yield* authSessions.create({
|
||||
sessionId,
|
||||
subject: claims.sub,
|
||||
role: claims.role,
|
||||
method: claims.method,
|
||||
client: {
|
||||
label: client.label ?? null,
|
||||
ipAddress: client.ipAddress ?? null,
|
||||
userAgent: client.userAgent ?? null,
|
||||
deviceType: client.deviceType,
|
||||
os: client.os ?? null,
|
||||
browser: client.browser ?? null,
|
||||
},
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
});
|
||||
yield* emitUpsert(
|
||||
toAuthClientSession({
|
||||
sessionId,
|
||||
subject: claims.sub,
|
||||
role: claims.role,
|
||||
method: claims.method,
|
||||
client,
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
lastConnectedAt: null,
|
||||
connected: false,
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
sessionId,
|
||||
token: `${encodedPayload}.${signature}`,
|
||||
method: claims.method,
|
||||
client,
|
||||
expiresAt: expiresAt,
|
||||
role: claims.role,
|
||||
} satisfies IssuedSession;
|
||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to issue session credential.")));
|
||||
|
||||
const verify: SessionCredentialServiceShape["verify"] = (token) =>
|
||||
Effect.gen(function* () {
|
||||
const [encodedPayload, signature] = token.split(".");
|
||||
if (!encodedPayload || !signature) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Malformed session token.",
|
||||
});
|
||||
}
|
||||
|
||||
const expectedSignature = signPayload(encodedPayload, signingSecret);
|
||||
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Invalid session token signature.",
|
||||
});
|
||||
}
|
||||
|
||||
const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SessionCredentialError({
|
||||
message: "Invalid session token payload.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
if (claims.exp <= now) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Session token expired.",
|
||||
});
|
||||
}
|
||||
|
||||
const row = yield* authSessions.getById({ sessionId: claims.sid });
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Unknown session token.",
|
||||
});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Session token revoked.",
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
sessionId: claims.sid,
|
||||
token,
|
||||
method: claims.method,
|
||||
client: toClientMetadata(row.value.client),
|
||||
expiresAt: DateTime.makeUnsafe(claims.exp),
|
||||
subject: claims.sub,
|
||||
role: claims.role,
|
||||
} satisfies VerifiedSession;
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause instanceof SessionCredentialError
|
||||
? cause
|
||||
: new SessionCredentialError({
|
||||
message: "Failed to verify session credential.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const issueWebSocketToken: SessionCredentialServiceShape["issueWebSocketToken"] = (
|
||||
sessionId,
|
||||
input,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
|
||||
});
|
||||
const claims: WebSocketClaims = {
|
||||
v: 1,
|
||||
kind: "websocket",
|
||||
sid: sessionId,
|
||||
iat: issuedAt.epochMilliseconds,
|
||||
exp: expiresAt.epochMilliseconds,
|
||||
};
|
||||
const encodedPayload = base64UrlEncode(JSON.stringify(claims));
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
return {
|
||||
token: `${encodedPayload}.${signature}`,
|
||||
expiresAt,
|
||||
};
|
||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to issue websocket token.")));
|
||||
|
||||
const verifyWebSocketToken: SessionCredentialServiceShape["verifyWebSocketToken"] = (token) =>
|
||||
Effect.gen(function* () {
|
||||
const [encodedPayload, signature] = token.split(".");
|
||||
if (!encodedPayload || !signature) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Malformed websocket token.",
|
||||
});
|
||||
}
|
||||
|
||||
const expectedSignature = signPayload(encodedPayload, signingSecret);
|
||||
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Invalid websocket token signature.",
|
||||
});
|
||||
}
|
||||
|
||||
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SessionCredentialError({
|
||||
message: "Invalid websocket token payload.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
if (claims.exp <= now) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Websocket token expired.",
|
||||
});
|
||||
}
|
||||
|
||||
const row = yield* authSessions.getById({ sessionId: claims.sid });
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Unknown websocket session.",
|
||||
});
|
||||
}
|
||||
if (row.value.expiresAt.epochMilliseconds <= now) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Websocket session expired.",
|
||||
});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Websocket session revoked.",
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
sessionId: row.value.sessionId,
|
||||
token,
|
||||
method: row.value.method,
|
||||
client: toClientMetadata(row.value.client),
|
||||
expiresAt: row.value.expiresAt,
|
||||
subject: row.value.subject,
|
||||
role: row.value.role,
|
||||
} satisfies VerifiedSession;
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause instanceof SessionCredentialError
|
||||
? cause
|
||||
: new SessionCredentialError({
|
||||
message: "Failed to verify websocket token.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const listActive: SessionCredentialServiceShape["listActive"] = () =>
|
||||
Effect.gen(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
const connectedSessions = yield* Ref.get(connectedSessionsRef);
|
||||
const rows = yield* authSessions.listActive({ now });
|
||||
|
||||
return rows.map((row) =>
|
||||
toAuthClientSession({
|
||||
sessionId: row.sessionId,
|
||||
subject: row.subject,
|
||||
role: row.role,
|
||||
method: row.method,
|
||||
client: toClientMetadata(row.client),
|
||||
issuedAt: row.issuedAt,
|
||||
expiresAt: row.expiresAt,
|
||||
lastConnectedAt: row.lastConnectedAt,
|
||||
connected: connectedSessions.has(row.sessionId),
|
||||
}),
|
||||
);
|
||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to list active sessions.")));
|
||||
|
||||
const revoke: SessionCredentialServiceShape["revoke"] = (sessionId) =>
|
||||
Effect.gen(function* () {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revoked = yield* authSessions.revoke({
|
||||
sessionId,
|
||||
revokedAt,
|
||||
});
|
||||
if (revoked) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
next.delete(sessionId);
|
||||
return next;
|
||||
});
|
||||
yield* emitRemoved(sessionId);
|
||||
}
|
||||
return revoked;
|
||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke session.")));
|
||||
|
||||
const revokeAllExcept: SessionCredentialServiceShape["revokeAllExcept"] = (sessionId) =>
|
||||
Effect.gen(function* () {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revokedSessionIds = yield* authSessions.revokeAllExcept({
|
||||
currentSessionId: sessionId,
|
||||
revokedAt,
|
||||
});
|
||||
if (revokedSessionIds.length > 0) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
for (const revokedSessionId of revokedSessionIds) {
|
||||
next.delete(revokedSessionId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
revokedSessionIds,
|
||||
(revokedSessionId) => emitRemoved(revokedSessionId),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
return revokedSessionIds.length;
|
||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke other sessions.")));
|
||||
|
||||
return {
|
||||
cookieName,
|
||||
issue,
|
||||
verify,
|
||||
issueWebSocketToken,
|
||||
verifyWebSocketToken,
|
||||
listActive,
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
revoke,
|
||||
revokeAllExcept,
|
||||
markConnected,
|
||||
markDisconnected,
|
||||
} satisfies SessionCredentialServiceShape;
|
||||
});
|
||||
|
||||
export const SessionCredentialServiceLive = Layer.effect(
|
||||
SessionCredentialService,
|
||||
makeSessionCredentialService,
|
||||
).pipe(Layer.provideMerge(AuthSessionRepositoryLive));
|
||||
@@ -0,0 +1,69 @@
|
||||
import type {
|
||||
AuthClientMetadata,
|
||||
AuthClientSession,
|
||||
AuthPairingLink,
|
||||
AuthSessionId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, DateTime, Duration, Effect, Context } from "effect";
|
||||
import { SessionRole } from "./SessionCredentialService";
|
||||
|
||||
export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
|
||||
|
||||
export interface IssuedPairingLink {
|
||||
readonly id: string;
|
||||
readonly credential: string;
|
||||
readonly role: SessionRole;
|
||||
readonly subject: string;
|
||||
readonly label?: string;
|
||||
readonly createdAt: DateTime.Utc;
|
||||
readonly expiresAt: DateTime.Utc;
|
||||
}
|
||||
|
||||
export interface IssuedBearerSession {
|
||||
readonly sessionId: AuthSessionId;
|
||||
readonly token: string;
|
||||
readonly method: "bearer-session-token";
|
||||
readonly role: SessionRole;
|
||||
readonly subject: string;
|
||||
readonly client: AuthClientMetadata;
|
||||
readonly expiresAt: DateTime.Utc;
|
||||
}
|
||||
|
||||
export class AuthControlPlaneError extends Data.TaggedError("AuthControlPlaneError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export interface AuthControlPlaneShape {
|
||||
readonly createPairingLink: (input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
readonly label?: string;
|
||||
readonly role?: SessionRole;
|
||||
readonly subject?: string;
|
||||
}) => Effect.Effect<IssuedPairingLink, AuthControlPlaneError>;
|
||||
readonly listPairingLinks: (input?: {
|
||||
readonly role?: SessionRole;
|
||||
readonly excludeSubjects?: ReadonlyArray<string>;
|
||||
}) => Effect.Effect<ReadonlyArray<AuthPairingLink>, AuthControlPlaneError>;
|
||||
readonly revokePairingLink: (id: string) => Effect.Effect<boolean, AuthControlPlaneError>;
|
||||
readonly issueSession: (input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
readonly subject?: string;
|
||||
readonly role?: SessionRole;
|
||||
readonly label?: string;
|
||||
}) => Effect.Effect<IssuedBearerSession, AuthControlPlaneError>;
|
||||
readonly listSessions: () => Effect.Effect<
|
||||
ReadonlyArray<AuthClientSession>,
|
||||
AuthControlPlaneError
|
||||
>;
|
||||
readonly revokeSession: (
|
||||
sessionId: AuthSessionId,
|
||||
) => Effect.Effect<boolean, AuthControlPlaneError>;
|
||||
readonly revokeOtherSessionsExcept: (
|
||||
sessionId: AuthSessionId,
|
||||
) => Effect.Effect<number, AuthControlPlaneError>;
|
||||
}
|
||||
|
||||
export class AuthControlPlane extends Context.Service<AuthControlPlane, AuthControlPlaneShape>()(
|
||||
"t3/AuthControlPlane",
|
||||
) {}
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { AuthPairingLink, ServerAuthBootstrapMethod } from "@t3tools/contracts";
|
||||
import { Data, DateTime, Duration, Context } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
|
||||
export type BootstrapCredentialRole = "owner" | "client";
|
||||
|
||||
export interface BootstrapGrant {
|
||||
readonly method: ServerAuthBootstrapMethod;
|
||||
readonly role: BootstrapCredentialRole;
|
||||
readonly subject: string;
|
||||
readonly label?: string;
|
||||
readonly expiresAt: DateTime.DateTime;
|
||||
}
|
||||
|
||||
export class BootstrapCredentialError extends Data.TaggedError("BootstrapCredentialError")<{
|
||||
readonly message: string;
|
||||
readonly status?: 401 | 500;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export interface IssuedBootstrapCredential {
|
||||
readonly id: string;
|
||||
readonly credential: string;
|
||||
readonly label?: string;
|
||||
readonly expiresAt: DateTime.Utc;
|
||||
}
|
||||
|
||||
export type BootstrapCredentialChange =
|
||||
| {
|
||||
readonly type: "pairingLinkUpserted";
|
||||
readonly pairingLink: AuthPairingLink;
|
||||
}
|
||||
| {
|
||||
readonly type: "pairingLinkRemoved";
|
||||
readonly id: string;
|
||||
};
|
||||
|
||||
export interface BootstrapCredentialServiceShape {
|
||||
readonly issueOneTimeToken: (input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
readonly role?: BootstrapCredentialRole;
|
||||
readonly subject?: string;
|
||||
readonly label?: string;
|
||||
}) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialError>;
|
||||
readonly listActive: () => Effect.Effect<
|
||||
ReadonlyArray<AuthPairingLink>,
|
||||
BootstrapCredentialError
|
||||
>;
|
||||
readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;
|
||||
readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialError>;
|
||||
readonly consume: (credential: string) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
|
||||
}
|
||||
|
||||
export class BootstrapCredentialService extends Context.Service<
|
||||
BootstrapCredentialService,
|
||||
BootstrapCredentialServiceShape
|
||||
>()("t3/auth/Services/BootstrapCredentialService") {}
|
||||
@@ -0,0 +1,84 @@
|
||||
import type {
|
||||
AuthBearerBootstrapResult,
|
||||
AuthBootstrapResult,
|
||||
AuthClientMetadata,
|
||||
AuthClientSession,
|
||||
AuthCreatePairingCredentialInput,
|
||||
AuthPairingLink,
|
||||
AuthPairingCredentialResult,
|
||||
AuthSessionId,
|
||||
AuthSessionState,
|
||||
ServerAuthDescriptor,
|
||||
ServerAuthSessionMethod,
|
||||
AuthWebSocketTokenResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, DateTime, Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import type { SessionRole } from "./SessionCredentialService.ts";
|
||||
|
||||
export interface AuthenticatedSession {
|
||||
readonly sessionId: AuthSessionId;
|
||||
readonly subject: string;
|
||||
readonly method: ServerAuthSessionMethod;
|
||||
readonly role: SessionRole;
|
||||
readonly expiresAt?: DateTime.DateTime;
|
||||
}
|
||||
|
||||
export class AuthError extends Data.TaggedError("AuthError")<{
|
||||
readonly message: string;
|
||||
readonly status?: 400 | 401 | 403 | 500;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export interface ServerAuthShape {
|
||||
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
|
||||
readonly getSessionState: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthSessionState, never>;
|
||||
readonly exchangeBootstrapCredential: (
|
||||
credential: string,
|
||||
requestMetadata: AuthClientMetadata,
|
||||
) => Effect.Effect<
|
||||
{
|
||||
readonly response: AuthBootstrapResult;
|
||||
readonly sessionToken: string;
|
||||
},
|
||||
AuthError
|
||||
>;
|
||||
readonly exchangeBootstrapCredentialForBearerSession: (
|
||||
credential: string,
|
||||
requestMetadata: AuthClientMetadata,
|
||||
) => Effect.Effect<AuthBearerBootstrapResult, AuthError>;
|
||||
readonly issuePairingCredential: (
|
||||
input?: AuthCreatePairingCredentialInput & {
|
||||
readonly role?: SessionRole;
|
||||
},
|
||||
) => Effect.Effect<AuthPairingCredentialResult, AuthError>;
|
||||
readonly listPairingLinks: () => Effect.Effect<ReadonlyArray<AuthPairingLink>, AuthError>;
|
||||
readonly revokePairingLink: (id: string) => Effect.Effect<boolean, AuthError>;
|
||||
readonly listClientSessions: (
|
||||
currentSessionId: AuthSessionId,
|
||||
) => Effect.Effect<ReadonlyArray<AuthClientSession>, AuthError>;
|
||||
readonly revokeClientSession: (
|
||||
currentSessionId: AuthSessionId,
|
||||
targetSessionId: AuthSessionId,
|
||||
) => Effect.Effect<boolean, AuthError>;
|
||||
readonly revokeOtherClientSessions: (
|
||||
currentSessionId: AuthSessionId,
|
||||
) => Effect.Effect<number, AuthError>;
|
||||
readonly authenticateHttpRequest: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthenticatedSession, AuthError>;
|
||||
readonly authenticateWebSocketUpgrade: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthenticatedSession, AuthError>;
|
||||
readonly issueWebSocketToken: (
|
||||
session: AuthenticatedSession,
|
||||
) => Effect.Effect<AuthWebSocketTokenResult, AuthError>;
|
||||
readonly issueStartupPairingUrl: (baseUrl: string) => Effect.Effect<string, AuthError>;
|
||||
}
|
||||
|
||||
export class ServerAuth extends Context.Service<ServerAuth, ServerAuthShape>()(
|
||||
"t3/auth/Services/ServerAuth",
|
||||
) {}
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { ServerAuthDescriptor } from "@t3tools/contracts";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export interface ServerAuthPolicyShape {
|
||||
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
|
||||
}
|
||||
|
||||
export class ServerAuthPolicy extends Context.Service<ServerAuthPolicy, ServerAuthPolicyShape>()(
|
||||
"t3/auth/Services/ServerAuthPolicy",
|
||||
) {}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Data, Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export interface ServerSecretStoreShape {
|
||||
readonly get: (name: string) => Effect.Effect<Uint8Array | null, SecretStoreError>;
|
||||
readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
|
||||
readonly getOrCreateRandom: (
|
||||
name: string,
|
||||
bytes: number,
|
||||
) => Effect.Effect<Uint8Array, SecretStoreError>;
|
||||
readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
|
||||
}
|
||||
|
||||
export class ServerSecretStore extends Context.Service<ServerSecretStore, ServerSecretStoreShape>()(
|
||||
"t3/auth/Services/ServerSecretStore",
|
||||
) {}
|
||||
@@ -0,0 +1,87 @@
|
||||
import type {
|
||||
AuthClientMetadata,
|
||||
AuthClientSession,
|
||||
AuthSessionId,
|
||||
ServerAuthSessionMethod,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, DateTime, Duration, Context } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
|
||||
export type SessionRole = "owner" | "client";
|
||||
|
||||
export interface IssuedSession {
|
||||
readonly sessionId: AuthSessionId;
|
||||
readonly token: string;
|
||||
readonly method: ServerAuthSessionMethod;
|
||||
readonly client: AuthClientMetadata;
|
||||
readonly expiresAt: DateTime.DateTime;
|
||||
readonly role: SessionRole;
|
||||
}
|
||||
|
||||
export interface VerifiedSession {
|
||||
readonly sessionId: AuthSessionId;
|
||||
readonly token: string;
|
||||
readonly method: ServerAuthSessionMethod;
|
||||
readonly client: AuthClientMetadata;
|
||||
readonly expiresAt?: DateTime.DateTime;
|
||||
readonly subject: string;
|
||||
readonly role: SessionRole;
|
||||
}
|
||||
|
||||
export type SessionCredentialChange =
|
||||
| {
|
||||
readonly type: "clientUpserted";
|
||||
readonly clientSession: AuthClientSession;
|
||||
}
|
||||
| {
|
||||
readonly type: "clientRemoved";
|
||||
readonly sessionId: AuthSessionId;
|
||||
};
|
||||
|
||||
export class SessionCredentialError extends Data.TaggedError("SessionCredentialError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export interface SessionCredentialServiceShape {
|
||||
readonly cookieName: string;
|
||||
readonly issue: (input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
readonly subject?: string;
|
||||
readonly method?: ServerAuthSessionMethod;
|
||||
readonly role?: SessionRole;
|
||||
readonly client?: AuthClientMetadata;
|
||||
}) => Effect.Effect<IssuedSession, SessionCredentialError>;
|
||||
readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;
|
||||
readonly issueWebSocketToken: (
|
||||
sessionId: AuthSessionId,
|
||||
input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
},
|
||||
) => Effect.Effect<
|
||||
{
|
||||
readonly token: string;
|
||||
readonly expiresAt: DateTime.DateTime;
|
||||
},
|
||||
SessionCredentialError
|
||||
>;
|
||||
readonly verifyWebSocketToken: (
|
||||
token: string,
|
||||
) => Effect.Effect<VerifiedSession, SessionCredentialError>;
|
||||
readonly listActive: () => Effect.Effect<
|
||||
ReadonlyArray<AuthClientSession>,
|
||||
SessionCredentialError
|
||||
>;
|
||||
readonly streamChanges: Stream.Stream<SessionCredentialChange>;
|
||||
readonly revoke: (sessionId: AuthSessionId) => Effect.Effect<boolean, SessionCredentialError>;
|
||||
readonly revokeAllExcept: (
|
||||
sessionId: AuthSessionId,
|
||||
) => Effect.Effect<number, SessionCredentialError>;
|
||||
readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
|
||||
readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export class SessionCredentialService extends Context.Service<
|
||||
SessionCredentialService,
|
||||
SessionCredentialServiceShape
|
||||
>()("t3/auth/Services/SessionCredentialService") {}
|
||||
@@ -0,0 +1,254 @@
|
||||
import {
|
||||
type AuthBearerBootstrapResult,
|
||||
AuthBootstrapInput,
|
||||
AuthCreatePairingCredentialInput,
|
||||
AuthRevokeClientSessionInput,
|
||||
AuthRevokePairingLinkInput,
|
||||
type AuthWebSocketTokenResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { DateTime, Effect, Schema } from "effect";
|
||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
|
||||
import { AuthError, ServerAuth } from "./Services/ServerAuth.ts";
|
||||
import { SessionCredentialService } from "./Services/SessionCredentialService.ts";
|
||||
import { deriveAuthClientMetadata } from "./utils.ts";
|
||||
|
||||
export const respondToAuthError = (error: AuthError) =>
|
||||
Effect.gen(function* () {
|
||||
if ((error.status ?? 500) >= 500) {
|
||||
yield* Effect.logError("auth route failed", {
|
||||
message: error.message,
|
||||
cause: error.cause,
|
||||
});
|
||||
}
|
||||
return HttpServerResponse.jsonUnsafe(
|
||||
{
|
||||
error: error.message,
|
||||
},
|
||||
{ status: error.status ?? 500 },
|
||||
);
|
||||
});
|
||||
|
||||
export const authSessionRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
"/api/auth/session",
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const session = yield* serverAuth.getSessionState(request);
|
||||
return HttpServerResponse.jsonUnsafe(session, { status: 200 });
|
||||
}),
|
||||
);
|
||||
|
||||
const PairingCredentialRequestHeaders = Schema.Struct({
|
||||
"content-length": Schema.optionalKey(Schema.String),
|
||||
"content-type": Schema.optionalKey(Schema.String),
|
||||
"transfer-encoding": Schema.optionalKey(Schema.String),
|
||||
});
|
||||
|
||||
function hasRequestBody(headers: typeof PairingCredentialRequestHeaders.Type) {
|
||||
const contentLengthHeader = headers["content-length"];
|
||||
if (typeof contentLengthHeader === "string") {
|
||||
const contentLength = Number.parseInt(contentLengthHeader, 10);
|
||||
if (Number.isFinite(contentLength)) {
|
||||
return contentLength > 0;
|
||||
}
|
||||
}
|
||||
return typeof headers["transfer-encoding"] === "string";
|
||||
}
|
||||
|
||||
export const authBootstrapRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/api/auth/bootstrap",
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const payload = yield* HttpServerRequest.schemaBodyJson(AuthBootstrapInput).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Invalid bootstrap payload.",
|
||||
status: 400,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const result = yield* serverAuth.exchangeBootstrapCredential(
|
||||
payload.credential,
|
||||
deriveAuthClientMetadata({ request }),
|
||||
);
|
||||
|
||||
return yield* HttpServerResponse.jsonUnsafe(result.response, { status: 200 }).pipe(
|
||||
HttpServerResponse.setCookie(sessions.cookieName, result.sessionToken, {
|
||||
expires: DateTime.toDate(result.response.expiresAt),
|
||||
httpOnly: true,
|
||||
path: "/",
|
||||
sameSite: "lax",
|
||||
}),
|
||||
);
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
export const authBearerBootstrapRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/api/auth/bootstrap/bearer",
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const payload = yield* HttpServerRequest.schemaBodyJson(AuthBootstrapInput).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Invalid bootstrap payload.",
|
||||
status: 400,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const result = yield* serverAuth.exchangeBootstrapCredentialForBearerSession(
|
||||
payload.credential,
|
||||
deriveAuthClientMetadata({ request }),
|
||||
);
|
||||
return HttpServerResponse.jsonUnsafe(result satisfies AuthBearerBootstrapResult, {
|
||||
status: 200,
|
||||
});
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
export const authWebSocketTokenRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/api/auth/ws-token",
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const session = yield* serverAuth.authenticateHttpRequest(request);
|
||||
const result = yield* serverAuth.issueWebSocketToken(session);
|
||||
return HttpServerResponse.jsonUnsafe(result satisfies AuthWebSocketTokenResult, {
|
||||
status: 200,
|
||||
});
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
export const authPairingCredentialRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/api/auth/pairing-token",
|
||||
Effect.gen(function* () {
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const session = yield* serverAuth.authenticateHttpRequest(request);
|
||||
if (session.role !== "owner") {
|
||||
return yield* new AuthError({
|
||||
message: "Only owner sessions can create pairing credentials.",
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
const headers = yield* HttpServerRequest.schemaHeaders(PairingCredentialRequestHeaders).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Invalid pairing credential request headers.",
|
||||
status: 400,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const payload = hasRequestBody(headers)
|
||||
? yield* HttpServerRequest.schemaBodyJson(AuthCreatePairingCredentialInput).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Invalid pairing credential payload.",
|
||||
status: 400,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
)
|
||||
: {};
|
||||
const result = yield* serverAuth.issuePairingCredential(payload);
|
||||
return HttpServerResponse.jsonUnsafe(result, { status: 200 });
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
const authenticateOwnerSession = Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const session = yield* serverAuth.authenticateHttpRequest(request);
|
||||
if (session.role !== "owner") {
|
||||
return yield* new AuthError({
|
||||
message: "Only owner sessions can manage network access.",
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
return { serverAuth, session } as const;
|
||||
});
|
||||
|
||||
export const authPairingLinksRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
"/api/auth/pairing-links",
|
||||
Effect.gen(function* () {
|
||||
const { serverAuth } = yield* authenticateOwnerSession;
|
||||
const pairingLinks = yield* serverAuth.listPairingLinks();
|
||||
return HttpServerResponse.jsonUnsafe(pairingLinks, { status: 200 });
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
export const authPairingLinksRevokeRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/api/auth/pairing-links/revoke",
|
||||
Effect.gen(function* () {
|
||||
const { serverAuth } = yield* authenticateOwnerSession;
|
||||
const payload = yield* HttpServerRequest.schemaBodyJson(AuthRevokePairingLinkInput).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Invalid revoke pairing link payload.",
|
||||
status: 400,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const revoked = yield* serverAuth.revokePairingLink(payload.id);
|
||||
return HttpServerResponse.jsonUnsafe({ revoked }, { status: 200 });
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
export const authClientsRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
"/api/auth/clients",
|
||||
Effect.gen(function* () {
|
||||
const { serverAuth, session } = yield* authenticateOwnerSession;
|
||||
const clients = yield* serverAuth.listClientSessions(session.sessionId);
|
||||
return HttpServerResponse.jsonUnsafe(clients, { status: 200 });
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
export const authClientsRevokeRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/api/auth/clients/revoke",
|
||||
Effect.gen(function* () {
|
||||
const { serverAuth, session } = yield* authenticateOwnerSession;
|
||||
const payload = yield* HttpServerRequest.schemaBodyJson(AuthRevokeClientSessionInput).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Invalid revoke client payload.",
|
||||
status: 400,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const revoked = yield* serverAuth.revokeClientSession(session.sessionId, payload.sessionId);
|
||||
return HttpServerResponse.jsonUnsafe({ revoked }, { status: 200 });
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
export const authClientsRevokeOthersRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/api/auth/clients/revoke-others",
|
||||
Effect.gen(function* () {
|
||||
const { serverAuth, session } = yield* authenticateOwnerSession;
|
||||
const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);
|
||||
return HttpServerResponse.jsonUnsafe({ revokedCount }, { status: 200 });
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { deriveAuthClientMetadata } from "./utils";
|
||||
|
||||
describe("deriveAuthClientMetadata", () => {
|
||||
it("labels Electron user agents as Electron instead of Chrome", () => {
|
||||
const metadata = deriveAuthClientMetadata({
|
||||
request: {
|
||||
headers: {
|
||||
"user-agent":
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) t3code/0.0.15 Chrome/136.0.7103.93 Electron/36.3.2 Safari/537.36",
|
||||
},
|
||||
source: {
|
||||
remoteAddress: "::ffff:127.0.0.1",
|
||||
},
|
||||
} as never,
|
||||
});
|
||||
|
||||
expect(metadata).toMatchObject({
|
||||
browser: "Electron",
|
||||
deviceType: "desktop",
|
||||
ipAddress: "127.0.0.1",
|
||||
os: "macOS",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
import type { AuthClientMetadata, AuthClientMetadataDeviceType } from "@t3tools/contracts";
|
||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as Crypto from "node:crypto";
|
||||
|
||||
const SESSION_COOKIE_NAME = "t3_session";
|
||||
|
||||
export function resolveSessionCookieName(input: {
|
||||
readonly mode: "web" | "desktop";
|
||||
readonly port: number;
|
||||
}): string {
|
||||
if (input.mode !== "desktop") {
|
||||
return SESSION_COOKIE_NAME;
|
||||
}
|
||||
|
||||
return `${SESSION_COOKIE_NAME}_${input.port}`;
|
||||
}
|
||||
|
||||
export function base64UrlEncode(input: string | Uint8Array): string {
|
||||
const buffer = typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.from(input);
|
||||
return buffer.toString("base64url");
|
||||
}
|
||||
|
||||
export function base64UrlDecodeUtf8(input: string): string {
|
||||
return Buffer.from(input, "base64url").toString("utf8");
|
||||
}
|
||||
|
||||
export function signPayload(payload: string, secret: Uint8Array): string {
|
||||
return Crypto.createHmac("sha256", Buffer.from(secret)).update(payload).digest("base64url");
|
||||
}
|
||||
|
||||
export function timingSafeEqualBase64Url(left: string, right: string): boolean {
|
||||
const leftBuffer = Buffer.from(left, "base64url");
|
||||
const rightBuffer = Buffer.from(right, "base64url");
|
||||
if (leftBuffer.length !== rightBuffer.length) {
|
||||
return false;
|
||||
}
|
||||
return Crypto.timingSafeEqual(leftBuffer, rightBuffer);
|
||||
}
|
||||
|
||||
function normalizeNonEmptyString(value: string | null | undefined): string | undefined {
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function normalizeIpAddress(value: string | null | undefined): string | undefined {
|
||||
const normalized = normalizeNonEmptyString(value);
|
||||
if (!normalized) {
|
||||
return undefined;
|
||||
}
|
||||
return normalized.startsWith("::ffff:") ? normalized.slice("::ffff:".length) : normalized;
|
||||
}
|
||||
|
||||
function inferDeviceType(userAgent: string | undefined): AuthClientMetadataDeviceType {
|
||||
if (!userAgent) {
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
const normalized = userAgent.toLowerCase();
|
||||
if (/bot|crawler|spider|slurp|curl|wget/.test(normalized)) {
|
||||
return "bot";
|
||||
}
|
||||
if (/ipad|tablet/.test(normalized)) {
|
||||
return "tablet";
|
||||
}
|
||||
if (/iphone|android.+mobile|mobile/.test(normalized)) {
|
||||
return "mobile";
|
||||
}
|
||||
return "desktop";
|
||||
}
|
||||
|
||||
function inferBrowser(userAgent: string | undefined): string | undefined {
|
||||
if (!userAgent) {
|
||||
return undefined;
|
||||
}
|
||||
const normalized = userAgent.toLowerCase();
|
||||
if (/edg\//.test(normalized)) return "Edge";
|
||||
if (/opr\//.test(normalized)) return "Opera";
|
||||
if (/firefox\//.test(normalized)) return "Firefox";
|
||||
if (/electron\//.test(normalized)) return "Electron";
|
||||
if (/chrome\//.test(normalized) || /crios\//.test(normalized)) return "Chrome";
|
||||
if (/safari\//.test(normalized) && !/chrome\//.test(normalized)) return "Safari";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function inferOs(userAgent: string | undefined): string | undefined {
|
||||
if (!userAgent) {
|
||||
return undefined;
|
||||
}
|
||||
const normalized = userAgent.toLowerCase();
|
||||
if (/iphone|ipad|ipod/.test(normalized)) return "iOS";
|
||||
if (/android/.test(normalized)) return "Android";
|
||||
if (/mac os x|macintosh/.test(normalized)) return "macOS";
|
||||
if (/windows nt/.test(normalized)) return "Windows";
|
||||
if (/linux/.test(normalized)) return "Linux";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function readRemoteAddressFromSource(source: unknown): string | undefined {
|
||||
if (!source || typeof source !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const candidate = source as {
|
||||
readonly remoteAddress?: string | null;
|
||||
readonly socket?: {
|
||||
readonly remoteAddress?: string | null;
|
||||
};
|
||||
};
|
||||
|
||||
return normalizeIpAddress(candidate.socket?.remoteAddress ?? candidate.remoteAddress);
|
||||
}
|
||||
|
||||
export function deriveAuthClientMetadata(input: {
|
||||
readonly request: HttpServerRequest.HttpServerRequest;
|
||||
readonly label?: string;
|
||||
}): AuthClientMetadata {
|
||||
const userAgent = normalizeNonEmptyString(input.request.headers["user-agent"]);
|
||||
const ipAddress = readRemoteAddressFromSource(input.request.source);
|
||||
const os = inferOs(userAgent);
|
||||
const browser = inferBrowser(userAgent);
|
||||
return {
|
||||
...(input.label ? { label: input.label } : {}),
|
||||
...(ipAddress ? { ipAddress } : {}),
|
||||
...(userAgent ? { userAgent } : {}),
|
||||
deviceType: inferDeviceType(userAgent),
|
||||
...(os ? { os } : {}),
|
||||
...(browser ? { browser } : {}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { cli } from "./cli";
|
||||
import { version } from "../package.json" with { type: "json" };
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
|
||||
Command.run(cli, { version }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(CliRuntimeLayer),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
@@ -8,10 +8,33 @@ import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { vi } from "vitest";
|
||||
|
||||
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap";
|
||||
import { assertNone, assertSome } from "@effect/vitest/utils";
|
||||
|
||||
const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null }));
|
||||
|
||||
vi.mock("node:fs", async (importOriginal) => {
|
||||
const actual = await importOriginal<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) => {
|
||||
@@ -47,6 +70,36 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to reading the inherited fd when path duplication fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
||||
|
||||
yield* fs.writeFileString(
|
||||
filePath,
|
||||
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
|
||||
mode: "desktop",
|
||||
})}\n`,
|
||||
);
|
||||
|
||||
// Open without acquireRelease: the direct-stream fallback uses autoClose: true,
|
||||
// so the stream owns the fd lifecycle and closes it asynchronously on end.
|
||||
// Attempting to also close it synchronously in a finalizer races with the
|
||||
// stream's async close and produces an uncaught EBADF.
|
||||
const fd = NFS.openSync(filePath, "r");
|
||||
|
||||
openSyncInterceptor.failPath = `/proc/self/fd/${fd}`;
|
||||
try {
|
||||
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
|
||||
assertSome(payload, {
|
||||
mode: "desktop",
|
||||
});
|
||||
} finally {
|
||||
openSyncInterceptor.failPath = null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns none when the fd is unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fd = NFS.openSync("/dev/null", "r");
|
||||
|
||||
@@ -108,21 +108,26 @@ const makeBootstrapInputStream = (fd: number) =>
|
||||
try: () => {
|
||||
const fdPath = resolveFdPath(fd);
|
||||
if (fdPath === undefined) {
|
||||
const stream = new Net.Socket({
|
||||
fd,
|
||||
readable: true,
|
||||
writable: false,
|
||||
});
|
||||
stream.setEncoding("utf8");
|
||||
return stream;
|
||||
return makeDirectBootstrapStream(fd);
|
||||
}
|
||||
|
||||
const streamFd = NFS.openSync(fdPath, "r");
|
||||
return NFS.createReadStream("", {
|
||||
fd: streamFd,
|
||||
encoding: "utf8",
|
||||
autoClose: true,
|
||||
});
|
||||
let streamFd: number | undefined;
|
||||
try {
|
||||
streamFd = NFS.openSync(fdPath, "r");
|
||||
return NFS.createReadStream("", {
|
||||
fd: streamFd,
|
||||
encoding: "utf8",
|
||||
autoClose: true,
|
||||
});
|
||||
} catch (error) {
|
||||
if (isBootstrapFdPathDuplicationError(error)) {
|
||||
if (streamFd !== undefined) {
|
||||
NFS.closeSync(streamFd);
|
||||
}
|
||||
return makeDirectBootstrapStream(fd);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
catch: (error) =>
|
||||
new BootstrapError({
|
||||
@@ -131,6 +136,29 @@ const makeBootstrapInputStream = (fd: number) =>
|
||||
}),
|
||||
});
|
||||
|
||||
const makeDirectBootstrapStream = (fd: number): Readable => {
|
||||
try {
|
||||
return NFS.createReadStream("", {
|
||||
fd,
|
||||
encoding: "utf8",
|
||||
autoClose: true,
|
||||
});
|
||||
} catch {
|
||||
const stream = new Net.Socket({
|
||||
fd,
|
||||
readable: true,
|
||||
writable: false,
|
||||
});
|
||||
stream.setEncoding("utf8");
|
||||
return stream;
|
||||
}
|
||||
};
|
||||
|
||||
const isBootstrapFdPathDuplicationError = Predicate.compose(
|
||||
Predicate.hasProperty("code"),
|
||||
(_) => _.code === "ENXIO" || _.code === "EINVAL" || _.code === "EPERM",
|
||||
);
|
||||
|
||||
export function resolveFdPath(
|
||||
fd: number,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Schema } from "effect";
|
||||
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
|
||||
import { GitCommandError } from "../git/Errors.ts";
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* CheckpointUnavailableError - Expected checkpoint does not exist.
|
||||
|
||||
@@ -1,82 +1,38 @@
|
||||
import {
|
||||
CheckpointRef,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { CheckpointRef, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
ProjectionSnapshotQuery,
|
||||
type ProjectionThreadCheckpointContext,
|
||||
} from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||
import { CheckpointDiffQueryLive } from "./CheckpointDiffQuery.ts";
|
||||
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
||||
import { CheckpointDiffQuery } from "../Services/CheckpointDiffQuery.ts";
|
||||
|
||||
function makeSnapshot(input: {
|
||||
function makeThreadCheckpointContext(input: {
|
||||
readonly projectId: ProjectId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly workspaceRoot: string;
|
||||
readonly worktreePath: string | null;
|
||||
readonly checkpointTurnCount: number;
|
||||
readonly checkpointRef: CheckpointRef;
|
||||
}): OrchestrationReadModel {
|
||||
}): ProjectionThreadCheckpointContext {
|
||||
return {
|
||||
snapshotSequence: 0,
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
projects: [
|
||||
threadId: input.threadId,
|
||||
projectId: input.projectId,
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
worktreePath: input.worktreePath,
|
||||
checkpoints: [
|
||||
{
|
||||
id: input.projectId,
|
||||
title: "Project",
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: input.threadId,
|
||||
projectId: input.projectId,
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: input.worktreePath,
|
||||
latestTurn: {
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-01-01T00:00:00.000Z",
|
||||
startedAt: "2026-01-01T00:00:00.000Z",
|
||||
completedAt: "2026-01-01T00:00:00.000Z",
|
||||
assistantMessageId: null,
|
||||
},
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
checkpoints: [
|
||||
{
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
checkpointTurnCount: input.checkpointTurnCount,
|
||||
checkpointRef: input.checkpointRef,
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: null,
|
||||
completedAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
session: null,
|
||||
turnId: TurnId.make("turn-1"),
|
||||
checkpointTurnCount: input.checkpointTurnCount,
|
||||
checkpointRef: input.checkpointRef,
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: null,
|
||||
completedAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -84,8 +40,8 @@ function makeSnapshot(input: {
|
||||
|
||||
describe("CheckpointDiffQueryLive", () => {
|
||||
it("computes diffs using canonical turn-0 checkpoint refs", async () => {
|
||||
const projectId = ProjectId.makeUnsafe("project-1");
|
||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
||||
const projectId = ProjectId.make("project-1");
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
const hasCheckpointRefCalls: Array<CheckpointRef> = [];
|
||||
const diffCheckpointsCalls: Array<{
|
||||
@@ -94,7 +50,7 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
readonly cwd: string;
|
||||
}> = [];
|
||||
|
||||
const snapshot = makeSnapshot({
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
projectId,
|
||||
threadId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
@@ -124,7 +80,12 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () => Effect.succeed(snapshot),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -158,7 +119,7 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
});
|
||||
|
||||
it("fails when the thread is missing from the snapshot", async () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-missing");
|
||||
const threadId = ThreadId.make("thread-missing");
|
||||
|
||||
const checkpointStore: CheckpointStoreShape = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
@@ -174,12 +135,11 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () =>
|
||||
Effect.succeed({
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [],
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
} satisfies OrchestrationReadModel),
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -4,11 +4,11 @@ import {
|
||||
type OrchestrationGetFullThreadDiffResult,
|
||||
type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
import { Effect, Layer, Option, Schema } from "effect";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { CheckpointInvariantError, CheckpointUnavailableError } from "../Errors.ts";
|
||||
import { checkpointRefForThreadTurn, resolveThreadWorkspaceCwd } from "../Utils.ts";
|
||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||
import { CheckpointStore } from "../Services/CheckpointStore.ts";
|
||||
import {
|
||||
CheckpointDiffQuery,
|
||||
@@ -21,8 +21,8 @@ const make = Effect.gen(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
|
||||
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
|
||||
function* (input) {
|
||||
const operation = "CheckpointDiffQuery.getTurnDiff";
|
||||
|
||||
if (input.fromTurnCount === input.toTurnCount) {
|
||||
@@ -41,16 +41,17 @@ const make = Effect.gen(function* () {
|
||||
return emptyDiff;
|
||||
}
|
||||
|
||||
const snapshot = yield* projectionSnapshotQuery.getSnapshot();
|
||||
const thread = snapshot.threads.find((entry) => entry.id === input.threadId);
|
||||
if (!thread) {
|
||||
const threadContext = yield* projectionSnapshotQuery.getThreadCheckpointContext(
|
||||
input.threadId,
|
||||
);
|
||||
if (Option.isNone(threadContext)) {
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
detail: `Thread '${input.threadId}' not found.`,
|
||||
});
|
||||
}
|
||||
|
||||
const maxTurnCount = thread.checkpoints.reduce(
|
||||
const maxTurnCount = threadContext.value.checkpoints.reduce(
|
||||
(max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),
|
||||
0,
|
||||
);
|
||||
@@ -62,10 +63,7 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const workspaceCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: snapshot.projects,
|
||||
});
|
||||
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
|
||||
if (!workspaceCwd) {
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
@@ -76,7 +74,7 @@ const make = Effect.gen(function* () {
|
||||
const fromCheckpointRef =
|
||||
input.fromTurnCount === 0
|
||||
? checkpointRefForThreadTurn(input.threadId, 0)
|
||||
: thread.checkpoints.find(
|
||||
: threadContext.value.checkpoints.find(
|
||||
(checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,
|
||||
)?.checkpointRef;
|
||||
if (!fromCheckpointRef) {
|
||||
@@ -87,7 +85,7 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const toCheckpointRef = thread.checkpoints.find(
|
||||
const toCheckpointRef = threadContext.value.checkpoints.find(
|
||||
(checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,
|
||||
)?.checkpointRef;
|
||||
if (!toCheckpointRef) {
|
||||
@@ -149,7 +147,8 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
return turnDiff;
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
|
||||
input: OrchestrationGetFullThreadDiffInput,
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import path from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||
import { CheckpointStoreLive } from "./CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../Services/CheckpointStore.ts";
|
||||
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-checkpoint-store-test-",
|
||||
});
|
||||
const GitCoreTestLayer = GitCoreLive.pipe(
|
||||
Layer.provide(ServerConfigLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
const CheckpointStoreTestLayer = CheckpointStoreLive.pipe(
|
||||
Layer.provide(GitCoreTestLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
const TestLayer = Layer.mergeAll(NodeServices.layer, GitCoreTestLayer, CheckpointStoreTestLayer);
|
||||
|
||||
function makeTmpDir(
|
||||
prefix = "checkpoint-store-test-",
|
||||
): Effect.Effect<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.make("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,7 +14,7 @@ import { randomUUID } from "node:crypto";
|
||||
import { Effect, Layer, FileSystem, Path } from "effect";
|
||||
|
||||
import { CheckpointInvariantError } from "../Errors.ts";
|
||||
import { GitCommandError } from "../../git/Errors.ts";
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
||||
import { CheckpointRef } from "@t3tools/contracts";
|
||||
@@ -86,139 +86,140 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
);
|
||||
|
||||
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const operation = "CheckpointStore.captureCheckpoint";
|
||||
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
|
||||
"captureCheckpoint",
|
||||
)(function* (input) {
|
||||
const operation = "CheckpointStore.captureCheckpoint";
|
||||
|
||||
yield* Effect.acquireUseRelease(
|
||||
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
|
||||
(tempDir) =>
|
||||
Effect.gen(function* () {
|
||||
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
|
||||
const commitEnv: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
GIT_INDEX_FILE: tempIndexPath,
|
||||
GIT_AUTHOR_NAME: "T3 Code",
|
||||
GIT_AUTHOR_EMAIL: "[email protected]",
|
||||
GIT_COMMITTER_NAME: "T3 Code",
|
||||
GIT_COMMITTER_EMAIL: "[email protected]",
|
||||
};
|
||||
yield* Effect.acquireUseRelease(
|
||||
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
|
||||
Effect.fn("captureCheckpoint.withTempDirectory")(function* (tempDir) {
|
||||
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
|
||||
const commitEnv: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
GIT_INDEX_FILE: tempIndexPath,
|
||||
GIT_AUTHOR_NAME: "T3 Code",
|
||||
GIT_AUTHOR_EMAIL: "[email protected]",
|
||||
GIT_COMMITTER_NAME: "T3 Code",
|
||||
GIT_COMMITTER_EMAIL: "[email protected]",
|
||||
};
|
||||
|
||||
const headExists = yield* hasHeadCommit(input.cwd);
|
||||
if (headExists) {
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["read-tree", "HEAD"],
|
||||
env: commitEnv,
|
||||
});
|
||||
}
|
||||
const headExists = yield* hasHeadCommit(input.cwd);
|
||||
if (headExists) {
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["read-tree", "HEAD"],
|
||||
env: commitEnv,
|
||||
});
|
||||
}
|
||||
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["add", "-A", "--", "."],
|
||||
env: commitEnv,
|
||||
});
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["add", "-A", "--", "."],
|
||||
env: commitEnv,
|
||||
});
|
||||
|
||||
const writeTreeResult = yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["write-tree"],
|
||||
env: commitEnv,
|
||||
});
|
||||
const treeOid = writeTreeResult.stdout.trim();
|
||||
if (treeOid.length === 0) {
|
||||
return yield* new GitCommandError({
|
||||
operation,
|
||||
command: "git write-tree",
|
||||
cwd: input.cwd,
|
||||
detail: "git write-tree returned an empty tree oid.",
|
||||
});
|
||||
}
|
||||
const writeTreeResult = yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["write-tree"],
|
||||
env: commitEnv,
|
||||
});
|
||||
const treeOid = writeTreeResult.stdout.trim();
|
||||
if (treeOid.length === 0) {
|
||||
return yield* new GitCommandError({
|
||||
operation,
|
||||
command: "git write-tree",
|
||||
cwd: input.cwd,
|
||||
detail: "git write-tree returned an empty tree oid.",
|
||||
});
|
||||
}
|
||||
|
||||
const message = `t3 checkpoint ref=${input.checkpointRef}`;
|
||||
const commitTreeResult = yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["commit-tree", treeOid, "-m", message],
|
||||
env: commitEnv,
|
||||
});
|
||||
const commitOid = commitTreeResult.stdout.trim();
|
||||
if (commitOid.length === 0) {
|
||||
return yield* new GitCommandError({
|
||||
operation,
|
||||
command: "git commit-tree",
|
||||
cwd: input.cwd,
|
||||
detail: "git commit-tree returned an empty commit oid.",
|
||||
});
|
||||
}
|
||||
const message = `t3 checkpoint ref=${input.checkpointRef}`;
|
||||
const commitTreeResult = yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["commit-tree", treeOid, "-m", message],
|
||||
env: commitEnv,
|
||||
});
|
||||
const commitOid = commitTreeResult.stdout.trim();
|
||||
if (commitOid.length === 0) {
|
||||
return yield* new GitCommandError({
|
||||
operation,
|
||||
command: "git commit-tree",
|
||||
cwd: input.cwd,
|
||||
detail: "git commit-tree returned an empty commit oid.",
|
||||
});
|
||||
}
|
||||
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["update-ref", input.checkpointRef, commitOid],
|
||||
});
|
||||
}),
|
||||
(tempDir) => fs.remove(tempDir, { recursive: true }),
|
||||
).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: (error) =>
|
||||
Effect.fail(
|
||||
new CheckpointInvariantError({
|
||||
operation: "CheckpointStore.captureCheckpoint",
|
||||
detail: "Failed to capture checkpoint.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
});
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["update-ref", input.checkpointRef, commitOid],
|
||||
});
|
||||
}),
|
||||
(tempDir) => fs.remove(tempDir, { recursive: true }),
|
||||
).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: (error) =>
|
||||
Effect.fail(
|
||||
new CheckpointInvariantError({
|
||||
operation: "CheckpointStore.captureCheckpoint",
|
||||
detail: "Failed to capture checkpoint.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
|
||||
resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
|
||||
Effect.map((commit) => commit !== null),
|
||||
);
|
||||
|
||||
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const operation = "CheckpointStore.restoreCheckpoint";
|
||||
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = Effect.fn(
|
||||
"restoreCheckpoint",
|
||||
)(function* (input) {
|
||||
const operation = "CheckpointStore.restoreCheckpoint";
|
||||
|
||||
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
|
||||
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
|
||||
|
||||
if (!commitOid && input.fallbackToHead === true) {
|
||||
commitOid = yield* resolveHeadCommit(input.cwd);
|
||||
}
|
||||
if (!commitOid && input.fallbackToHead === true) {
|
||||
commitOid = yield* resolveHeadCommit(input.cwd);
|
||||
}
|
||||
|
||||
if (!commitOid) {
|
||||
return false;
|
||||
}
|
||||
if (!commitOid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
|
||||
});
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["clean", "-fd", "--", "."],
|
||||
});
|
||||
|
||||
const headExists = yield* hasHeadCommit(input.cwd);
|
||||
if (headExists) {
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["reset", "--quiet", "--", "."],
|
||||
});
|
||||
}
|
||||
|
||||
return true;
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
|
||||
});
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["clean", "-fd", "--", "."],
|
||||
});
|
||||
|
||||
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const headExists = yield* hasHeadCommit(input.cwd);
|
||||
if (headExists) {
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["reset", "--quiet", "--", "."],
|
||||
});
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = Effect.fn("diffCheckpoints")(
|
||||
function* (input) {
|
||||
const operation = "CheckpointStore.diffCheckpoints";
|
||||
|
||||
let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
|
||||
@@ -247,24 +248,26 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
return result.stdout;
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const operation = "CheckpointStore.deleteCheckpointRefs";
|
||||
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = Effect.fn(
|
||||
"deleteCheckpointRefs",
|
||||
)(function* (input) {
|
||||
const operation = "CheckpointStore.deleteCheckpointRefs";
|
||||
|
||||
yield* Effect.forEach(
|
||||
input.checkpointRefs,
|
||||
(checkpointRef) =>
|
||||
git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["update-ref", "-d", checkpointRef],
|
||||
allowNonZeroExit: true,
|
||||
}),
|
||||
{ discard: true },
|
||||
);
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
input.checkpointRefs,
|
||||
(checkpointRef) =>
|
||||
git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["update-ref", "-d", checkpointRef],
|
||||
allowNonZeroExit: true,
|
||||
}),
|
||||
{ discard: true },
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
isGitRepository,
|
||||
|
||||
@@ -12,7 +12,7 @@ import type {
|
||||
OrchestrationGetTurnDiffInput,
|
||||
OrchestrationGetTurnDiffResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { CheckpointServiceError } from "../Errors.ts";
|
||||
@@ -43,7 +43,7 @@ export interface CheckpointDiffQueryShape {
|
||||
/**
|
||||
* CheckpointDiffQuery - Service tag for checkpoint diff queries.
|
||||
*/
|
||||
export class CheckpointDiffQuery extends ServiceMap.Service<
|
||||
export class CheckpointDiffQuery extends Context.Service<
|
||||
CheckpointDiffQuery,
|
||||
CheckpointDiffQueryShape
|
||||
>()("t3/checkpointing/Services/CheckpointDiffQuery") {}
|
||||
@@ -5,12 +5,12 @@
|
||||
* workspace thread timeline. It does not store user-facing checkpoint metadata
|
||||
* and does not coordinate provider conversation rollback.
|
||||
*
|
||||
* Uses Effect `ServiceMap.Service` for dependency injection and exposes typed
|
||||
* Uses Effect `Context.Service` for dependency injection and exposes typed
|
||||
* domain errors for checkpoint storage operations.
|
||||
*
|
||||
* @module CheckpointStore
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { CheckpointStoreError } from "../Errors.ts";
|
||||
@@ -95,6 +95,6 @@ export interface CheckpointStoreShape {
|
||||
/**
|
||||
* CheckpointStore - Service tag for checkpoint persistence and restore operations.
|
||||
*/
|
||||
export class CheckpointStore extends ServiceMap.Service<CheckpointStore, CheckpointStoreShape>()(
|
||||
export class CheckpointStore extends Context.Service<CheckpointStore, CheckpointStoreShape>()(
|
||||
"t3/checkpointing/Services/CheckpointStore",
|
||||
) {}
|
||||
@@ -4,7 +4,7 @@ import { CheckpointRef, ProjectId, type ThreadId } from "@t3tools/contracts";
|
||||
export const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
|
||||
|
||||
export function checkpointRefForThreadTurn(threadId: ThreadId, turnCount: number): CheckpointRef {
|
||||
return CheckpointRef.makeUnsafe(
|
||||
return CheckpointRef.make(
|
||||
`${CHECKPOINT_REFS_PREFIX}/${Encoding.encodeBase64Url(threadId)}/turn/${turnCount}`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,528 @@
|
||||
import os from "node:os";
|
||||
|
||||
import { assert, expect, it } from "@effect/vitest";
|
||||
import { ConfigProvider, Effect, FileSystem, Layer, Option, Path } from "effect";
|
||||
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { deriveServerPaths } from "./config";
|
||||
import { resolveServerConfig } from "./cli";
|
||||
|
||||
it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
const defaultObservabilityConfig = {
|
||||
traceMinLevel: "Info",
|
||||
traceTimingEnabled: true,
|
||||
traceBatchWindowMs: 200,
|
||||
traceMaxBytes: 10 * 1024 * 1024,
|
||||
traceMaxFiles: 10,
|
||||
otlpTracesUrl: undefined,
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
otlpServiceName: "t3-server",
|
||||
} as const;
|
||||
|
||||
const openBootstrapFd = Effect.fn(function* (payload: Record<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("preserves explicit false CLI boolean flags over env and bootstrap values", () =>
|
||||
Effect.gen(function* () {
|
||||
const { join } = yield* Path.Path;
|
||||
const baseDir = join(os.tmpdir(), "t3-cli-config-false-flags");
|
||||
const fd = yield* openBootstrapFd({
|
||||
noBrowser: true,
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
||||
|
||||
const resolved = yield* resolveServerConfig(
|
||||
{
|
||||
mode: Option.some("web"),
|
||||
port: Option.some(8788),
|
||||
host: Option.some("127.0.0.1"),
|
||||
baseDir: Option.some(baseDir),
|
||||
cwd: Option.none(),
|
||||
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
|
||||
noBrowser: Option.some(false),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.some(false),
|
||||
logWebSocketEvents: Option.some(false),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
ConfigProvider.layer(
|
||||
ConfigProvider.fromEnv({
|
||||
env: {
|
||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
|
||||
T3CODE_LOG_WS_EVENTS: "true",
|
||||
},
|
||||
}),
|
||||
),
|
||||
NetService.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Info",
|
||||
...defaultObservabilityConfig,
|
||||
mode: "web",
|
||||
port: 8788,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
host: "127.0.0.1",
|
||||
staticDir: undefined,
|
||||
devUrl: new URL("http://127.0.0.1:4173"),
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses bootstrap envelope values as fallbacks when flags and env are absent", () =>
|
||||
Effect.gen(function* () {
|
||||
const { join } = yield* Path.Path;
|
||||
const baseDir = "/tmp/t3-bootstrap-home";
|
||||
const fd = yield* openBootstrapFd({
|
||||
mode: "desktop",
|
||||
port: 4888,
|
||||
host: "127.0.0.2",
|
||||
t3Home: baseDir,
|
||||
devUrl: "http://127.0.0.1:5173",
|
||||
noBrowser: true,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: true,
|
||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
||||
});
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
|
||||
|
||||
const resolved = yield* resolveServerConfig(
|
||||
{
|
||||
mode: Option.none(),
|
||||
port: Option.none(),
|
||||
host: Option.none(),
|
||||
baseDir: Option.none(),
|
||||
cwd: Option.none(),
|
||||
devUrl: Option.none(),
|
||||
noBrowser: Option.none(),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
ConfigProvider.layer(
|
||||
ConfigProvider.fromEnv({
|
||||
env: {
|
||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||
},
|
||||
}),
|
||||
),
|
||||
NetService.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Info",
|
||||
...defaultObservabilityConfig,
|
||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
||||
mode: "desktop",
|
||||
port: 4888,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
host: "127.0.0.2",
|
||||
staticDir: undefined,
|
||||
devUrl: new URL("http://127.0.0.1:5173"),
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
assert.equal(join(baseDir, "dev"), resolved.stateDir);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates derived runtime directories during config resolution", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-dirs-" });
|
||||
const customCwd = path.join(baseDir, "nested", "project");
|
||||
|
||||
const resolved = yield* resolveServerConfig(
|
||||
{
|
||||
mode: Option.some("desktop"),
|
||||
port: Option.some(4888),
|
||||
host: Option.none(),
|
||||
baseDir: Option.some(baseDir),
|
||||
cwd: Option.some(customCwd),
|
||||
devUrl: Option.some(new URL("http://127.0.0.1:5173")),
|
||||
noBrowser: Option.none(),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
|
||||
NetService.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
for (const directory of [
|
||||
customCwd,
|
||||
resolved.stateDir,
|
||||
resolved.logsDir,
|
||||
resolved.providerLogsDir,
|
||||
resolved.terminalLogsDir,
|
||||
resolved.attachmentsDir,
|
||||
resolved.worktreesDir,
|
||||
path.dirname(resolved.serverLogPath),
|
||||
path.dirname(resolved.serverTracePath),
|
||||
]) {
|
||||
expect(yield* fs.exists(directory)).toBe(true);
|
||||
}
|
||||
expect(resolved.cwd).toBe(path.resolve(customCwd));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("applies flag then env precedence over bootstrap envelope values", () =>
|
||||
Effect.gen(function* () {
|
||||
const { join } = yield* Path.Path;
|
||||
const baseDir = join(os.tmpdir(), "t3-cli-config-env-wins");
|
||||
const fd = yield* openBootstrapFd({
|
||||
mode: "desktop",
|
||||
port: 4888,
|
||||
host: "127.0.0.2",
|
||||
t3Home: "/tmp/t3-bootstrap-home",
|
||||
devUrl: "http://127.0.0.1:5173",
|
||||
noBrowser: false,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
});
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
||||
|
||||
const resolved = yield* resolveServerConfig(
|
||||
{
|
||||
mode: Option.none(),
|
||||
port: Option.some(8788),
|
||||
host: Option.some("127.0.0.1"),
|
||||
baseDir: Option.none(),
|
||||
cwd: Option.none(),
|
||||
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
|
||||
noBrowser: Option.none(),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
},
|
||||
Option.some("Debug"),
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
ConfigProvider.layer(
|
||||
ConfigProvider.fromEnv({
|
||||
env: {
|
||||
T3CODE_MODE: "web",
|
||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||
T3CODE_HOME: baseDir,
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
|
||||
T3CODE_LOG_WS_EVENTS: "true",
|
||||
},
|
||||
}),
|
||||
),
|
||||
NetService.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Debug",
|
||||
...defaultObservabilityConfig,
|
||||
mode: "web",
|
||||
port: 8788,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
host: "127.0.0.1",
|
||||
staticDir: undefined,
|
||||
devUrl: new URL("http://127.0.0.1:4173"),
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to persisted observability settings when env vars are absent", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-settings-" });
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
|
||||
yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
|
||||
yield* fs.writeFileString(
|
||||
derivedPaths.settingsPath,
|
||||
`${JSON.stringify({
|
||||
observability: {
|
||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
||||
},
|
||||
})}\n`,
|
||||
);
|
||||
|
||||
const resolved = yield* resolveServerConfig(
|
||||
{
|
||||
mode: Option.some("desktop"),
|
||||
port: Option.some(4888),
|
||||
host: Option.none(),
|
||||
baseDir: Option.some(baseDir),
|
||||
cwd: Option.none(),
|
||||
devUrl: Option.none(),
|
||||
noBrowser: Option.none(),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
|
||||
NetService.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(resolved.otlpTracesUrl).toBe("http://localhost:4318/v1/traces");
|
||||
expect(resolved.otlpMetricsUrl).toBe("http://localhost:4318/v1/metrics");
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Info",
|
||||
...defaultObservabilityConfig,
|
||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
||||
mode: "desktop",
|
||||
port: 4888,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
host: "127.0.0.1",
|
||||
staticDir: resolved.staticDir,
|
||||
devUrl: undefined,
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("forces noBrowser and disables auto-bootstrap for headless startup presentation", () =>
|
||||
Effect.gen(function* () {
|
||||
const { join } = yield* Path.Path;
|
||||
const baseDir = join(os.tmpdir(), "t3-cli-config-headless-base");
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
|
||||
|
||||
const resolved = yield* resolveServerConfig(
|
||||
{
|
||||
mode: Option.some("web"),
|
||||
port: Option.some(3773),
|
||||
host: Option.none(),
|
||||
baseDir: Option.some(baseDir),
|
||||
cwd: Option.none(),
|
||||
devUrl: Option.none(),
|
||||
noBrowser: Option.none(),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
{
|
||||
startupPresentation: "headless",
|
||||
},
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
ConfigProvider.layer(
|
||||
ConfigProvider.fromEnv({
|
||||
env: {
|
||||
T3CODE_NO_BROWSER: "false",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
|
||||
},
|
||||
}),
|
||||
),
|
||||
NetService.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Info",
|
||||
...defaultObservabilityConfig,
|
||||
mode: "web",
|
||||
port: 3773,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
host: undefined,
|
||||
staticDir: resolved.staticDir,
|
||||
devUrl: undefined,
|
||||
noBrowser: true,
|
||||
startupPresentation: "headless",
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,356 @@
|
||||
import * as NodeHttp from "node:http";
|
||||
import { mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as HttpRouter from "effect/unstable/http/HttpRouter";
|
||||
import * as HttpServer from "effect/unstable/http/HttpServer";
|
||||
import * as CliError from "effect/unstable/cli/CliError";
|
||||
import * as TestConsole from "effect/testing/TestConsole";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
|
||||
import { cli } from "./cli.ts";
|
||||
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";
|
||||
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
|
||||
import {
|
||||
orchestrationDispatchRouteLayer,
|
||||
orchestrationSnapshotRouteLayer,
|
||||
} from "./orchestration/http.ts";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
|
||||
import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";
|
||||
import {
|
||||
makePersistedServerRuntimeState,
|
||||
persistServerRuntimeState,
|
||||
} from "./serverRuntimeState.ts";
|
||||
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
|
||||
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
|
||||
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
|
||||
const runCli = (args: ReadonlyArray<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("accepts canonical --no-<flag> boolean negation", () =>
|
||||
runCliWithRuntime(["--no-log-websocket-events", "--version"]),
|
||||
);
|
||||
|
||||
it.effect("rejects invalid log-level casing before launching the server", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* 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
@@ -0,0 +1,88 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { DateTime } from "effect";
|
||||
|
||||
import {
|
||||
formatIssuedPairingCredential,
|
||||
formatIssuedSession,
|
||||
formatPairingCredentialList,
|
||||
formatSessionList,
|
||||
} from "./cliAuthFormat.ts";
|
||||
|
||||
it("formats issued pairing credentials with the secret and optional pair URL", () => {
|
||||
const output = formatIssuedPairingCredential(
|
||||
{
|
||||
id: "pairing-1",
|
||||
credential: "secret-pairing-token",
|
||||
role: "client",
|
||||
subject: "one-time-token",
|
||||
createdAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
|
||||
expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
|
||||
},
|
||||
{ baseUrl: "https://example.com", json: false },
|
||||
);
|
||||
|
||||
expect(output).toContain("secret-pairing-token");
|
||||
expect(output).toContain("https://example.com/pair#token=secret-pairing-token");
|
||||
});
|
||||
|
||||
it("formats pairing listings without exposing the secret token", () => {
|
||||
const output = formatPairingCredentialList(
|
||||
[
|
||||
{
|
||||
id: "pairing-1",
|
||||
credential: "secret-pairing-token",
|
||||
subject: "one-time-token",
|
||||
label: "Phone",
|
||||
role: "client",
|
||||
createdAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
|
||||
expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
|
||||
},
|
||||
],
|
||||
{ json: false },
|
||||
);
|
||||
|
||||
expect(output).toContain("pairing-1");
|
||||
expect(output).not.toContain("secret-pairing-token");
|
||||
});
|
||||
|
||||
it("formats issued sessions with the bearer token but omits tokens from listings", () => {
|
||||
const issuedOutput = formatIssuedSession(
|
||||
{
|
||||
sessionId: "session-1" as never,
|
||||
token: "secret-session-token",
|
||||
method: "bearer-session-token",
|
||||
role: "owner",
|
||||
subject: "cli-issued-session",
|
||||
client: {
|
||||
label: "deploy-bot",
|
||||
deviceType: "bot",
|
||||
},
|
||||
expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
|
||||
},
|
||||
{ json: false },
|
||||
);
|
||||
|
||||
const listedOutput = formatSessionList(
|
||||
[
|
||||
{
|
||||
sessionId: "session-1" as never,
|
||||
method: "bearer-session-token",
|
||||
role: "owner",
|
||||
subject: "cli-issued-session",
|
||||
client: {
|
||||
label: "deploy-bot",
|
||||
deviceType: "bot",
|
||||
},
|
||||
connected: false,
|
||||
current: false,
|
||||
issuedAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
|
||||
expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
|
||||
lastConnectedAt: null,
|
||||
},
|
||||
],
|
||||
{ json: false },
|
||||
);
|
||||
|
||||
expect(issuedOutput).toContain("secret-session-token");
|
||||
expect(listedOutput).not.toContain("secret-session-token");
|
||||
});
|
||||
@@ -0,0 +1,190 @@
|
||||
import type { AuthClientMetadata, AuthClientSession, AuthPairingLink } from "@t3tools/contracts";
|
||||
import { DateTime } from "effect";
|
||||
|
||||
import type { IssuedBearerSession, IssuedPairingLink } from "./auth/Services/AuthControlPlane.ts";
|
||||
|
||||
const newline = "\n";
|
||||
|
||||
function serializeOptionalFields(values: ReadonlyArray<string | null | undefined>) {
|
||||
return values.filter((value): value is string => typeof value === "string" && value.length > 0);
|
||||
}
|
||||
|
||||
function formatClientMetadata(metadata: AuthClientMetadata): string {
|
||||
const details = serializeOptionalFields([
|
||||
metadata.label,
|
||||
metadata.deviceType !== "unknown" ? metadata.deviceType : undefined,
|
||||
metadata.os,
|
||||
metadata.browser,
|
||||
metadata.ipAddress,
|
||||
]);
|
||||
return details.length > 0 ? details.join(" | ") : "unlabeled client";
|
||||
}
|
||||
|
||||
function toIsoString(value: DateTime.DateTime | DateTime.Utc): string {
|
||||
return DateTime.formatIso(DateTime.toUtc(value));
|
||||
}
|
||||
|
||||
export function formatIssuedPairingCredential(
|
||||
credential: IssuedPairingLink,
|
||||
options?: {
|
||||
readonly json?: boolean;
|
||||
readonly baseUrl?: string;
|
||||
},
|
||||
): string {
|
||||
const pairUrl =
|
||||
options?.baseUrl != null && options.baseUrl.length > 0
|
||||
? (() => {
|
||||
const url = new URL("/pair", options.baseUrl);
|
||||
url.searchParams.delete("token");
|
||||
url.hash = new URLSearchParams([["token", credential.credential]]).toString();
|
||||
return url.toString();
|
||||
})()
|
||||
: undefined;
|
||||
|
||||
if (options?.json) {
|
||||
return `${JSON.stringify(
|
||||
{
|
||||
id: credential.id,
|
||||
credential: credential.credential,
|
||||
...(credential.label ? { label: credential.label } : {}),
|
||||
role: credential.role,
|
||||
expiresAt: toIsoString(credential.expiresAt),
|
||||
...(pairUrl ? { pairUrl } : {}),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}${newline}`;
|
||||
}
|
||||
|
||||
return (
|
||||
[
|
||||
`Issued client pairing token ${credential.id}.`,
|
||||
`Token: ${credential.credential}`,
|
||||
...(pairUrl ? [`Pair URL: ${pairUrl}`] : []),
|
||||
`Expires at: ${credential.expiresAt}`,
|
||||
].join(newline) + newline
|
||||
);
|
||||
}
|
||||
|
||||
export function formatPairingCredentialList(
|
||||
credentials: ReadonlyArray<AuthPairingLink>,
|
||||
options?: {
|
||||
readonly json?: boolean;
|
||||
},
|
||||
): string {
|
||||
if (options?.json) {
|
||||
return `${JSON.stringify(
|
||||
credentials.map((credential) => ({
|
||||
id: credential.id,
|
||||
...(credential.label ? { label: credential.label } : {}),
|
||||
role: credential.role,
|
||||
createdAt: toIsoString(credential.createdAt),
|
||||
expiresAt: toIsoString(credential.expiresAt),
|
||||
})),
|
||||
null,
|
||||
2,
|
||||
)}${newline}`;
|
||||
}
|
||||
|
||||
if (credentials.length === 0) {
|
||||
return `No active pairing credentials.${newline}`;
|
||||
}
|
||||
|
||||
return (
|
||||
credentials
|
||||
.map((credential) =>
|
||||
[
|
||||
`${credential.id}${credential.label ? ` (${credential.label})` : ""}`,
|
||||
` role: ${credential.role}`,
|
||||
` created: ${toIsoString(credential.createdAt)}`,
|
||||
` expires: ${toIsoString(credential.expiresAt)}`,
|
||||
].join(newline),
|
||||
)
|
||||
.join(`${newline}${newline}`) + newline
|
||||
);
|
||||
}
|
||||
|
||||
export function formatIssuedSession(
|
||||
session: IssuedBearerSession,
|
||||
options?: {
|
||||
readonly json?: boolean;
|
||||
readonly tokenOnly?: boolean;
|
||||
},
|
||||
): string {
|
||||
if (options?.tokenOnly) {
|
||||
return `${session.token}${newline}`;
|
||||
}
|
||||
|
||||
if (options?.json) {
|
||||
return `${JSON.stringify(
|
||||
{
|
||||
sessionId: session.sessionId,
|
||||
token: session.token,
|
||||
method: session.method,
|
||||
role: session.role,
|
||||
subject: session.subject,
|
||||
client: session.client,
|
||||
expiresAt: toIsoString(session.expiresAt),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}${newline}`;
|
||||
}
|
||||
|
||||
return (
|
||||
[
|
||||
`Issued ${session.role} bearer session ${session.sessionId}.`,
|
||||
`Token: ${session.token}`,
|
||||
`Subject: ${session.subject}`,
|
||||
`Client: ${formatClientMetadata(session.client)}`,
|
||||
`Expires at: ${toIsoString(session.expiresAt)}`,
|
||||
].join(newline) + newline
|
||||
);
|
||||
}
|
||||
|
||||
export function formatSessionList(
|
||||
sessions: ReadonlyArray<AuthClientSession>,
|
||||
options?: {
|
||||
readonly json?: boolean;
|
||||
},
|
||||
): string {
|
||||
if (options?.json) {
|
||||
return `${JSON.stringify(
|
||||
sessions.map((session) => ({
|
||||
sessionId: session.sessionId,
|
||||
method: session.method,
|
||||
role: session.role,
|
||||
subject: session.subject,
|
||||
client: session.client,
|
||||
connected: session.connected,
|
||||
issuedAt: toIsoString(session.issuedAt),
|
||||
expiresAt: toIsoString(session.expiresAt),
|
||||
lastConnectedAt: session.lastConnectedAt ? toIsoString(session.lastConnectedAt) : null,
|
||||
})),
|
||||
null,
|
||||
2,
|
||||
)}${newline}`;
|
||||
}
|
||||
|
||||
if (sessions.length === 0) {
|
||||
return `No active sessions.${newline}`;
|
||||
}
|
||||
|
||||
return (
|
||||
sessions
|
||||
.map((session) =>
|
||||
[
|
||||
`${session.sessionId} [${session.role}]${session.connected ? " connected" : ""}`,
|
||||
` method: ${session.method}`,
|
||||
` subject: ${session.subject}`,
|
||||
` client: ${formatClientMetadata(session.client)}`,
|
||||
` issued: ${toIsoString(session.issuedAt)}`,
|
||||
` last connected: ${
|
||||
session.lastConnectedAt ? toIsoString(session.lastConnectedAt) : "never"
|
||||
}`,
|
||||
` expires: ${toIsoString(session.expiresAt)}`,
|
||||
].join(newline),
|
||||
)
|
||||
.join(`${newline}${newline}`) + newline
|
||||
);
|
||||
}
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
resolveCodexModelForAccount,
|
||||
} from "./codexAppServerManager";
|
||||
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
|
||||
|
||||
function createSendTurnHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
@@ -111,9 +111,9 @@ function createPendingUserInputHarness() {
|
||||
},
|
||||
pendingUserInputs: new Map([
|
||||
[
|
||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
ApprovalRequestId.make("req-user-input-1"),
|
||||
{
|
||||
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
requestId: ApprovalRequestId.make("req-user-input-1"),
|
||||
jsonRpcId: 42,
|
||||
threadId: asThreadId("thread_1"),
|
||||
},
|
||||
@@ -207,6 +207,42 @@ describe("classifyCodexStderrLine", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("process stderr events", () => {
|
||||
it("emits classified stderr lines as notifications", () => {
|
||||
const manager = new CodexAppServerManager();
|
||||
const emitEvent = vi
|
||||
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
|
||||
.mockImplementation(() => {});
|
||||
|
||||
(
|
||||
manager as unknown as {
|
||||
emitNotificationEvent: (
|
||||
context: { session: { threadId: ThreadId } },
|
||||
method: string,
|
||||
message: string,
|
||||
) => void;
|
||||
}
|
||||
).emitNotificationEvent(
|
||||
{
|
||||
session: {
|
||||
threadId: asThreadId("thread-1"),
|
||||
},
|
||||
},
|
||||
"process/stderr",
|
||||
"fatal: permission denied",
|
||||
);
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
kind: "notification",
|
||||
method: "process/stderr",
|
||||
threadId: "thread-1",
|
||||
message: "fatal: permission denied",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeCodexModelSlug", () => {
|
||||
it("maps 5.3 aliases to gpt-5.3-codex", () => {
|
||||
expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
|
||||
@@ -274,7 +310,7 @@ describe("readCodexAccountSnapshot", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps spark enabled for api key accounts", () => {
|
||||
it("disables spark for api key accounts", () => {
|
||||
expect(
|
||||
readCodexAccountSnapshot({
|
||||
type: "apiKey",
|
||||
@@ -282,7 +318,20 @@ describe("readCodexAccountSnapshot", () => {
|
||||
).toEqual({
|
||||
type: "apiKey",
|
||||
planType: null,
|
||||
sparkEnabled: true,
|
||||
sparkEnabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("disables spark for unknown chatgpt plans", () => {
|
||||
expect(
|
||||
readCodexAccountSnapshot({
|
||||
type: "chatgpt",
|
||||
email: "[email protected]",
|
||||
}),
|
||||
).toEqual({
|
||||
type: "chatgpt",
|
||||
planType: "unknown",
|
||||
sparkEnabled: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -307,6 +356,16 @@ describe("resolveCodexModelForAccount", () => {
|
||||
}),
|
||||
).toBe("gpt-5.3-codex-spark");
|
||||
});
|
||||
|
||||
it("falls back from spark to default for api key auth", () => {
|
||||
expect(
|
||||
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
|
||||
type: "apiKey",
|
||||
planType: null,
|
||||
sparkEnabled: false,
|
||||
}),
|
||||
).toBe("gpt-5.3-codex");
|
||||
});
|
||||
});
|
||||
|
||||
describe("startSession", () => {
|
||||
@@ -342,6 +401,7 @@ describe("startSession", () => {
|
||||
manager.startSession({
|
||||
threadId: asThreadId("thread-1"),
|
||||
provider: "codex",
|
||||
binaryPath: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
).rejects.toThrow("cwd missing");
|
||||
@@ -390,6 +450,7 @@ describe("startSession", () => {
|
||||
manager.startSession({
|
||||
threadId: asThreadId("thread-1"),
|
||||
provider: "codex",
|
||||
binaryPath: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
@@ -682,7 +743,7 @@ describe("respondToUserInput", () => {
|
||||
|
||||
await manager.respondToUserInput(
|
||||
asThreadId("thread_1"),
|
||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
ApprovalRequestId.make("req-user-input-1"),
|
||||
{
|
||||
scope: "All request methods",
|
||||
compat: "Keep current envelope",
|
||||
@@ -719,7 +780,7 @@ describe("respondToUserInput", () => {
|
||||
|
||||
await manager.respondToUserInput(
|
||||
asThreadId("thread_1"),
|
||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
ApprovalRequestId.make("req-user-input-1"),
|
||||
{
|
||||
scope: [],
|
||||
},
|
||||
@@ -948,12 +1009,8 @@ describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume"
|
||||
provider: "codex",
|
||||
cwd: workspaceDir,
|
||||
runtimeMode: "full-access",
|
||||
providerOptions: {
|
||||
codex: {
|
||||
...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
|
||||
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
||||
},
|
||||
},
|
||||
binaryPath: process.env.CODEX_BINARY_PATH!,
|
||||
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
||||
});
|
||||
|
||||
const firstTurn = await manager.sendTurn({
|
||||
@@ -983,12 +1040,8 @@ describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume"
|
||||
cwd: workspaceDir,
|
||||
runtimeMode: "approval-required",
|
||||
resumeCursor: firstSession.resumeCursor,
|
||||
providerOptions: {
|
||||
codex: {
|
||||
...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
|
||||
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
||||
},
|
||||
},
|
||||
binaryPath: process.env.CODEX_BINARY_PATH!,
|
||||
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
||||
});
|
||||
|
||||
expect(resumedSession.threadId).toBe(originalThreadId);
|
||||
|
||||
@@ -14,19 +14,27 @@ import {
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderEvent,
|
||||
type ProviderSession,
|
||||
type ProviderSessionStartInput,
|
||||
type ProviderTurnStartResult,
|
||||
RuntimeMode,
|
||||
ProviderInteractionMode,
|
||||
} from "@t3tools/contracts";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { Effect, ServiceMap } from "effect";
|
||||
import { Effect, Context } from "effect";
|
||||
|
||||
import {
|
||||
formatCodexCliUpgradeMessage,
|
||||
isCodexCliVersionSupported,
|
||||
parseCodexCliVersion,
|
||||
} from "./provider/codexCliVersion";
|
||||
import {
|
||||
readCodexAccountSnapshot,
|
||||
resolveCodexModelForAccount,
|
||||
type CodexAccountSnapshot,
|
||||
} from "./provider/codexAccount";
|
||||
import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer";
|
||||
|
||||
export { buildCodexInitializeParams } from "./provider/codexAppServer";
|
||||
export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount";
|
||||
|
||||
type PendingRequestKey = string;
|
||||
|
||||
@@ -97,23 +105,6 @@ interface JsonRpcNotification {
|
||||
params?: unknown;
|
||||
}
|
||||
|
||||
type CodexPlanType =
|
||||
| "free"
|
||||
| "go"
|
||||
| "plus"
|
||||
| "pro"
|
||||
| "team"
|
||||
| "business"
|
||||
| "enterprise"
|
||||
| "edu"
|
||||
| "unknown";
|
||||
|
||||
interface CodexAccountSnapshot {
|
||||
readonly type: "apiKey" | "chatgpt" | "unknown";
|
||||
readonly planType: CodexPlanType | null;
|
||||
readonly sparkEnabled: boolean;
|
||||
}
|
||||
|
||||
export interface CodexAppServerSendTurnInput {
|
||||
readonly threadId: ThreadId;
|
||||
readonly input?: string;
|
||||
@@ -131,7 +122,8 @@ export interface CodexAppServerStartSessionInput {
|
||||
readonly model?: string;
|
||||
readonly serviceTier?: string;
|
||||
readonly resumeCursor?: unknown;
|
||||
readonly providerOptions?: ProviderSessionStartInput["providerOptions"];
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
}
|
||||
|
||||
@@ -146,6 +138,7 @@ export interface CodexThreadSnapshot {
|
||||
}
|
||||
|
||||
const CODEX_VERSION_CHECK_TIMEOUT_MS = 4_000;
|
||||
const CODEX_THREAD_COMPACTION_TIMEOUT_MS = 60_000;
|
||||
|
||||
const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
|
||||
const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
|
||||
@@ -162,50 +155,6 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
|
||||
"unknown thread",
|
||||
"does not exist",
|
||||
];
|
||||
const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
|
||||
const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
|
||||
const CODEX_SPARK_DISABLED_PLAN_TYPES = new Set<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)
|
||||
|
||||
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.
|
||||
@@ -342,31 +291,26 @@ In Default mode, strongly prefer making reasonable assumptions and executing the
|
||||
</collaboration_mode>`;
|
||||
|
||||
function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
|
||||
readonly approvalPolicy: "on-request" | "never";
|
||||
readonly sandbox: "workspace-write" | "danger-full-access";
|
||||
readonly approvalPolicy: "untrusted" | "on-request" | "never";
|
||||
readonly sandbox: "read-only" | "workspace-write" | "danger-full-access";
|
||||
} {
|
||||
if (runtimeMode === "approval-required") {
|
||||
return {
|
||||
approvalPolicy: "on-request",
|
||||
sandbox: "workspace-write",
|
||||
};
|
||||
switch (runtimeMode) {
|
||||
case "approval-required":
|
||||
return {
|
||||
approvalPolicy: "untrusted",
|
||||
sandbox: "read-only",
|
||||
};
|
||||
case "auto-accept-edits":
|
||||
return {
|
||||
approvalPolicy: "on-request",
|
||||
sandbox: "workspace-write",
|
||||
};
|
||||
case "full-access":
|
||||
return {
|
||||
approvalPolicy: "never",
|
||||
sandbox: "danger-full-access",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
approvalPolicy: "never",
|
||||
sandbox: "danger-full-access",
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveCodexModelForAccount(
|
||||
model: string | undefined,
|
||||
account: CodexAccountSnapshot,
|
||||
): string | undefined {
|
||||
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
|
||||
return model;
|
||||
}
|
||||
|
||||
return CODEX_DEFAULT_MODEL;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -375,15 +319,7 @@ export function resolveCodexModelForAccount(
|
||||
* entire process tree instead.
|
||||
*/
|
||||
function killChildTree(child: ChildProcessWithoutNullStreams): void {
|
||||
if (process.platform === "win32" && child.pid !== undefined) {
|
||||
try {
|
||||
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
||||
return;
|
||||
} catch {
|
||||
// fallback to direct kill
|
||||
}
|
||||
}
|
||||
child.kill();
|
||||
killCodexChildProcess(child);
|
||||
}
|
||||
|
||||
export function normalizeCodexModelSlug(
|
||||
@@ -402,19 +338,6 @@ export function normalizeCodexModelSlug(
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function buildCodexInitializeParams() {
|
||||
return {
|
||||
clientInfo: {
|
||||
name: "t3code_desktop",
|
||||
title: "T3 Code Desktop",
|
||||
version: "0.1.0",
|
||||
},
|
||||
capabilities: {
|
||||
experimentalApi: true,
|
||||
},
|
||||
} as const;
|
||||
}
|
||||
|
||||
function buildCodexCollaborationMode(input: {
|
||||
readonly interactionMode?: "default" | "plan";
|
||||
readonly model?: string;
|
||||
@@ -517,7 +440,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
private readonly sessions = new Map<ThreadId, CodexSessionContext>();
|
||||
|
||||
private runPromise: (effect: Effect.Effect<unknown, never>) => Promise<unknown>;
|
||||
constructor(services?: ServiceMap.ServiceMap<never>) {
|
||||
constructor(services?: Context.Context<never>) {
|
||||
super();
|
||||
this.runPromise = services ? Effect.runPromiseWith(services) : Effect.runPromise;
|
||||
}
|
||||
@@ -541,9 +464,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const codexOptions = readCodexProviderOptions(input);
|
||||
const codexBinaryPath = codexOptions.binaryPath ?? "codex";
|
||||
const codexHomePath = codexOptions.homePath;
|
||||
const codexBinaryPath = input.binaryPath;
|
||||
const codexHomePath = input.homePath;
|
||||
this.assertSupportedCodexCliVersion({
|
||||
binaryPath: codexBinaryPath,
|
||||
cwd: resolvedCwd,
|
||||
@@ -719,7 +641,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
this.stopSession(threadId);
|
||||
} else {
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "error",
|
||||
provider: "codex",
|
||||
threadId,
|
||||
@@ -818,7 +740,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
if (!turnIdRaw) {
|
||||
throw new Error("turn/start response did not include a turn id.");
|
||||
}
|
||||
const turnId = TurnId.makeUnsafe(turnIdRaw);
|
||||
const turnId = TurnId.make(turnIdRaw);
|
||||
|
||||
this.updateSession(context, {
|
||||
status: "running",
|
||||
@@ -874,6 +796,60 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return this.parseThreadSnapshot("thread/read", response);
|
||||
}
|
||||
|
||||
async compactThread(threadId: ThreadId): Promise<CodexThreadSnapshot> {
|
||||
const context = this.requireSession(threadId);
|
||||
const providerThreadId = readResumeThreadId({
|
||||
threadId: context.session.threadId,
|
||||
runtimeMode: context.session.runtimeMode,
|
||||
resumeCursor: context.session.resumeCursor,
|
||||
});
|
||||
if (!providerThreadId) {
|
||||
throw new Error("Session is missing a provider resume thread id.");
|
||||
}
|
||||
|
||||
const compactionWait = {
|
||||
cleanup: () => undefined,
|
||||
};
|
||||
const waitForCompaction = new Promise<void>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
compactionWait.cleanup();
|
||||
reject(new Error("Timed out waiting for Codex thread compaction."));
|
||||
}, CODEX_THREAD_COMPACTION_TIMEOUT_MS);
|
||||
|
||||
const onEvent = (event: ProviderEvent) => {
|
||||
if (
|
||||
event.provider !== "codex" ||
|
||||
event.threadId !== context.session.threadId ||
|
||||
event.kind !== "notification"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (event.method === "thread/compacted") {
|
||||
compactionWait.cleanup();
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
|
||||
compactionWait.cleanup = () => {
|
||||
clearTimeout(timeout);
|
||||
this.off("event", onEvent);
|
||||
};
|
||||
|
||||
this.on("event", onEvent);
|
||||
});
|
||||
|
||||
try {
|
||||
await this.sendRequest(context, "thread/compact/start", {
|
||||
threadId: providerThreadId,
|
||||
});
|
||||
await waitForCompaction;
|
||||
} catch (error) {
|
||||
compactionWait.cleanup();
|
||||
throw error;
|
||||
}
|
||||
return this.readThread(threadId);
|
||||
}
|
||||
|
||||
async rollbackThread(threadId: ThreadId, numTurns: number): Promise<CodexThreadSnapshot> {
|
||||
const context = this.requireSession(threadId);
|
||||
const providerThreadId = readResumeThreadId({
|
||||
@@ -919,7 +895,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -958,7 +934,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1047,7 +1023,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
continue;
|
||||
}
|
||||
|
||||
this.emitErrorEvent(context, "process/stderr", classified.message);
|
||||
this.emitNotificationEvent(context, "process/stderr", classified.message);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1140,7 +1116,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
: undefined;
|
||||
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1213,7 +1189,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
const requestKind = this.requestKindForMethod(request.method);
|
||||
let requestId: ApprovalRequestId | undefined;
|
||||
if (requestKind) {
|
||||
requestId = ApprovalRequestId.makeUnsafe(randomUUID());
|
||||
requestId = ApprovalRequestId.make(randomUUID());
|
||||
const pendingRequest: PendingApprovalRequest = {
|
||||
requestId,
|
||||
jsonRpcId: request.id,
|
||||
@@ -1232,7 +1208,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
if (request.method === "item/tool/requestUserInput") {
|
||||
requestId = ApprovalRequestId.makeUnsafe(randomUUID());
|
||||
requestId = ApprovalRequestId.make(randomUUID());
|
||||
context.pendingUserInputs.set(requestId, {
|
||||
requestId,
|
||||
jsonRpcId: request.id,
|
||||
@@ -1243,7 +1219,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "request",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1333,7 +1309,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
|
||||
private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "session",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1345,7 +1321,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
|
||||
private emitErrorEvent(context: CodexSessionContext, method: string, message: string): void {
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "error",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1355,6 +1331,22 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
}
|
||||
|
||||
private emitNotificationEvent(
|
||||
context: CodexSessionContext,
|
||||
method: string,
|
||||
message: string,
|
||||
): void {
|
||||
this.emitEvent({
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method,
|
||||
message,
|
||||
});
|
||||
}
|
||||
|
||||
private emitEvent(event: ProviderEvent): void {
|
||||
this.emit("event", event);
|
||||
}
|
||||
@@ -1404,7 +1396,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
const turns = turnsRaw.map((turnValue, index) => {
|
||||
const turn = this.readObject(turnValue);
|
||||
const turnIdRaw = this.readString(turn, "id") ?? `${threadIdRaw}:turn:${index + 1}`;
|
||||
const turnId = TurnId.makeUnsafe(turnIdRaw);
|
||||
const turnId = TurnId.make(turnIdRaw);
|
||||
const items = this.readArray(turn, "items") ?? [];
|
||||
return {
|
||||
id: turnId,
|
||||
@@ -1591,20 +1583,6 @@ function normalizeProviderThreadId(value: string | undefined): string | undefine
|
||||
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: {
|
||||
readonly binaryPath: string;
|
||||
readonly cwd: string;
|
||||
@@ -1658,14 +1636,18 @@ function readResumeCursorThreadId(resumeCursor: unknown): string | undefined {
|
||||
return typeof rawThreadId === "string" ? normalizeProviderThreadId(rawThreadId) : undefined;
|
||||
}
|
||||
|
||||
function readResumeThreadId(input: CodexAppServerStartSessionInput): string | undefined {
|
||||
function readResumeThreadId(input: {
|
||||
readonly resumeCursor?: unknown;
|
||||
readonly threadId?: ThreadId;
|
||||
readonly runtimeMode?: RuntimeMode;
|
||||
}): string | undefined {
|
||||
return readResumeCursorThreadId(input.resumeCursor);
|
||||
}
|
||||
|
||||
function toTurnId(value: string | undefined): TurnId | undefined {
|
||||
return brandIfNonEmpty(value, TurnId.makeUnsafe);
|
||||
return brandIfNonEmpty(value, TurnId.make);
|
||||
}
|
||||
|
||||
function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
|
||||
return brandIfNonEmpty(value, ProviderItemId.makeUnsafe);
|
||||
return brandIfNonEmpty(value, ProviderItemId.make);
|
||||
}
|
||||
@@ -6,11 +6,15 @@
|
||||
*
|
||||
* @module ServerConfig
|
||||
*/
|
||||
import { Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
|
||||
import { Effect, FileSystem, Layer, LogLevel, Path, Schema, Context } from "effect";
|
||||
|
||||
export const DEFAULT_PORT = 3773;
|
||||
|
||||
export type RuntimeMode = "web" | "desktop";
|
||||
export const RuntimeMode = Schema.Literals(["web", "desktop"]);
|
||||
export type RuntimeMode = typeof RuntimeMode.Type;
|
||||
|
||||
export const StartupPresentation = Schema.Literals(["browser", "headless"]);
|
||||
export type StartupPresentation = typeof StartupPresentation.Type;
|
||||
|
||||
/**
|
||||
* ServerDerivedPaths - Derived paths from the base directory.
|
||||
@@ -19,20 +23,35 @@ 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.
|
||||
*/
|
||||
export interface ServerConfigShape extends ServerDerivedPaths {
|
||||
readonly logLevel: LogLevel.LogLevel;
|
||||
readonly traceMinLevel: LogLevel.LogLevel;
|
||||
readonly traceTimingEnabled: boolean;
|
||||
readonly traceBatchWindowMs: number;
|
||||
readonly traceMaxBytes: number;
|
||||
readonly traceMaxFiles: number;
|
||||
readonly otlpTracesUrl: string | undefined;
|
||||
readonly otlpMetricsUrl: string | undefined;
|
||||
readonly otlpExportIntervalMs: number;
|
||||
readonly otlpServiceName: string;
|
||||
readonly mode: RuntimeMode;
|
||||
readonly port: number;
|
||||
readonly host: string | undefined;
|
||||
@@ -41,7 +60,8 @@ export interface ServerConfigShape extends ServerDerivedPaths {
|
||||
readonly staticDir: string | undefined;
|
||||
readonly devUrl: URL | undefined;
|
||||
readonly noBrowser: boolean;
|
||||
readonly authToken: string | undefined;
|
||||
readonly startupPresentation: StartupPresentation;
|
||||
readonly desktopBootstrapToken: string | undefined;
|
||||
readonly autoBootstrapProjectFromCwd: boolean;
|
||||
readonly logWebSocketEvents: boolean;
|
||||
}
|
||||
@@ -60,21 +80,47 @@ export const deriveServerPaths = Effect.fn(function* (
|
||||
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.
|
||||
*/
|
||||
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
|
||||
export class ServerConfig extends Context.Service<ServerConfig, ServerConfigShape>()(
|
||||
"t3/config/ServerConfig",
|
||||
) {
|
||||
static readonly layerTest = (cwd: string, baseDirOrPrefix: string | { prefix: string }) =>
|
||||
@@ -89,12 +135,19 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS
|
||||
? baseDirOrPrefix
|
||||
: yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
|
||||
|
||||
yield* fs.makeDirectory(derivedPaths.stateDir, { recursive: true });
|
||||
yield* fs.makeDirectory(derivedPaths.logsDir, { recursive: true });
|
||||
yield* fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true });
|
||||
yield* ensureServerDirectories(derivedPaths);
|
||||
|
||||
return {
|
||||
logLevel: "Error",
|
||||
traceMinLevel: "Info",
|
||||
traceTimingEnabled: true,
|
||||
traceBatchWindowMs: 200,
|
||||
traceMaxBytes: 10 * 1024 * 1024,
|
||||
traceMaxFiles: 10,
|
||||
otlpTracesUrl: undefined,
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
otlpServiceName: "t3-server",
|
||||
cwd,
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
@@ -103,10 +156,11 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS
|
||||
logWebSocketEvents: false,
|
||||
port: 0,
|
||||
host: undefined,
|
||||
authToken: undefined,
|
||||
desktopBootstrapToken: undefined,
|
||||
staticDir: undefined,
|
||||
devUrl,
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
} satisfies ServerConfigShape;
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import * as nodePath from "node:path";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Effect, Exit, FileSystem, Layer, PlatformError } from "effect";
|
||||
|
||||
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "../../config.ts";
|
||||
import { ServerEnvironment } from "../Services/ServerEnvironment.ts";
|
||||
import { ServerEnvironmentLive } from "./ServerEnvironment.ts";
|
||||
|
||||
const makeServerEnvironmentLayer = (baseDir: string) =>
|
||||
ServerEnvironmentLive.pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
|
||||
|
||||
const makeServerConfig = Effect.fn(function* (baseDir: string) {
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
|
||||
|
||||
return {
|
||||
...derivedPaths,
|
||||
logLevel: "Error",
|
||||
traceMinLevel: "Info",
|
||||
traceTimingEnabled: true,
|
||||
traceBatchWindowMs: 200,
|
||||
traceMaxBytes: 10 * 1024 * 1024,
|
||||
traceMaxFiles: 10,
|
||||
otlpTracesUrl: undefined,
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
otlpServiceName: "t3-server",
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
mode: "web",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
port: 0,
|
||||
host: undefined,
|
||||
desktopBootstrapToken: undefined,
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
} satisfies ServerConfigShape;
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
|
||||
it.effect("persists the environment id across service restarts", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-server-environment-test-",
|
||||
});
|
||||
|
||||
const first = yield* Effect.gen(function* () {
|
||||
const serverEnvironment = yield* ServerEnvironment;
|
||||
return yield* serverEnvironment.getDescriptor;
|
||||
}).pipe(Effect.provide(makeServerEnvironmentLayer(baseDir)));
|
||||
const second = yield* Effect.gen(function* () {
|
||||
const serverEnvironment = yield* ServerEnvironment;
|
||||
return yield* serverEnvironment.getDescriptor;
|
||||
}).pipe(Effect.provide(makeServerEnvironmentLayer(baseDir)));
|
||||
|
||||
expect(first.environmentId).toBe(second.environmentId);
|
||||
expect(second.capabilities.repositoryIdentity).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails instead of overwriting a persisted id when reading the file errors", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-server-environment-read-error-test-",
|
||||
});
|
||||
const serverConfig = yield* makeServerConfig(baseDir);
|
||||
const environmentIdPath = serverConfig.environmentIdPath;
|
||||
yield* fileSystem.makeDirectory(nodePath.dirname(environmentIdPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(environmentIdPath, "persisted-environment-id\n");
|
||||
const writeAttempts: string[] = [];
|
||||
const failingFileSystemLayer = FileSystem.layerNoop({
|
||||
exists: (path) => Effect.succeed(path === environmentIdPath),
|
||||
readFileString: (path) =>
|
||||
path === environmentIdPath
|
||||
? Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
description: "permission denied",
|
||||
pathOrDescriptor: path,
|
||||
}),
|
||||
)
|
||||
: Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
description: "not found",
|
||||
pathOrDescriptor: path,
|
||||
}),
|
||||
),
|
||||
writeFileString: (path) => {
|
||||
writeAttempts.push(path);
|
||||
return Effect.void;
|
||||
},
|
||||
});
|
||||
|
||||
const exit = yield* Effect.gen(function* () {
|
||||
const serverEnvironment = yield* ServerEnvironment;
|
||||
return yield* serverEnvironment.getDescriptor;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
ServerEnvironmentLive.pipe(
|
||||
Layer.provide(
|
||||
Layer.merge(Layer.succeed(ServerConfig, serverConfig), failingFileSystemLayer),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.exit,
|
||||
);
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
expect(writeAttempts).toEqual([]);
|
||||
expect(yield* fileSystem.readFileString(environmentIdPath)).toBe(
|
||||
"persisted-environment-id\n",
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
|
||||
import { Effect, FileSystem, Layer, Path, Random } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/ServerEnvironment.ts";
|
||||
import { version } from "../../../package.json" with { type: "json" };
|
||||
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
|
||||
|
||||
function platformOs(): ExecutionEnvironmentDescriptor["platform"]["os"] {
|
||||
switch (process.platform) {
|
||||
case "darwin":
|
||||
return "darwin";
|
||||
case "linux":
|
||||
return "linux";
|
||||
case "win32":
|
||||
return "windows";
|
||||
default:
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
function platformArch(): ExecutionEnvironmentDescriptor["platform"]["arch"] {
|
||||
switch (process.arch) {
|
||||
case "arm64":
|
||||
return "arm64";
|
||||
case "x64":
|
||||
return "x64";
|
||||
default:
|
||||
return "other";
|
||||
}
|
||||
}
|
||||
|
||||
export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
|
||||
const readPersistedEnvironmentId = Effect.gen(function* () {
|
||||
const exists = yield* fileSystem
|
||||
.exists(serverConfig.environmentIdPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (!exists) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const raw = yield* fileSystem
|
||||
.readFileString(serverConfig.environmentIdPath)
|
||||
.pipe(Effect.map((value) => value.trim()));
|
||||
|
||||
return raw.length > 0 ? raw : null;
|
||||
});
|
||||
|
||||
const persistEnvironmentId = (value: string) =>
|
||||
fileSystem.writeFileString(serverConfig.environmentIdPath, `${value}\n`);
|
||||
|
||||
const environmentIdRaw = yield* Effect.gen(function* () {
|
||||
const persisted = yield* readPersistedEnvironmentId;
|
||||
if (persisted) {
|
||||
return persisted;
|
||||
}
|
||||
|
||||
const generated = yield* Random.nextUUIDv4;
|
||||
yield* persistEnvironmentId(generated);
|
||||
return generated;
|
||||
});
|
||||
|
||||
const environmentId = EnvironmentId.make(environmentIdRaw);
|
||||
const cwdBaseName = path.basename(serverConfig.cwd).trim();
|
||||
const label = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName,
|
||||
});
|
||||
|
||||
const descriptor: ExecutionEnvironmentDescriptor = {
|
||||
environmentId,
|
||||
label,
|
||||
platform: {
|
||||
os: platformOs(),
|
||||
arch: platformArch(),
|
||||
},
|
||||
serverVersion: version,
|
||||
capabilities: {
|
||||
repositoryIdentity: true,
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
getEnvironmentId: Effect.succeed(environmentId),
|
||||
getDescriptor: Effect.succeed(descriptor),
|
||||
} satisfies ServerEnvironmentShape;
|
||||
});
|
||||
|
||||
export const ServerEnvironmentLive = Layer.effect(ServerEnvironment, makeServerEnvironment());
|
||||
@@ -0,0 +1,150 @@
|
||||
import { afterEach, describe, expect, it } from "@effect/vitest";
|
||||
import { Effect, FileSystem } from "effect";
|
||||
import { vi } from "vitest";
|
||||
|
||||
vi.mock("../../processRunner.ts", () => ({
|
||||
runProcess: vi.fn(),
|
||||
}));
|
||||
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
|
||||
|
||||
const mockedRunProcess = vi.mocked(runProcess);
|
||||
const NoopFileSystemLayer = FileSystem.layerNoop({});
|
||||
|
||||
afterEach(() => {
|
||||
mockedRunProcess.mockReset();
|
||||
});
|
||||
|
||||
describe("resolveServerEnvironmentLabel", () => {
|
||||
it.effect("uses hostname fallback regardless of launch mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "win32",
|
||||
hostname: "macbook-pro",
|
||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||
|
||||
expect(result).toBe("macbook-pro");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers the macOS ComputerName", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: " Julius's MacBook Pro \n",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "darwin",
|
||||
hostname: "macbook-pro",
|
||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||
|
||||
expect(result).toBe("Julius's MacBook Pro");
|
||||
expect(mockedRunProcess).toHaveBeenCalledWith(
|
||||
"scutil",
|
||||
["--get", "ComputerName"],
|
||||
expect.objectContaining({ allowNonZeroExit: true }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers Linux PRETTY_HOSTNAME from machine-info", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "linux",
|
||||
hostname: "buildbox",
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
FileSystem.layerNoop({
|
||||
exists: (path) => Effect.succeed(path === "/etc/machine-info"),
|
||||
readFileString: (path) =>
|
||||
path === "/etc/machine-info"
|
||||
? Effect.succeed('PRETTY_HOSTNAME="Build Agent 01"\nICON_NAME="computer-vm"\n')
|
||||
: Effect.succeed(""),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(result).toBe("Build Agent 01");
|
||||
expect(mockedRunProcess).not.toHaveBeenCalled();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to hostnamectl pretty hostname on Linux", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: "CI Runner\n",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "linux",
|
||||
hostname: "runner-01",
|
||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||
|
||||
expect(result).toBe("CI Runner");
|
||||
expect(mockedRunProcess).toHaveBeenCalledWith(
|
||||
"hostnamectl",
|
||||
["--pretty"],
|
||||
expect.objectContaining({ allowNonZeroExit: true }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to the hostname when friendly labels are unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "win32",
|
||||
hostname: "JULIUS-LAPTOP",
|
||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||
|
||||
expect(result).toBe("JULIUS-LAPTOP");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to the hostname when the friendly-label command is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockRejectedValueOnce(new Error("spawn scutil ENOENT"));
|
||||
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "darwin",
|
||||
hostname: "macbook-pro",
|
||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||
|
||||
expect(result).toBe("macbook-pro");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to the cwd basename when the hostname is blank", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: " ",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "linux",
|
||||
hostname: " ",
|
||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||
|
||||
expect(result).toBe("t3code");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import * as OS from "node:os";
|
||||
|
||||
import { Effect, FileSystem } from "effect";
|
||||
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
|
||||
interface ResolveServerEnvironmentLabelInput {
|
||||
readonly cwdBaseName: string;
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly hostname?: string | null;
|
||||
}
|
||||
|
||||
function normalizeLabel(value: string | null | undefined): string | null {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed && trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function parseMachineInfoValue(raw: string, key: string): string | null {
|
||||
for (const line of raw.split(/\r?\n/g)) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.length === 0 || trimmed.startsWith("#") || !trimmed.startsWith(`${key}=`)) {
|
||||
continue;
|
||||
}
|
||||
const value = trimmed.slice(key.length + 1).trim();
|
||||
if (
|
||||
(value.startsWith('"') && value.endsWith('"')) ||
|
||||
(value.startsWith("'") && value.endsWith("'"))
|
||||
) {
|
||||
return normalizeLabel(value.slice(1, -1));
|
||||
}
|
||||
return normalizeLabel(value);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const readLinuxMachineInfo = Effect.fn("readLinuxMachineInfo")(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const exists = yield* fileSystem
|
||||
.exists("/etc/machine-info")
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (!exists) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return yield* fileSystem
|
||||
.readFileString("/etc/machine-info")
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
});
|
||||
|
||||
const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
) {
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
runProcess(command, args, {
|
||||
allowNonZeroExit: true,
|
||||
}),
|
||||
catch: () => null,
|
||||
}).pipe(Effect.orElseSucceed(() => null));
|
||||
|
||||
if (!result || result.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalizeLabel(result.stdout);
|
||||
});
|
||||
|
||||
const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function* (
|
||||
platform: NodeJS.Platform,
|
||||
) {
|
||||
if (platform === "darwin") {
|
||||
return yield* runFriendlyLabelCommand("scutil", ["--get", "ComputerName"]);
|
||||
}
|
||||
|
||||
if (platform === "linux") {
|
||||
const machineInfo = normalizeLabel(yield* readLinuxMachineInfo());
|
||||
if (machineInfo) {
|
||||
const prettyHostname = parseMachineInfoValue(machineInfo, "PRETTY_HOSTNAME");
|
||||
if (prettyHostname) {
|
||||
return prettyHostname;
|
||||
}
|
||||
}
|
||||
|
||||
return yield* runFriendlyLabelCommand("hostnamectl", ["--pretty"]);
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
export const resolveServerEnvironmentLabel = Effect.fn("resolveServerEnvironmentLabel")(function* (
|
||||
input: ResolveServerEnvironmentLabelInput,
|
||||
) {
|
||||
const platform = input.platform ?? process.platform;
|
||||
const friendlyHostLabel = yield* resolveFriendlyHostLabel(platform);
|
||||
if (friendlyHostLabel) {
|
||||
return friendlyHostLabel;
|
||||
}
|
||||
|
||||
const hostname = normalizeLabel(input.hostname ?? OS.hostname());
|
||||
if (hostname) {
|
||||
return hostname;
|
||||
}
|
||||
|
||||
return normalizeLabel(input.cwdBaseName) ?? "T3 environment";
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { EnvironmentId, ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export interface ServerEnvironmentShape {
|
||||
readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
|
||||
readonly getDescriptor: Effect.Effect<ExecutionEnvironmentDescriptor>;
|
||||
}
|
||||
|
||||
export class ServerEnvironment extends Context.Service<ServerEnvironment, ServerEnvironmentShape>()(
|
||||
"t3/environment/Services/ServerEnvironment",
|
||||
) {}
|
||||
@@ -1,67 +0,0 @@
|
||||
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;
|
||||
@@ -5,9 +5,12 @@ 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-",
|
||||
@@ -245,4 +248,62 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("generates thread titles through the Claude provider", () =>
|
||||
withFakeClaudeEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
structured_output: {
|
||||
title:
|
||||
' "Reconnect failures after restart because the session state does not recover" ',
|
||||
},
|
||||
}),
|
||||
stdinMustContain: "You write concise thread titles for coding conversations.",
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Please investigate reconnect failures after restarting the session.",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.title).toBe(
|
||||
sanitizeThreadTitle(
|
||||
'"Reconnect failures after restart because the session state does not recover"',
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>
|
||||
withFakeClaudeEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
structured_output: {
|
||||
title: ' """ """ ',
|
||||
},
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Name this thread.",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("New thread");
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -11,22 +11,27 @@ import { Effect, Layer, Option, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ClaudeModelSelection } from "@t3tools/contracts";
|
||||
import { normalizeClaudeModelOptions } from "@t3tools/shared/model";
|
||||
import { resolveApiModelId } from "@t3tools/shared/model";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "../Prompts.ts";
|
||||
import {
|
||||
normalizeCliError,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
toJsonSchemaObject,
|
||||
} from "../Utils.ts";
|
||||
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts";
|
||||
|
||||
const CLAUDE_TIMEOUT_MS = 180_000;
|
||||
|
||||
@@ -40,6 +45,7 @@ const ClaudeOutputEnvelope = Schema.Struct({
|
||||
|
||||
const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const serverSettingsService = yield* Effect.service(ServerSettingsService);
|
||||
|
||||
const readStreamAsString = <E>(
|
||||
operation: string,
|
||||
@@ -60,138 +66,141 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||
* Spawn the Claude CLI with structured JSON output and return the parsed,
|
||||
* schema-validated result.
|
||||
*/
|
||||
const runClaudeJson = <S extends Schema.Top>({
|
||||
const runClaudeJson = Effect.fn("runClaudeJson")(function* <S extends Schema.Top>({
|
||||
operation,
|
||||
cwd,
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
modelSelection,
|
||||
}: {
|
||||
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
modelSelection: ClaudeModelSelection;
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
|
||||
const normalizedOptions = normalizeClaudeModelOptions(
|
||||
modelSelection.model,
|
||||
modelSelection.options,
|
||||
);
|
||||
const settings = {
|
||||
...(typeof normalizedOptions?.thinking === "boolean"
|
||||
? { alwaysThinkingEnabled: normalizedOptions.thinking }
|
||||
: {}),
|
||||
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
|
||||
};
|
||||
}): 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 runClaudeCommand = Effect.gen(function* () {
|
||||
const command = ChildProcess.make(
|
||||
"claude",
|
||||
[
|
||||
"-p",
|
||||
"--output-format",
|
||||
"json",
|
||||
"--json-schema",
|
||||
jsonSchemaStr,
|
||||
"--model",
|
||||
modelSelection.model,
|
||||
...(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 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 child = yield* commandSpawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
readStreamAsString(operation, child.stdout),
|
||||
readStreamAsString(operation, child.stderr),
|
||||
child.exitCode.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
|
||||
normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
|
||||
),
|
||||
);
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
readStreamAsString(operation, child.stdout),
|
||||
readStreamAsString(operation, child.stderr),
|
||||
child.exitCode.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError(
|
||||
"claude",
|
||||
operation,
|
||||
cause,
|
||||
"Failed to read Claude CLI exit code",
|
||||
),
|
||||
),
|
||||
if (exitCode !== 0) {
|
||||
const stderrDetail = stderr.trim();
|
||||
const stdoutDetail = stdout.trim();
|
||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||
return yield* new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
detail.length > 0
|
||||
? `Claude CLI command failed: ${detail}`
|
||||
: `Claude CLI command failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
|
||||
return stdout;
|
||||
});
|
||||
|
||||
const rawStdout = yield* runClaudeCommand().pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (exitCode !== 0) {
|
||||
const stderrDetail = stderr.trim();
|
||||
const stdoutDetail = stdout.trim();
|
||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||
return yield* new TextGenerationError({
|
||||
const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
|
||||
rawStdout,
|
||||
).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
detail.length > 0
|
||||
? `Claude CLI command failed: ${detail}`
|
||||
: `Claude CLI command failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
|
||||
return stdout;
|
||||
});
|
||||
|
||||
const rawStdout = yield* runClaudeCommand.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
|
||||
),
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
detail: "Claude CLI returned unexpected output format.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
),
|
||||
);
|
||||
|
||||
const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
|
||||
rawStdout,
|
||||
).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Claude CLI returned unexpected output format.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Claude returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Claude returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TextGenerationShape methods
|
||||
@@ -291,10 +300,39 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||
};
|
||||
});
|
||||
|
||||
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
|
||||
"ClaudeTextGeneration.generateThreadTitle",
|
||||
)(function* (input) {
|
||||
const { prompt, outputSchema } = buildThreadTitlePrompt({
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "claudeAgent") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateThreadTitle",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runClaudeJson({
|
||||
operation: "generateThreadTitle",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
title: sanitizeThreadTitle(generated.title),
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
} satisfies TextGenerationShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -5,8 +5,9 @@ import { expect } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
const DEFAULT_TEST_MODEL_SELECTION = {
|
||||
provider: "codex" as const,
|
||||
@@ -14,6 +15,7 @@ const DEFAULT_TEST_MODEL_SELECTION = {
|
||||
};
|
||||
|
||||
const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-codex-text-generation-test-",
|
||||
@@ -22,7 +24,20 @@ const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
function makeFakeCodexBinary(dir: string) {
|
||||
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* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -35,12 +50,16 @@ function makeFakeCodexBinary(dir: string) {
|
||||
[
|
||||
"#!/bin/sh",
|
||||
'output_path=""',
|
||||
'seen_image="0"',
|
||||
'seen_fast_service_tier="0"',
|
||||
'seen_reasoning_effort=""',
|
||||
"while [ $# -gt 0 ]; do",
|
||||
' if [ "$1" = "--image" ]; then',
|
||||
" shift",
|
||||
' if [ -n "$1" ]; then',
|
||||
' seen_image="1"',
|
||||
" fi",
|
||||
" shift",
|
||||
" continue",
|
||||
" fi",
|
||||
' if [ "$1" = "--config" ]; then',
|
||||
@@ -53,55 +72,80 @@ function makeFakeCodexBinary(dir: string) {
|
||||
' seen_reasoning_effort="$1"',
|
||||
" ;;",
|
||||
" esac",
|
||||
" shift",
|
||||
" continue",
|
||||
" fi",
|
||||
' if [ "$1" = "--output-last-message" ]; then',
|
||||
" shift",
|
||||
' output_path="$1"',
|
||||
" shift",
|
||||
" continue",
|
||||
" fi",
|
||||
" shift",
|
||||
"done",
|
||||
'stdin_content="$(cat)"',
|
||||
'if [ "$T3_FAKE_CODEX_REQUIRE_IMAGE" = "1" ] && [ "$seen_image" != "1" ]; then',
|
||||
' printf "%s\\n" "missing --image input" >&2',
|
||||
" exit 2",
|
||||
"fi",
|
||||
'if [ "$T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER" = "1" ] && [ "$seen_fast_service_tier" != "1" ]; then',
|
||||
' printf "%s\\n" "missing fast service tier config" >&2',
|
||||
" exit 5",
|
||||
"fi",
|
||||
'if [ -n "$T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT" ] && [ "$seen_reasoning_effort" != "model_reasoning_effort=\\"$T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT\\"" ]; then',
|
||||
' printf "%s\\n" "unexpected reasoning effort config: $seen_reasoning_effort" >&2',
|
||||
" exit 6",
|
||||
"fi",
|
||||
'if [ "$T3_FAKE_CODEX_FORBID_REASONING_EFFORT" = "1" ] && [ -n "$seen_reasoning_effort" ]; then',
|
||||
' printf "%s\\n" "reasoning effort config should be omitted: $seen_reasoning_effort" >&2',
|
||||
" exit 7",
|
||||
"fi",
|
||||
'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",
|
||||
...(input.requireImage
|
||||
? [
|
||||
'if [ "$seen_image" != "1" ]; then',
|
||||
' 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',
|
||||
' 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=}"',
|
||||
" cat > \"$output_path\" <<'__T3CODE_FAKE_CODEX_OUTPUT__'",
|
||||
input.output,
|
||||
"__T3CODE_FAKE_CODEX_OUTPUT__",
|
||||
"fi",
|
||||
'exit "${T3_FAKE_CODEX_EXIT_CODE:-0}"',
|
||||
`exit ${input.exitCode ?? 0}`,
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* fs.chmod(codexPath, 0o755);
|
||||
return binDir;
|
||||
return codexPath;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -123,146 +167,29 @@ function withFakeCodexEnv<A, E, R>(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
|
||||
const binDir = yield* makeFakeCodexBinary(tempDir);
|
||||
const previousPath = process.env.PATH;
|
||||
const previousOutput = process.env.T3_FAKE_CODEX_OUTPUT_B64;
|
||||
const previousExitCode = process.env.T3_FAKE_CODEX_EXIT_CODE;
|
||||
const previousStderr = process.env.T3_FAKE_CODEX_STDERR;
|
||||
const previousRequireImage = process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||
const previousRequireFastServiceTier = process.env.T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER;
|
||||
const previousRequireReasoningEffort = process.env.T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT;
|
||||
const previousForbidReasoningEffort = process.env.T3_FAKE_CODEX_FORBID_REASONING_EFFORT;
|
||||
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.requireFastServiceTier) {
|
||||
process.env.T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER = "1";
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER;
|
||||
}
|
||||
|
||||
if (input.requireReasoningEffort !== undefined) {
|
||||
process.env.T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT = input.requireReasoningEffort;
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT;
|
||||
}
|
||||
|
||||
if (input.forbidReasoningEffort) {
|
||||
process.env.T3_FAKE_CODEX_FORBID_REASONING_EFFORT = "1";
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CODEX_FORBID_REASONING_EFFORT;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const previousSettings = yield* serverSettings.getSettings;
|
||||
yield* serverSettings.updateSettings({
|
||||
providers: {
|
||||
codex: {
|
||||
binaryPath: codexPath,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
previousPath,
|
||||
previousOutput,
|
||||
previousExitCode,
|
||||
previousStderr,
|
||||
previousRequireImage,
|
||||
previousRequireFastServiceTier,
|
||||
previousRequireReasoningEffort,
|
||||
previousForbidReasoningEffort,
|
||||
previousStdinMustContain,
|
||||
previousStdinMustNotContain,
|
||||
};
|
||||
return { serverSettings, previousBinaryPath: previousSettings.providers.codex.binaryPath };
|
||||
}),
|
||||
() => effect,
|
||||
(previous) =>
|
||||
Effect.sync(() => {
|
||||
process.env.PATH = previous.previousPath;
|
||||
|
||||
if (previous.previousOutput === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_OUTPUT_B64;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_OUTPUT_B64 = previous.previousOutput;
|
||||
}
|
||||
|
||||
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.previousRequireFastServiceTier === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER =
|
||||
previous.previousRequireFastServiceTier;
|
||||
}
|
||||
|
||||
if (previous.previousRequireReasoningEffort === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT =
|
||||
previous.previousRequireReasoningEffort;
|
||||
}
|
||||
|
||||
if (previous.previousForbidReasoningEffort === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_FORBID_REASONING_EFFORT;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_FORBID_REASONING_EFFORT =
|
||||
previous.previousForbidReasoningEffort;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}),
|
||||
({ serverSettings, previousBinaryPath }) =>
|
||||
serverSettings
|
||||
.updateSettings({
|
||||
providers: {
|
||||
codex: {
|
||||
binaryPath: previousBinaryPath,
|
||||
},
|
||||
},
|
||||
})
|
||||
.pipe(Effect.asVoid),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -431,6 +358,70 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("generates thread titles and trims them for sidebar use", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
title:
|
||||
' "Investigate websocket reconnect regressions after worktree restore" \nignored line',
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Please investigate websocket reconnect regressions after a worktree restore.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("Investigate websocket reconnect regressions aft...");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("falls back when thread title normalization becomes whitespace-only", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
title: ' """ """ ',
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Name this thread.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("New thread");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("trims whitespace exposed after quote removal in thread titles", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
title: ` "' hello world '" `,
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Name this thread.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("hello world");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("omits attachment metadata section when no attachments are provided", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
|
||||
@@ -4,14 +4,14 @@ import { Effect, FileSystem, Layer, Option, Path, Schema, Scope, Stream } from "
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { CodexModelSelection } from "@t3tools/contracts";
|
||||
import { normalizeCodexModelOptions } from "@t3tools/shared/model";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import {
|
||||
type BranchNameGenerationInput,
|
||||
type ThreadTitleGenerationResult,
|
||||
type TextGenerationShape,
|
||||
TextGeneration,
|
||||
} from "../Services/TextGeneration.ts";
|
||||
@@ -19,22 +19,27 @@ 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_TIMEOUT_MS = 180_000;
|
||||
|
||||
const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const serverSettingsService = yield* Effect.service(ServerSettingsService);
|
||||
|
||||
type MaterializedImageAttachments = {
|
||||
readonly imagePaths: ReadonlyArray<string>;
|
||||
@@ -80,40 +85,43 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
||||
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
const materializeImageAttachments = (
|
||||
_operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName",
|
||||
const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
|
||||
_operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle",
|
||||
attachments: BranchNameGenerationInput["attachments"],
|
||||
): Effect.Effect<MaterializedImageAttachments, TextGenerationError> =>
|
||||
Effect.gen(function* () {
|
||||
if (!attachments || attachments.length === 0) {
|
||||
return { imagePaths: [] };
|
||||
): Effect.fn.Return<MaterializedImageAttachments, TextGenerationError> {
|
||||
if (!attachments || attachments.length === 0) {
|
||||
return { imagePaths: [] };
|
||||
}
|
||||
|
||||
const imagePaths: string[] = [];
|
||||
for (const attachment of attachments) {
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const imagePaths: string[] = [];
|
||||
for (const attachment of attachments) {
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolvedPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
|
||||
continue;
|
||||
}
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(resolvedPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
continue;
|
||||
}
|
||||
imagePaths.push(resolvedPath);
|
||||
const resolvedPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
|
||||
continue;
|
||||
}
|
||||
return { imagePaths };
|
||||
});
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(resolvedPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
continue;
|
||||
}
|
||||
imagePaths.push(resolvedPath);
|
||||
}
|
||||
return { imagePaths };
|
||||
});
|
||||
|
||||
const runCodexJson = <S extends Schema.Top>({
|
||||
const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
|
||||
operation,
|
||||
cwd,
|
||||
prompt,
|
||||
@@ -122,136 +130,148 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
cleanupPaths = [],
|
||||
modelSelection,
|
||||
}: {
|
||||
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
imagePaths?: ReadonlyArray<string>;
|
||||
cleanupPaths?: ReadonlyArray<string>;
|
||||
modelSelection: CodexModelSelection;
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const schemaPath = yield* writeTempFile(
|
||||
operation,
|
||||
"codex-schema",
|
||||
JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
|
||||
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
||||
const schemaPath = yield* writeTempFile(
|
||||
operation,
|
||||
"codex-schema",
|
||||
JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
|
||||
);
|
||||
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
||||
|
||||
const codexSettings = yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => settings.providers.codex,
|
||||
).pipe(Effect.catch(() => Effect.undefined));
|
||||
|
||||
const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
|
||||
const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
|
||||
getCodexModelCapabilities(modelSelection.model),
|
||||
modelSelection.options,
|
||||
);
|
||||
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
||||
|
||||
const runCodexCommand = Effect.gen(function* () {
|
||||
const normalizedOptions = normalizeCodexModelOptions(
|
||||
const reasoningEffort =
|
||||
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
|
||||
const command = ChildProcess.make(
|
||||
codexSettings?.binaryPath || "codex",
|
||||
[
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
modelSelection.model,
|
||||
modelSelection.options,
|
||||
);
|
||||
const reasoningEffort =
|
||||
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
|
||||
const command = ChildProcess.make(
|
||||
"codex",
|
||||
[
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
modelSelection.model,
|
||||
"--config",
|
||||
`model_reasoning_effort="${reasoningEffort}"`,
|
||||
...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
outputPath,
|
||||
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
||||
"-",
|
||||
],
|
||||
{
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdin: {
|
||||
stream: Stream.encodeText(Stream.make(prompt)),
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const child = yield* commandSpawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
|
||||
),
|
||||
);
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
readStreamAsString(operation, child.stdout),
|
||||
readStreamAsString(operation, child.stderr),
|
||||
child.exitCode.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
if (exitCode !== 0) {
|
||||
const stderrDetail = stderr.trim();
|
||||
const stdoutDetail = stdout.trim();
|
||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||
return yield* new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
detail.length > 0
|
||||
? `Codex CLI command failed: ${detail}`
|
||||
: `Codex CLI command failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const cleanup = Effect.all(
|
||||
[schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
|
||||
"--config",
|
||||
`model_reasoning_effort="${reasoningEffort}"`,
|
||||
...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
outputPath,
|
||||
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
||||
"-",
|
||||
],
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
|
||||
},
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdin: {
|
||||
stream: Stream.encodeText(Stream.make(prompt)),
|
||||
},
|
||||
},
|
||||
).pipe(Effect.asVoid);
|
||||
);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
yield* runCodexCommand.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(CODEX_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
|
||||
),
|
||||
onSome: () => Effect.void,
|
||||
const child = yield* commandSpawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
|
||||
),
|
||||
);
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
readStreamAsString(operation, child.stdout),
|
||||
readStreamAsString(operation, child.stderr),
|
||||
child.exitCode.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
if (exitCode !== 0) {
|
||||
const stderrDetail = stderr.trim();
|
||||
const stdoutDetail = stdout.trim();
|
||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||
return yield* new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
detail.length > 0
|
||||
? `Codex CLI command failed: ${detail}`
|
||||
: `Codex CLI command failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const cleanup = Effect.all(
|
||||
[schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
yield* runCodexCommand().pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(CODEX_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
|
||||
),
|
||||
onSome: () => Effect.void,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* fileSystem.readFileString(outputPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Failed to read Codex output file.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Codex returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* fileSystem.readFileString(outputPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Failed to read Codex output file.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Codex returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.ensuring(cleanup));
|
||||
});
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.ensuring(cleanup));
|
||||
});
|
||||
|
||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
|
||||
"CodexTextGeneration.generateCommitMessage",
|
||||
@@ -352,10 +372,44 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
};
|
||||
});
|
||||
|
||||
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
|
||||
"CodexTextGeneration.generateThreadTitle",
|
||||
)(function* (input) {
|
||||
const { imagePaths } = yield* materializeImageAttachments(
|
||||
"generateThreadTitle",
|
||||
input.attachments,
|
||||
);
|
||||
const { prompt, outputSchema } = buildThreadTitlePrompt({
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "codex") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateThreadTitle",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runCodexJson({
|
||||
operation: "generateThreadTitle",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
imagePaths,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
title: sanitizeThreadTitle(generated.title),
|
||||
} satisfies ThreadTitleGenerationResult;
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
} satisfies TextGenerationShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import { describe, expect, vi } from "vitest";
|
||||
|
||||
import { GitCoreLive, makeGitCore } from "./GitCore.ts";
|
||||
import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";
|
||||
import { GitCommandError } from "../Errors.ts";
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
import { type ProcessRunResult, runProcess } from "../../processRunner.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
|
||||
@@ -59,6 +59,23 @@ function git(
|
||||
});
|
||||
}
|
||||
|
||||
function configureRemote(
|
||||
cwd: string,
|
||||
remoteName: string,
|
||||
remotePath: string,
|
||||
fetchNamespace: string,
|
||||
): Effect.Effect<string, GitCommandError, GitCore> {
|
||||
return Effect.gen(function* () {
|
||||
yield* git(cwd, ["config", `remote.${remoteName}.url`, remotePath]);
|
||||
return yield* git(cwd, [
|
||||
"config",
|
||||
"--replace-all",
|
||||
`remote.${remoteName}.fetch`,
|
||||
`+refs/heads/*:refs/remotes/${fetchNamespace}/*`,
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
function runShellCommand(input: {
|
||||
command: string;
|
||||
cwd: string;
|
||||
@@ -132,6 +149,19 @@ function commitWithDate(
|
||||
});
|
||||
}
|
||||
|
||||
function buildLargeText(lineCount = 20_000): string {
|
||||
return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`)
|
||||
.join("\n")
|
||||
.concat("\n");
|
||||
}
|
||||
|
||||
function splitNullSeparatedPaths(input: string): string[] {
|
||||
return input
|
||||
.split("\0")
|
||||
.map((value) => value.trim())
|
||||
.filter((value) => value.length > 0);
|
||||
}
|
||||
|
||||
// ── Tests ──
|
||||
|
||||
it.layer(TestLayer)("git integration", (it) => {
|
||||
@@ -175,6 +205,87 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("workspace helpers", () => {
|
||||
it.effect("filterIgnoredPaths chunks large path lists and preserves kept paths", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = "/virtual/repo";
|
||||
const relativePaths = Array.from({ length: 340 }, (_, index) => {
|
||||
const prefix = index % 3 === 0 ? "ignored" : "kept";
|
||||
return `${prefix}/segment-${String(index).padStart(4, "0")}/${"x".repeat(900)}.ts`;
|
||||
});
|
||||
const expectedPaths = relativePaths.filter(
|
||||
(relativePath) => !relativePath.startsWith("ignored/"),
|
||||
);
|
||||
|
||||
const seenChunks: string[][] = [];
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (
|
||||
input.args.join(" ") !==
|
||||
"-c core.fsmonitor=false -c core.untrackedCache=false check-ignore --no-index -z --stdin"
|
||||
) {
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "unexpected git command in chunking test",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const chunkPaths = splitNullSeparatedPaths(input.stdin ?? "");
|
||||
seenChunks.push(chunkPaths);
|
||||
const ignoredPaths = chunkPaths.filter((relativePath) =>
|
||||
relativePath.startsWith("ignored/"),
|
||||
);
|
||||
|
||||
return Effect.succeed({
|
||||
code: ignoredPaths.length > 0 ? 0 : 1,
|
||||
stdout: ignoredPaths.length > 0 ? `${ignoredPaths.join("\0")}\0` : "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
});
|
||||
|
||||
const result = yield* core.filterIgnoredPaths(cwd, relativePaths);
|
||||
|
||||
expect(seenChunks.length).toBeGreaterThan(1);
|
||||
expect(seenChunks.flat()).toEqual(relativePaths);
|
||||
expect(result).toEqual(expectedPaths);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("listWorkspaceFiles disables fsmonitor and untracked cache helpers", () =>
|
||||
Effect.gen(function* () {
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
expect(input.args).toEqual([
|
||||
"-c",
|
||||
"core.fsmonitor=false",
|
||||
"-c",
|
||||
"core.untrackedCache=false",
|
||||
"ls-files",
|
||||
"--cached",
|
||||
"--others",
|
||||
"--exclude-standard",
|
||||
"-z",
|
||||
]);
|
||||
return Effect.succeed({
|
||||
code: 0,
|
||||
stdout: "src/index.ts\0README.md\0",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
});
|
||||
|
||||
const result = yield* core.listWorkspaceFiles("/virtual/repo");
|
||||
expect(result.paths).toEqual(["src/index.ts", "README.md"]);
|
||||
expect(result.truncated).toBe(false);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── listGitBranches ──
|
||||
|
||||
describe("listGitBranches", () => {
|
||||
@@ -307,6 +418,94 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("paginates branch results and returns paging metadata", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const { initialBranch } = yield* initRepoWithCommit(tmp);
|
||||
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-a" });
|
||||
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-b" });
|
||||
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-c" });
|
||||
|
||||
const firstPage = yield* (yield* GitCore).listBranches({ cwd: tmp, limit: 2 });
|
||||
expect(firstPage.totalCount).toBe(4);
|
||||
expect(firstPage.nextCursor).toBe(2);
|
||||
expect(firstPage.branches.map((branch) => branch.name)).toEqual([
|
||||
initialBranch,
|
||||
"feature-a",
|
||||
]);
|
||||
|
||||
const secondPage = yield* (yield* GitCore).listBranches({
|
||||
cwd: tmp,
|
||||
cursor: firstPage.nextCursor ?? 0,
|
||||
limit: 2,
|
||||
});
|
||||
expect(secondPage.totalCount).toBe(4);
|
||||
expect(secondPage.nextCursor).toBeNull();
|
||||
expect(secondPage.branches.map((branch) => branch.name)).toEqual([
|
||||
"feature-b",
|
||||
"feature-c",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("parses separate branch names when column.ui is always enabled", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const { initialBranch } = yield* initRepoWithCommit(tmp);
|
||||
const createdBranchNames = [
|
||||
"go-bin",
|
||||
"copilot/rewrite-cli-in-go",
|
||||
"copilot/rewrite-cli-in-rust",
|
||||
] as const;
|
||||
for (const branchName of createdBranchNames) {
|
||||
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: branchName });
|
||||
}
|
||||
yield* git(tmp, ["config", "column.ui", "always"]);
|
||||
|
||||
const rawBranchOutput = yield* git(tmp, ["branch", "--no-color"], {
|
||||
...process.env,
|
||||
COLUMNS: "120",
|
||||
});
|
||||
expect(
|
||||
rawBranchOutput
|
||||
.split("\n")
|
||||
.some(
|
||||
(line) =>
|
||||
createdBranchNames.filter((branchName) => line.includes(branchName)).length >= 2,
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
const realGitCore = yield* GitCore;
|
||||
const core = yield* makeIsolatedGitCore((input) =>
|
||||
realGitCore.execute(
|
||||
input.args[0] === "branch"
|
||||
? {
|
||||
...input,
|
||||
env: { ...input.env, COLUMNS: "120" },
|
||||
}
|
||||
: input,
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* core.listBranches({ cwd: tmp });
|
||||
const localBranchNames = result.branches
|
||||
.filter((branch) => !branch.isRemote)
|
||||
.map((branch) => branch.name);
|
||||
|
||||
expect(localBranchNames).toHaveLength(4);
|
||||
expect(localBranchNames).toEqual(
|
||||
expect.arrayContaining([initialBranch, ...createdBranchNames]),
|
||||
);
|
||||
expect(
|
||||
localBranchNames.some(
|
||||
(branchName) =>
|
||||
createdBranchNames.filter((createdBranch) => branchName.includes(createdBranch))
|
||||
.length >= 2,
|
||||
),
|
||||
).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("isDefault is false when no remote exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
@@ -394,6 +593,41 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
expect(remoteBranch?.remoteName).toBe(remoteName);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"filters branch queries before pagination and dedupes origin refs with local matches",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const tmp = yield* makeTmpDir();
|
||||
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
const { initialBranch } = yield* initRepoWithCommit(tmp);
|
||||
yield* git(tmp, ["remote", "add", "origin", remote]);
|
||||
yield* git(tmp, ["push", "-u", "origin", initialBranch]);
|
||||
|
||||
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/demo" });
|
||||
yield* git(tmp, ["push", "-u", "origin", "feature/demo"]);
|
||||
|
||||
yield* git(tmp, ["checkout", "-b", "feature/remote-only"]);
|
||||
yield* git(tmp, ["push", "-u", "origin", "feature/remote-only"]);
|
||||
yield* git(tmp, ["checkout", initialBranch]);
|
||||
yield* git(tmp, ["branch", "-D", "feature/remote-only"]);
|
||||
|
||||
const result = yield* (yield* GitCore).listBranches({
|
||||
cwd: tmp,
|
||||
query: "feature/",
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
expect(result.totalCount).toBe(2);
|
||||
expect(result.nextCursor).toBeNull();
|
||||
expect(result.branches.map((branch) => branch.name)).toEqual([
|
||||
"feature/demo",
|
||||
"origin/feature/remote-only",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── checkoutGitBranch ──
|
||||
@@ -415,6 +649,9 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
|
||||
it.effect("refreshes upstream behind count after checkout when remote branch advanced", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* Effect.context<never>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
const clone = yield* makeTmpDir();
|
||||
@@ -448,17 +685,23 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
yield* (yield* GitCore).checkoutBranch({ cwd: source, branch: featureBranch });
|
||||
const core = yield* GitCore;
|
||||
yield* Effect.promise(() =>
|
||||
vi.waitFor(async () => {
|
||||
const details = await Effect.runPromise(core.statusDetails(source));
|
||||
expect(details.branch).toBe(featureBranch);
|
||||
expect(details.aheadCount).toBe(0);
|
||||
expect(details.behindCount).toBe(1);
|
||||
}),
|
||||
vi.waitFor(
|
||||
async () => {
|
||||
const details = await runPromise(core.statusDetails(source));
|
||||
expect(details.branch).toBe(featureBranch);
|
||||
expect(details.aheadCount).toBe(0);
|
||||
expect(details.behindCount).toBe(1);
|
||||
},
|
||||
{
|
||||
timeout: 10_000,
|
||||
interval: 100,
|
||||
},
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps checkout successful when upstream refresh fails", () =>
|
||||
it.effect("statusDetails remains successful when upstream refresh fails after checkout", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
@@ -483,7 +726,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
const realGitCore = yield* GitCore;
|
||||
let refreshFetchAttempts = 0;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (input.args[0] === "fetch") {
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
refreshFetchAttempts += 1;
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
@@ -497,16 +740,15 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
return realGitCore.execute(input);
|
||||
});
|
||||
yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
|
||||
yield* Effect.promise(() =>
|
||||
vi.waitFor(() => {
|
||||
expect(refreshFetchAttempts).toBe(1);
|
||||
}),
|
||||
);
|
||||
const status = yield* core.statusDetails(source);
|
||||
expect(refreshFetchAttempts).toBe(1);
|
||||
expect(status.branch).toBe(featureBranch);
|
||||
expect(status.upstreamRef).toBe(`origin/${featureBranch}`);
|
||||
expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refresh fetch is scoped to the checked out branch upstream refspec", () =>
|
||||
it.effect("defers upstream refresh until statusDetails is requested", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
@@ -528,76 +770,152 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
yield* git(source, ["checkout", defaultBranch]);
|
||||
|
||||
const realGitCore = yield* GitCore;
|
||||
let fetchArgs: readonly string[] | null = null;
|
||||
let refreshFetchAttempts = 0;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (input.args[0] === "fetch") {
|
||||
fetchArgs = [...input.args];
|
||||
return Effect.succeed({ code: 0, stdout: "", stderr: "" });
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
refreshFetchAttempts += 1;
|
||||
return Effect.succeed({
|
||||
code: 0,
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
}
|
||||
return realGitCore.execute(input);
|
||||
});
|
||||
yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
|
||||
yield* Effect.promise(() =>
|
||||
vi.waitFor(() => {
|
||||
expect(fetchArgs).not.toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
|
||||
expect(fetchArgs).toEqual([
|
||||
"fetch",
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
"origin",
|
||||
`+refs/heads/${featureBranch}:refs/remotes/origin/${featureBranch}`,
|
||||
]);
|
||||
yield* Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, 50)));
|
||||
expect(refreshFetchAttempts).toBe(0);
|
||||
const status = yield* core.statusDetails(source);
|
||||
expect(status.branch).toBe(featureBranch);
|
||||
expect(refreshFetchAttempts).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns checkout result before background upstream refresh completes", () =>
|
||||
it.effect("shares upstream refreshes across worktrees that use the same git common dir", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
const ok = (stdout = "") =>
|
||||
Effect.succeed({
|
||||
code: 0,
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
|
||||
yield* initRepoWithCommit(source);
|
||||
const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
yield* git(source, ["remote", "add", "origin", remote]);
|
||||
yield* git(source, ["push", "-u", "origin", defaultBranch]);
|
||||
|
||||
const featureBranch = "feature/background-refresh";
|
||||
yield* git(source, ["checkout", "-b", featureBranch]);
|
||||
yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n");
|
||||
yield* git(source, ["add", "feature.txt"]);
|
||||
yield* git(source, ["commit", "-m", "feature base"]);
|
||||
yield* git(source, ["push", "-u", "origin", featureBranch]);
|
||||
yield* git(source, ["checkout", defaultBranch]);
|
||||
|
||||
const realGitCore = yield* GitCore;
|
||||
let fetchStarted = false;
|
||||
let releaseFetch!: () => void;
|
||||
const waitForReleasePromise = new Promise<void>((resolve) => {
|
||||
releaseFetch = resolve;
|
||||
});
|
||||
let fetchCount = 0;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (input.args[0] === "fetch") {
|
||||
fetchStarted = true;
|
||||
return Effect.promise(() =>
|
||||
waitForReleasePromise.then(() => ({ code: 0, stdout: "", stderr: "" })),
|
||||
if (
|
||||
input.args[0] === "rev-parse" &&
|
||||
input.args[1] === "--abbrev-ref" &&
|
||||
input.args[2] === "--symbolic-full-name" &&
|
||||
input.args[3] === "@{upstream}"
|
||||
) {
|
||||
return ok("origin/main\n");
|
||||
}
|
||||
if (input.args[0] === "remote") {
|
||||
return ok("origin\n");
|
||||
}
|
||||
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
|
||||
return ok("/repo/.git\n");
|
||||
}
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
fetchCount += 1;
|
||||
expect(input.cwd).toBe("/repo");
|
||||
return ok();
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.status") {
|
||||
return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n");
|
||||
}
|
||||
if (
|
||||
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
|
||||
input.operation === "GitCore.statusDetails.stagedNumstat"
|
||||
) {
|
||||
return ok();
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.defaultRef") {
|
||||
return ok("refs/remotes/origin/main\n");
|
||||
}
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "Unexpected git command in shared refresh cache test.",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
yield* core.statusDetails("/repo/worktrees/main");
|
||||
yield* core.statusDetails("/repo/worktrees/pr-123");
|
||||
expect(fetchCount).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("briefly backs off failed upstream refreshes across sibling worktrees", () =>
|
||||
Effect.gen(function* () {
|
||||
const ok = (stdout = "") =>
|
||||
Effect.succeed({
|
||||
code: 0,
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
|
||||
let fetchCount = 0;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (
|
||||
input.args[0] === "rev-parse" &&
|
||||
input.args[1] === "--abbrev-ref" &&
|
||||
input.args[2] === "--symbolic-full-name" &&
|
||||
input.args[3] === "@{upstream}"
|
||||
) {
|
||||
return ok("origin/main\n");
|
||||
}
|
||||
if (input.args[0] === "remote") {
|
||||
return ok("origin\n");
|
||||
}
|
||||
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
|
||||
return ok("/repo/.git\n");
|
||||
}
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
fetchCount += 1;
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "simulated fetch timeout",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return realGitCore.execute(input);
|
||||
if (input.operation === "GitCore.statusDetails.status") {
|
||||
return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n");
|
||||
}
|
||||
if (
|
||||
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
|
||||
input.operation === "GitCore.statusDetails.stagedNumstat"
|
||||
) {
|
||||
return ok();
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.defaultRef") {
|
||||
return ok("refs/remotes/origin/main\n");
|
||||
}
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "Unexpected git command in refresh failure cooldown test.",
|
||||
}),
|
||||
);
|
||||
});
|
||||
yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
|
||||
yield* Effect.promise(() =>
|
||||
vi.waitFor(() => {
|
||||
expect(fetchStarted).toBe(true);
|
||||
}),
|
||||
);
|
||||
expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
|
||||
releaseFetch();
|
||||
|
||||
yield* core.statusDetails("/repo/worktrees/main");
|
||||
yield* core.statusDetails("/repo/worktrees/pr-123");
|
||||
expect(fetchCount).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -638,16 +956,21 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
it.effect("checks out a remote tracking branch when remote name contains slashes", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const prefixRemote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
const prefixFetchNamespace = "prefix-my-org";
|
||||
const prefixRemoteName = "my-org";
|
||||
const remoteName = "my-org/upstream";
|
||||
const featureBranch = "feature";
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* git(prefixRemote, ["init", "--bare"]);
|
||||
|
||||
yield* initRepoWithCommit(source);
|
||||
const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
yield* git(source, ["remote", "add", remoteName, remote]);
|
||||
yield* configureRemote(source, prefixRemoteName, prefixRemote, prefixFetchNamespace);
|
||||
yield* configureRemote(source, remoteName, remote, remoteName);
|
||||
yield* git(source, ["push", "-u", remoteName, defaultBranch]);
|
||||
|
||||
yield* git(source, ["checkout", "-b", featureBranch]);
|
||||
@@ -658,12 +981,41 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
yield* git(source, ["checkout", defaultBranch]);
|
||||
yield* git(source, ["branch", "-D", featureBranch]);
|
||||
|
||||
yield* (yield* GitCore).checkoutBranch({
|
||||
const checkoutResult = yield* (yield* GitCore).checkoutBranch({
|
||||
cwd: source,
|
||||
branch: `${remoteName}/${featureBranch}`,
|
||||
});
|
||||
|
||||
expect(checkoutResult.branch).toBe("upstream/feature");
|
||||
expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature");
|
||||
const realGitCore = yield* GitCore;
|
||||
let fetchArgs: readonly string[] | null = null;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
fetchArgs = [...input.args];
|
||||
return Effect.succeed({
|
||||
code: 0,
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
}
|
||||
return realGitCore.execute(input);
|
||||
});
|
||||
|
||||
const status = yield* core.statusDetails(source);
|
||||
expect(status.branch).toBe("upstream/feature");
|
||||
expect(status.upstreamRef).toBe(`${remoteName}/${featureBranch}`);
|
||||
expect(fetchArgs).toEqual([
|
||||
"--git-dir",
|
||||
path.join(source, ".git"),
|
||||
"fetch",
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
remoteName,
|
||||
`+refs/heads/${featureBranch}:refs/remotes/${remoteName}/${featureBranch}`,
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1550,6 +1902,47 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("pushes to the tracked upstream when the remote name contains slashes", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir();
|
||||
const prefixRemote = yield* makeTmpDir();
|
||||
const prefixFetchNamespace = "prefix-my-org";
|
||||
const prefixRemoteName = "my-org";
|
||||
const remoteName = "my-org/upstream";
|
||||
const featureBranch = "feature/slash-remote-push";
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* git(prefixRemote, ["init", "--bare"]);
|
||||
|
||||
const { initialBranch } = yield* initRepoWithCommit(tmp);
|
||||
yield* configureRemote(tmp, prefixRemoteName, prefixRemote, prefixFetchNamespace);
|
||||
yield* configureRemote(tmp, remoteName, remote, remoteName);
|
||||
yield* git(tmp, ["push", "-u", remoteName, initialBranch]);
|
||||
|
||||
yield* git(tmp, ["checkout", "-b", featureBranch]);
|
||||
yield* writeTextFile(path.join(tmp, "feature.txt"), "first revision\n");
|
||||
yield* git(tmp, ["add", "feature.txt"]);
|
||||
yield* git(tmp, ["commit", "-m", "feature base"]);
|
||||
yield* git(tmp, ["push", "-u", remoteName, featureBranch]);
|
||||
|
||||
yield* writeTextFile(path.join(tmp, "feature.txt"), "second revision\n");
|
||||
yield* git(tmp, ["add", "feature.txt"]);
|
||||
yield* git(tmp, ["commit", "-m", "feature update"]);
|
||||
|
||||
const core = yield* GitCore;
|
||||
const pushed = yield* core.pushCurrentBranch(tmp, null);
|
||||
expect(pushed.status).toBe("pushed");
|
||||
expect(pushed.setUpstream).toBe(false);
|
||||
expect(pushed.upstreamBranch).toBe(`${remoteName}/${featureBranch}`);
|
||||
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
|
||||
`${remoteName}/${featureBranch}`,
|
||||
);
|
||||
expect(yield* git(tmp, ["ls-remote", "--heads", remoteName, featureBranch])).toContain(
|
||||
featureBranch,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("includes command context when worktree removal fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
@@ -1667,6 +2060,40 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prepareCommitContext truncates oversized staged patches instead of failing", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const core = yield* GitCore;
|
||||
|
||||
yield* writeTextFile(path.join(tmp, "README.md"), buildLargeText());
|
||||
|
||||
const context = yield* core.prepareCommitContext(tmp);
|
||||
expect(context).not.toBeNull();
|
||||
expect(context!.stagedSummary).toContain("README.md");
|
||||
expect(context!.stagedPatch).toContain("[truncated]");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("readRangeContext truncates oversized diff patches instead of failing", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const { initialBranch } = yield* initRepoWithCommit(tmp);
|
||||
const core = yield* GitCore;
|
||||
|
||||
yield* core.createBranch({ cwd: tmp, branch: "feature/large-range-context" });
|
||||
yield* core.checkoutBranch({ cwd: tmp, branch: "feature/large-range-context" });
|
||||
yield* writeTextFile(path.join(tmp, "large.txt"), buildLargeText());
|
||||
yield* git(tmp, ["add", "large.txt"]);
|
||||
yield* git(tmp, ["commit", "-m", "Add large range context"]);
|
||||
|
||||
const rangeContext = yield* core.readRangeContext(tmp, initialBranch);
|
||||
expect(rangeContext.commitSummary).toContain("Add large range context");
|
||||
expect(rangeContext.diffSummary).toContain("large.txt");
|
||||
expect(rangeContext.diffPatch).toContain("[truncated]");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("pushes with upstream setup and then skips when up to date", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
@@ -1781,7 +2208,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
let didFailRemoteBranches = false;
|
||||
let didFailRemoteNames = false;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (input.args.join(" ") === "branch --no-color --remotes") {
|
||||
if (input.args.join(" ") === "branch --no-color --no-column --remotes") {
|
||||
didFailRemoteBranches = true;
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
|
||||
+1756
-1402
File diff suppressed because it is too large.
Load diff
@@ -1,8 +1,8 @@
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
import { Effect, Layer, Schema, SchemaIssue } from "effect";
|
||||
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
|
||||
import { runProcess } from "../../processRunner";
|
||||
import { GitHubCliError } from "../Errors.ts";
|
||||
import { GitHubCliError } from "@t3tools/contracts";
|
||||
import {
|
||||
GitHubCli,
|
||||
type GitHubRepositoryCloneUrls,
|
||||
@@ -154,7 +154,7 @@ function decodeGitHubJson<S extends Schema.Top>(
|
||||
(error) =>
|
||||
new GitHubCliError({
|
||||
operation,
|
||||
detail: error instanceof Error ? `${invalidDetail}: ${error.message}` : invalidDetail,
|
||||
detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
@@ -187,7 +187,7 @@ const makeGitHubCli = Effect.sync(() => {
|
||||
"--limit",
|
||||
String(input.limit ?? 1),
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName",
|
||||
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
||||
],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,312 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Deferred, Effect, Exit, Layer, Option, Scope, Stream } from "effect";
|
||||
import type {
|
||||
GitStatusLocalResult,
|
||||
GitStatusRemoteResult,
|
||||
GitStatusResult,
|
||||
GitStatusStreamEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe } from "vitest";
|
||||
|
||||
import { GitStatusBroadcaster } from "../Services/GitStatusBroadcaster.ts";
|
||||
import { GitStatusBroadcasterLive } from "./GitStatusBroadcaster.ts";
|
||||
import { type GitManagerShape, GitManager } from "../Services/GitManager.ts";
|
||||
|
||||
const baseLocalStatus: GitStatusLocalResult = {
|
||||
isRepo: true,
|
||||
hostingProvider: {
|
||||
kind: "github",
|
||||
name: "GitHub",
|
||||
baseUrl: "https://github.com",
|
||||
},
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "feature/status-broadcast",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
};
|
||||
|
||||
const baseRemoteStatus: GitStatusRemoteResult = {
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
};
|
||||
|
||||
const baseStatus: GitStatusResult = {
|
||||
...baseLocalStatus,
|
||||
...baseRemoteStatus,
|
||||
};
|
||||
|
||||
function makeTestLayer(state: {
|
||||
currentLocalStatus: GitStatusLocalResult;
|
||||
currentRemoteStatus: GitStatusRemoteResult | null;
|
||||
localStatusCalls: number;
|
||||
remoteStatusCalls: number;
|
||||
localInvalidationCalls: number;
|
||||
remoteInvalidationCalls: number;
|
||||
}) {
|
||||
const gitManager: GitManagerShape = {
|
||||
localStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localStatusCalls += 1;
|
||||
return state.currentLocalStatus;
|
||||
}),
|
||||
remoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteStatusCalls += 1;
|
||||
return state.currentRemoteStatus;
|
||||
}),
|
||||
status: () => Effect.die("status should not be called in this test"),
|
||||
invalidateLocalStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateRemoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateStatus: () => Effect.die("invalidateStatus should not be called in this test"),
|
||||
resolvePullRequest: () => Effect.die("resolvePullRequest should not be called in this test"),
|
||||
preparePullRequestThread: () =>
|
||||
Effect.die("preparePullRequestThread should not be called in this test"),
|
||||
runStackedAction: () => Effect.die("runStackedAction should not be called in this test"),
|
||||
};
|
||||
|
||||
return GitStatusBroadcasterLive.pipe(Layer.provide(Layer.succeed(GitManager, gitManager)));
|
||||
}
|
||||
|
||||
describe("GitStatusBroadcasterLive", () => {
|
||||
it.effect("reuses the cached git status across repeated reads", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: baseRemoteStatus,
|
||||
localStatusCalls: 0,
|
||||
remoteStatusCalls: 0,
|
||||
localInvalidationCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* GitStatusBroadcaster;
|
||||
|
||||
const first = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
const second = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
|
||||
assert.deepStrictEqual(first, baseStatus);
|
||||
assert.deepStrictEqual(second, baseStatus);
|
||||
assert.equal(state.localStatusCalls, 1);
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
assert.equal(state.localInvalidationCalls, 0);
|
||||
assert.equal(state.remoteInvalidationCalls, 0);
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it.effect("refreshes the cached snapshot after explicit invalidation", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: baseRemoteStatus,
|
||||
localStatusCalls: 0,
|
||||
remoteStatusCalls: 0,
|
||||
localInvalidationCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* GitStatusBroadcaster;
|
||||
const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
|
||||
state.currentLocalStatus = {
|
||||
...baseLocalStatus,
|
||||
branch: "feature/updated-status",
|
||||
};
|
||||
state.currentRemoteStatus = {
|
||||
...baseRemoteStatus,
|
||||
aheadCount: 2,
|
||||
};
|
||||
const refreshed = yield* broadcaster.refreshStatus("/repo");
|
||||
const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
|
||||
assert.deepStrictEqual(initial, baseStatus);
|
||||
assert.deepStrictEqual(refreshed, {
|
||||
...state.currentLocalStatus,
|
||||
...state.currentRemoteStatus,
|
||||
});
|
||||
assert.deepStrictEqual(cached, {
|
||||
...state.currentLocalStatus,
|
||||
...state.currentRemoteStatus,
|
||||
});
|
||||
assert.equal(state.localStatusCalls, 2);
|
||||
assert.equal(state.remoteStatusCalls, 2);
|
||||
assert.equal(state.localInvalidationCalls, 1);
|
||||
assert.equal(state.remoteInvalidationCalls, 1);
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it.effect("refreshes only the cached local snapshot when requested", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: baseRemoteStatus,
|
||||
localStatusCalls: 0,
|
||||
remoteStatusCalls: 0,
|
||||
localInvalidationCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* GitStatusBroadcaster;
|
||||
const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
|
||||
state.currentLocalStatus = {
|
||||
...baseLocalStatus,
|
||||
branch: "feature/local-only-refresh",
|
||||
hasWorkingTreeChanges: true,
|
||||
};
|
||||
|
||||
const refreshedLocal = yield* broadcaster.refreshLocalStatus("/repo");
|
||||
const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
|
||||
assert.deepStrictEqual(initial, baseStatus);
|
||||
assert.deepStrictEqual(refreshedLocal, state.currentLocalStatus);
|
||||
assert.deepStrictEqual(cached, {
|
||||
...state.currentLocalStatus,
|
||||
...baseRemoteStatus,
|
||||
});
|
||||
assert.equal(state.localStatusCalls, 2);
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
assert.equal(state.localInvalidationCalls, 1);
|
||||
assert.equal(state.remoteInvalidationCalls, 0);
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it.effect("streams a local snapshot first and remote updates later", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: baseRemoteStatus,
|
||||
localStatusCalls: 0,
|
||||
remoteStatusCalls: 0,
|
||||
localInvalidationCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* GitStatusBroadcaster;
|
||||
const snapshotDeferred = yield* Deferred.make<GitStatusStreamEvent>();
|
||||
const remoteUpdatedDeferred = yield* Deferred.make<GitStatusStreamEvent>();
|
||||
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) => {
|
||||
if (event._tag === "snapshot") {
|
||||
return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore);
|
||||
}
|
||||
if (event._tag === "remoteUpdated") {
|
||||
return Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore);
|
||||
}
|
||||
return Effect.void;
|
||||
}).pipe(Effect.forkScoped);
|
||||
|
||||
const snapshot = yield* Deferred.await(snapshotDeferred);
|
||||
yield* broadcaster.refreshStatus("/repo");
|
||||
const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
|
||||
|
||||
assert.deepStrictEqual(snapshot, {
|
||||
_tag: "snapshot",
|
||||
local: baseLocalStatus,
|
||||
remote: null,
|
||||
} satisfies GitStatusStreamEvent);
|
||||
assert.deepStrictEqual(remoteUpdated, {
|
||||
_tag: "remoteUpdated",
|
||||
remote: baseRemoteStatus,
|
||||
} satisfies GitStatusStreamEvent);
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it.effect("stops the remote poller after the last stream subscriber disconnects", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: baseRemoteStatus,
|
||||
localStatusCalls: 0,
|
||||
remoteStatusCalls: 0,
|
||||
localInvalidationCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
};
|
||||
let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
|
||||
let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
|
||||
const testLayer = GitStatusBroadcasterLive.pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(GitManager, {
|
||||
localStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localStatusCalls += 1;
|
||||
return state.currentLocalStatus;
|
||||
}),
|
||||
remoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteStatusCalls += 1;
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
remoteStartedDeferred
|
||||
? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.andThen(Effect.never as Effect.Effect<GitStatusRemoteResult | null, never>),
|
||||
Effect.onInterrupt(() =>
|
||||
remoteInterruptedDeferred
|
||||
? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
status: () => Effect.die("status should not be called in this test"),
|
||||
invalidateLocalStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateRemoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateStatus: () => Effect.die("invalidateStatus should not be called in this test"),
|
||||
resolvePullRequest: () =>
|
||||
Effect.die("resolvePullRequest should not be called in this test"),
|
||||
preparePullRequestThread: () =>
|
||||
Effect.die("preparePullRequestThread should not be called in this test"),
|
||||
runStackedAction: () => Effect.die("runStackedAction should not be called in this test"),
|
||||
} satisfies GitManagerShape),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const remoteInterrupted = yield* Deferred.make<void>();
|
||||
const remoteStarted = yield* Deferred.make<void>();
|
||||
remoteInterruptedDeferred = remoteInterrupted;
|
||||
remoteStartedDeferred = remoteStarted;
|
||||
|
||||
const broadcaster = yield* GitStatusBroadcaster;
|
||||
const firstSnapshot = yield* Deferred.make<GitStatusStreamEvent>();
|
||||
const secondSnapshot = yield* Deferred.make<GitStatusStreamEvent>();
|
||||
const firstScope = yield* Scope.make();
|
||||
const secondScope = yield* Scope.make();
|
||||
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
|
||||
event._tag === "snapshot"
|
||||
? Deferred.succeed(firstSnapshot, event).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
).pipe(Effect.forkIn(firstScope));
|
||||
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
|
||||
event._tag === "snapshot"
|
||||
? Deferred.succeed(secondSnapshot, event).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
).pipe(Effect.forkIn(secondScope));
|
||||
|
||||
yield* Deferred.await(firstSnapshot);
|
||||
yield* Deferred.await(secondSnapshot);
|
||||
yield* Deferred.await(remoteStarted);
|
||||
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
|
||||
yield* Scope.close(firstScope, Exit.void);
|
||||
assert.equal(Option.isNone(yield* Deferred.poll(remoteInterrupted)), true);
|
||||
|
||||
yield* Scope.close(secondScope, Exit.void).pipe(Effect.forkScoped);
|
||||
yield* Deferred.await(remoteInterrupted);
|
||||
assert.equal(Option.isSome(yield* Deferred.poll(remoteInterrupted)), true);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,311 @@
|
||||
import { realpathSync } from "node:fs";
|
||||
|
||||
import {
|
||||
Duration,
|
||||
Effect,
|
||||
Exit,
|
||||
Fiber,
|
||||
Layer,
|
||||
PubSub,
|
||||
Ref,
|
||||
Scope,
|
||||
Stream,
|
||||
SynchronizedRef,
|
||||
} from "effect";
|
||||
import type {
|
||||
GitStatusInput,
|
||||
GitStatusLocalResult,
|
||||
GitStatusRemoteResult,
|
||||
GitStatusStreamEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { mergeGitStatusParts } from "@t3tools/shared/git";
|
||||
|
||||
import {
|
||||
GitStatusBroadcaster,
|
||||
type GitStatusBroadcasterShape,
|
||||
} from "../Services/GitStatusBroadcaster.ts";
|
||||
import { GitManager } from "../Services/GitManager.ts";
|
||||
|
||||
const GIT_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
|
||||
|
||||
interface GitStatusChange {
|
||||
readonly cwd: string;
|
||||
readonly event: GitStatusStreamEvent;
|
||||
}
|
||||
|
||||
interface CachedValue<T> {
|
||||
readonly fingerprint: string;
|
||||
readonly value: T;
|
||||
}
|
||||
|
||||
interface CachedGitStatus {
|
||||
readonly local: CachedValue<GitStatusLocalResult> | null;
|
||||
readonly remote: CachedValue<GitStatusRemoteResult | null> | null;
|
||||
}
|
||||
|
||||
interface ActiveRemotePoller {
|
||||
readonly fiber: Fiber.Fiber<void, never>;
|
||||
readonly subscriberCount: number;
|
||||
}
|
||||
|
||||
function normalizeCwd(cwd: string): string {
|
||||
try {
|
||||
return realpathSync.native(cwd);
|
||||
} catch {
|
||||
return cwd;
|
||||
}
|
||||
}
|
||||
|
||||
function fingerprintStatusPart(status: unknown): string {
|
||||
return JSON.stringify(status);
|
||||
}
|
||||
|
||||
export const GitStatusBroadcasterLive = Layer.effect(
|
||||
GitStatusBroadcaster,
|
||||
Effect.gen(function* () {
|
||||
const gitManager = yield* GitManager;
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<GitStatusChange>(),
|
||||
(pubsub) => PubSub.shutdown(pubsub),
|
||||
);
|
||||
const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
|
||||
Scope.close(scope, Exit.void),
|
||||
);
|
||||
const cacheRef = yield* Ref.make(new Map<string, CachedGitStatus>());
|
||||
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
|
||||
|
||||
const getCachedStatus = Effect.fn("getCachedStatus")(function* (cwd: string) {
|
||||
return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
|
||||
});
|
||||
|
||||
const updateCachedLocalStatus = Effect.fn("updateCachedLocalStatus")(function* (
|
||||
cwd: string,
|
||||
local: GitStatusLocalResult,
|
||||
options?: { publish?: boolean },
|
||||
) {
|
||||
const nextLocal = {
|
||||
fingerprint: fingerprintStatusPart(local),
|
||||
value: local,
|
||||
} satisfies CachedValue<GitStatusLocalResult>;
|
||||
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
|
||||
const previous = cache.get(cwd) ?? { local: null, remote: null };
|
||||
const nextCache = new Map(cache);
|
||||
nextCache.set(cwd, {
|
||||
...previous,
|
||||
local: nextLocal,
|
||||
});
|
||||
return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
|
||||
});
|
||||
|
||||
if (options?.publish && shouldPublish) {
|
||||
yield* PubSub.publish(changesPubSub, {
|
||||
cwd,
|
||||
event: {
|
||||
_tag: "localUpdated",
|
||||
local,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return local;
|
||||
});
|
||||
|
||||
const updateCachedRemoteStatus = Effect.fn("updateCachedRemoteStatus")(function* (
|
||||
cwd: string,
|
||||
remote: GitStatusRemoteResult | null,
|
||||
options?: { publish?: boolean },
|
||||
) {
|
||||
const nextRemote = {
|
||||
fingerprint: fingerprintStatusPart(remote),
|
||||
value: remote,
|
||||
} satisfies CachedValue<GitStatusRemoteResult | null>;
|
||||
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
|
||||
const previous = cache.get(cwd) ?? { local: null, remote: null };
|
||||
const nextCache = new Map(cache);
|
||||
nextCache.set(cwd, {
|
||||
...previous,
|
||||
remote: nextRemote,
|
||||
});
|
||||
return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;
|
||||
});
|
||||
|
||||
if (options?.publish && shouldPublish) {
|
||||
yield* PubSub.publish(changesPubSub, {
|
||||
cwd,
|
||||
event: {
|
||||
_tag: "remoteUpdated",
|
||||
remote,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return remote;
|
||||
});
|
||||
|
||||
const loadLocalStatus = Effect.fn("loadLocalStatus")(function* (cwd: string) {
|
||||
const local = yield* gitManager.localStatus({ cwd });
|
||||
return yield* updateCachedLocalStatus(cwd, local);
|
||||
});
|
||||
|
||||
const loadRemoteStatus = Effect.fn("loadRemoteStatus")(function* (cwd: string) {
|
||||
const remote = yield* gitManager.remoteStatus({ cwd });
|
||||
return yield* updateCachedRemoteStatus(cwd, remote);
|
||||
});
|
||||
|
||||
const getOrLoadLocalStatus = Effect.fn("getOrLoadLocalStatus")(function* (cwd: string) {
|
||||
const cached = yield* getCachedStatus(cwd);
|
||||
if (cached?.local) {
|
||||
return cached.local.value;
|
||||
}
|
||||
return yield* loadLocalStatus(cwd);
|
||||
});
|
||||
|
||||
const getOrLoadRemoteStatus = Effect.fn("getOrLoadRemoteStatus")(function* (cwd: string) {
|
||||
const cached = yield* getCachedStatus(cwd);
|
||||
if (cached?.remote) {
|
||||
return cached.remote.value;
|
||||
}
|
||||
return yield* loadRemoteStatus(cwd);
|
||||
});
|
||||
|
||||
const getStatus: GitStatusBroadcasterShape["getStatus"] = Effect.fn("getStatus")(function* (
|
||||
input: GitStatusInput,
|
||||
) {
|
||||
const normalizedCwd = normalizeCwd(input.cwd);
|
||||
const [local, remote] = yield* Effect.all([
|
||||
getOrLoadLocalStatus(normalizedCwd),
|
||||
getOrLoadRemoteStatus(normalizedCwd),
|
||||
]);
|
||||
return mergeGitStatusParts(local, remote);
|
||||
});
|
||||
|
||||
const refreshLocalStatus: GitStatusBroadcasterShape["refreshLocalStatus"] = Effect.fn(
|
||||
"refreshLocalStatus",
|
||||
)(function* (cwd) {
|
||||
const normalizedCwd = normalizeCwd(cwd);
|
||||
yield* gitManager.invalidateLocalStatus(normalizedCwd);
|
||||
const local = yield* gitManager.localStatus({ cwd: normalizedCwd });
|
||||
return yield* updateCachedLocalStatus(normalizedCwd, local, { publish: true });
|
||||
});
|
||||
|
||||
const refreshRemoteStatus = Effect.fn("refreshRemoteStatus")(function* (cwd: string) {
|
||||
yield* gitManager.invalidateRemoteStatus(cwd);
|
||||
const remote = yield* gitManager.remoteStatus({ cwd });
|
||||
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
|
||||
});
|
||||
|
||||
const refreshStatus: GitStatusBroadcasterShape["refreshStatus"] = Effect.fn("refreshStatus")(
|
||||
function* (cwd) {
|
||||
const normalizedCwd = normalizeCwd(cwd);
|
||||
const [local, remote] = yield* Effect.all([
|
||||
refreshLocalStatus(normalizedCwd),
|
||||
refreshRemoteStatus(normalizedCwd),
|
||||
]);
|
||||
return mergeGitStatusParts(local, remote);
|
||||
},
|
||||
);
|
||||
|
||||
const makeRemoteRefreshLoop = (cwd: string) => {
|
||||
const logRefreshFailure = (error: Error) =>
|
||||
Effect.logWarning("git remote status refresh failed", {
|
||||
cwd,
|
||||
detail: error.message,
|
||||
});
|
||||
|
||||
return refreshRemoteStatus(cwd).pipe(
|
||||
Effect.catch(logRefreshFailure),
|
||||
Effect.andThen(
|
||||
Effect.forever(
|
||||
Effect.sleep(GIT_STATUS_REFRESH_INTERVAL).pipe(
|
||||
Effect.andThen(refreshRemoteStatus(cwd).pipe(Effect.catch(logRefreshFailure))),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const retainRemotePoller = Effect.fn("retainRemotePoller")(function* (cwd: string) {
|
||||
yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
|
||||
const existing = activePollers.get(cwd);
|
||||
if (existing) {
|
||||
const nextPollers = new Map(activePollers);
|
||||
nextPollers.set(cwd, {
|
||||
...existing,
|
||||
subscriberCount: existing.subscriberCount + 1,
|
||||
});
|
||||
return Effect.succeed([undefined, nextPollers] as const);
|
||||
}
|
||||
|
||||
return makeRemoteRefreshLoop(cwd).pipe(
|
||||
Effect.forkIn(broadcasterScope),
|
||||
Effect.map((fiber) => {
|
||||
const nextPollers = new Map(activePollers);
|
||||
nextPollers.set(cwd, {
|
||||
fiber,
|
||||
subscriberCount: 1,
|
||||
});
|
||||
return [undefined, nextPollers] as const;
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const releaseRemotePoller = Effect.fn("releaseRemotePoller")(function* (cwd: string) {
|
||||
const pollerToInterrupt = yield* SynchronizedRef.modify(pollersRef, (activePollers) => {
|
||||
const existing = activePollers.get(cwd);
|
||||
if (!existing) {
|
||||
return [null, activePollers] as const;
|
||||
}
|
||||
|
||||
if (existing.subscriberCount > 1) {
|
||||
const nextPollers = new Map(activePollers);
|
||||
nextPollers.set(cwd, {
|
||||
...existing,
|
||||
subscriberCount: existing.subscriberCount - 1,
|
||||
});
|
||||
return [null, nextPollers] as const;
|
||||
}
|
||||
|
||||
const nextPollers = new Map(activePollers);
|
||||
nextPollers.delete(cwd);
|
||||
return [existing.fiber, nextPollers] as const;
|
||||
});
|
||||
|
||||
if (pollerToInterrupt) {
|
||||
yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const streamStatus: GitStatusBroadcasterShape["streamStatus"] = (input) =>
|
||||
Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const normalizedCwd = normalizeCwd(input.cwd);
|
||||
const subscription = yield* PubSub.subscribe(changesPubSub);
|
||||
const initialLocal = yield* getOrLoadLocalStatus(normalizedCwd);
|
||||
const initialRemote = (yield* getCachedStatus(normalizedCwd))?.remote?.value ?? null;
|
||||
yield* retainRemotePoller(normalizedCwd);
|
||||
|
||||
const release = releaseRemotePoller(normalizedCwd).pipe(Effect.ignore, Effect.asVoid);
|
||||
|
||||
return Stream.concat(
|
||||
Stream.make({
|
||||
_tag: "snapshot" as const,
|
||||
local: initialLocal,
|
||||
remote: initialRemote,
|
||||
}),
|
||||
Stream.fromSubscription(subscription).pipe(
|
||||
Stream.filter((event) => event.cwd === normalizedCwd),
|
||||
Stream.map((event) => event.event),
|
||||
),
|
||||
).pipe(Stream.ensuring(release));
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
getStatus,
|
||||
refreshLocalStatus,
|
||||
refreshStatus,
|
||||
streamStatus,
|
||||
} satisfies GitStatusBroadcasterShape;
|
||||
}),
|
||||
);
|
||||
Loaded 100 of 576 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user