Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
33b347391d | ||
|
|
d8aa2f85df | ||
|
|
64d6938cf4 | ||
|
|
0a88719a3a | ||
|
|
0bc94bc24e | ||
|
|
19eb9e7227 | ||
|
|
e3404d1710 | ||
|
|
5abe2845ca | ||
|
|
435a08b35a | ||
|
|
b6227a4b67 | ||
|
|
aa5521dcfb | ||
|
|
c190e9f2b7 | ||
|
|
881c64937a | ||
|
|
2d03847ccd | ||
|
|
d303ac39cb | ||
|
|
48fc85e7fe | ||
|
|
0ea639196a | ||
|
|
6f51725732 | ||
|
|
8622b952ca | ||
|
|
f47c1f1046 | ||
|
|
145ddfc408 | ||
|
|
0bb787b90d | ||
|
|
59f23d7bfd | ||
|
|
4a4795e5f0 | ||
|
|
5b58f74e9a | ||
|
|
32dca3b76b | ||
|
|
6358444900 | ||
|
|
792ad4b5c1 | ||
|
|
d41781987c | ||
|
|
fc6507066e | ||
|
|
bf9c828aef | ||
|
|
7b676b76de | ||
|
|
d5f2333173 | ||
|
|
40e7dbdae9 |
No files matched your search
+2
-2
@@ -1,13 +1,13 @@
|
||||
# Scripts
|
||||
|
||||
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
|
||||
- `bun run dev` — Starts contracts, server, and web in workspace dev mode.
|
||||
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
|
||||
- `bun run dev:web` — Starts just the Vite dev server for the web app.
|
||||
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
|
||||
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
|
||||
`bun run dev -- --base-dir ~/.t3-2`
|
||||
- `bun run start` — Runs the production server (serves built web app as static files).
|
||||
- `bun run build` — Builds contracts, web app, and server through Turbo.
|
||||
- `bun run build` — Builds workspace packages and apps through Vite+ task running.
|
||||
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
||||
- `bun run test` — Runs workspace tests.
|
||||
- `bun run dist:desktop:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
|
||||
|
||||
+15
-18
@@ -19,18 +19,17 @@ jobs:
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
run-install: false
|
||||
|
||||
- name: Cache Bun and Turbo
|
||||
- name: Cache Bun
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: |
|
||||
~/.bun/install/cache
|
||||
.turbo
|
||||
key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-${{ hashFiles('turbo.json') }}
|
||||
path: ~/.bun/install/cache
|
||||
key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
|
||||
|
||||
@@ -45,22 +44,19 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Format
|
||||
run: bun run fmt:check
|
||||
- name: Check workspace (lint & fmt)
|
||||
run: vp check
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
|
||||
- name: Typecheck
|
||||
run: bun run typecheck
|
||||
- name: Check workspace (typecheck)
|
||||
run: vp run -r typecheck
|
||||
|
||||
- name: Test
|
||||
run: bun run test
|
||||
run: vp test
|
||||
|
||||
- name: Install browser test runtime
|
||||
run: |
|
||||
cd apps/web
|
||||
bunx playwright install --with-deps chromium
|
||||
vpx playwright install --with-deps chromium
|
||||
|
||||
- name: Browser test
|
||||
run: bun run --cwd apps/web test:browser
|
||||
@@ -85,10 +81,11 @@ jobs:
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
run-install: false
|
||||
|
||||
- name: Exercise release-only workflow steps
|
||||
run: node scripts/release-smoke.ts
|
||||
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
||||
"ignorePatterns": [
|
||||
".plans",
|
||||
"dist",
|
||||
"dist-electron",
|
||||
"node_modules",
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo",
|
||||
"**/routeTree.gen.ts",
|
||||
"apps/web/public/mockServiceWorker.js"
|
||||
],
|
||||
"sortPackageJson": {}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"ignorePatterns": [
|
||||
"dist",
|
||||
"dist-electron",
|
||||
"node_modules",
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo",
|
||||
"**/routeTree.gen.ts"
|
||||
],
|
||||
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
|
||||
"categories": {
|
||||
"correctness": "warn",
|
||||
"suspicious": "warn",
|
||||
"perf": "warn"
|
||||
},
|
||||
"rules": {
|
||||
"react-in-jsx-scope": "off",
|
||||
"eslint/no-shadow": "off",
|
||||
"eslint/no-await-in-loop": "off"
|
||||
}
|
||||
}
|
||||
@@ -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,8 +2,8 @@
|
||||
|
||||
## Task Completion Requirements
|
||||
|
||||
- All of `bun fmt`, `bun lint`, and `bun typecheck` must pass before considering tasks completed.
|
||||
- NEVER run `bun test`. Always use `bun run test` (runs Vitest).
|
||||
- `vp check` & `vp run typecheck` must pass before considering tasks completed.
|
||||
- NEVER run `bun test`. Always use `vp test` (runs Vitest).
|
||||
|
||||
## Project Snapshot
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -5,12 +5,12 @@
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
"dev": "bun run --parallel dev:bundle dev:electron",
|
||||
"dev:bundle": "tsdown --watch",
|
||||
"dev:bundle": "vp pack --watch",
|
||||
"dev:electron": "bun run scripts/dev-electron.mjs",
|
||||
"build": "tsdown",
|
||||
"build": "vp pack",
|
||||
"start": "bun run scripts/start-electron.mjs",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"test": "vp test run --passWithNoTests",
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -22,10 +22,9 @@
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@types/node": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"electron-builder": "26.8.1",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
"wait-on": "^8.0.2"
|
||||
"vite-plus": "catalog:"
|
||||
},
|
||||
"productName": "T3 Code (Alpha)"
|
||||
}
|
||||
@@ -1,27 +1,29 @@
|
||||
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 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,
|
||||
tcpPort: port,
|
||||
});
|
||||
|
||||
const childEnv = { ...process.env };
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { BrowserWindow } from "electron";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const { showMessageBoxMock } = vi.hoisted(() => ({
|
||||
showMessageBoxMock: vi.fn(),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -66,6 +66,8 @@ 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;
|
||||
@@ -80,6 +82,9 @@ const DESKTOP_UPDATE_CHANNEL = "latest";
|
||||
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
|
||||
|
||||
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
|
||||
type LinuxDesktopNamedApp = Electron.App & {
|
||||
setDesktopName?: (desktopName: string) => void;
|
||||
};
|
||||
|
||||
let mainWindow: BrowserWindow | null = null;
|
||||
let backendProcess: ChildProcess.ChildProcess | null = null;
|
||||
@@ -99,7 +104,7 @@ let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
|
||||
const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
|
||||
platform: process.platform,
|
||||
processArch: process.arch,
|
||||
runningUnderArm64Translation: app.runningUnderARM64Translation === true,
|
||||
runningUnderArm64Translation: app.runningUnderARM64Translation,
|
||||
});
|
||||
const initialUpdateState = (): DesktopUpdateState =>
|
||||
createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo);
|
||||
@@ -263,6 +268,10 @@ function captureBackendOutput(child: ChildProcess.ChildProcess): void {
|
||||
|
||||
initializePackagedLogging();
|
||||
|
||||
if (process.platform === "linux") {
|
||||
app.commandLine.appendSwitch("class", LINUX_WM_CLASS);
|
||||
}
|
||||
|
||||
function getDestructiveMenuIcon(): Electron.NativeImage | undefined {
|
||||
if (process.platform !== "darwin") return undefined;
|
||||
if (destructiveMenuIconCache !== undefined) {
|
||||
@@ -390,7 +399,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 {
|
||||
@@ -715,6 +724,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) {
|
||||
|
||||
@@ -3,7 +3,7 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { afterEach, describe, expect, it } from "vite-plus/test";
|
||||
|
||||
const tempRoots: string[] = [];
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
createInitialDesktopUpdateState,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
|
||||
@@ -5,5 +5,5 @@
|
||||
"types": ["node", "electron"],
|
||||
"lib": ["ES2023", "DOM", "esnext.disposable"]
|
||||
},
|
||||
"include": ["src", "tsdown.config.ts"]
|
||||
"include": ["src", "vite.config.ts"]
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import { defineConfig } from "tsdown";
|
||||
|
||||
const shared = {
|
||||
format: "cjs" as const,
|
||||
outDir: "dist-electron",
|
||||
sourcemap: true,
|
||||
outExtensions: () => ({ js: ".js" }),
|
||||
};
|
||||
|
||||
export default defineConfig([
|
||||
{
|
||||
...shared,
|
||||
entry: ["src/main.ts"],
|
||||
clean: true,
|
||||
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||
},
|
||||
{
|
||||
...shared,
|
||||
entry: ["src/preload.ts"],
|
||||
},
|
||||
]);
|
||||
@@ -1,24 +0,0 @@
|
||||
{
|
||||
"$schema": "https://turbo.build/schema.json",
|
||||
"extends": ["//"],
|
||||
"tasks": {
|
||||
"build": {
|
||||
"dependsOn": ["^build"],
|
||||
"outputs": ["dist-electron/**"],
|
||||
},
|
||||
"dev": {
|
||||
"dependsOn": ["t3#build"],
|
||||
"persistent": true,
|
||||
},
|
||||
"start": {
|
||||
"dependsOn": ["build", "@t3tools/web#build", "t3#build"],
|
||||
"cache": false,
|
||||
"persistent": true,
|
||||
},
|
||||
"smoke-test": {
|
||||
"dependsOn": ["build", "@t3tools/web#build", "t3#build"],
|
||||
"cache": false,
|
||||
"outputs": [],
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { defineConfig } from "vite-plus";
|
||||
|
||||
const shared = {
|
||||
format: "cjs" as const,
|
||||
outDir: "dist-electron",
|
||||
sourcemap: true,
|
||||
outExtensions: () => ({ js: ".js" }),
|
||||
};
|
||||
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
tsconfigPaths: true,
|
||||
},
|
||||
pack: [
|
||||
{
|
||||
...shared,
|
||||
entry: ["src/main.ts"],
|
||||
clean: true,
|
||||
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||
},
|
||||
{
|
||||
...shared,
|
||||
entry: ["src/preload.ts"],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -68,6 +68,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, {
|
||||
@@ -113,19 +115,19 @@ function waitFor<A, E>(
|
||||
predicate: (value: A) => boolean,
|
||||
description: string,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<A, never>;
|
||||
): Effect.Effect<A>;
|
||||
function waitFor<A, B extends A, E>(
|
||||
read: Effect.Effect<A, E>,
|
||||
predicate: (value: A) => value is B,
|
||||
description: string,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<B, never>;
|
||||
): Effect.Effect<B>;
|
||||
function waitFor<A, E>(
|
||||
read: Effect.Effect<A, E>,
|
||||
predicate: (value: A) => boolean,
|
||||
description: string,
|
||||
timeoutMs = 10_000,
|
||||
): Effect.Effect<A, never> {
|
||||
timeoutMs = 40_000,
|
||||
): Effect.Effect<A> {
|
||||
const RETRY_SIGNAL = "wait_for_retry";
|
||||
const retryIntervalMs = 10;
|
||||
const maxRetries = Math.max(0, Math.floor(timeoutMs / retryIntervalMs));
|
||||
@@ -174,11 +176,11 @@ export interface OrchestrationIntegrationHarness {
|
||||
threadId: string,
|
||||
predicate: (thread: OrchestrationThread) => boolean,
|
||||
timeoutMs?: number,
|
||||
) => Effect.Effect<OrchestrationThread, never>;
|
||||
) => Effect.Effect<OrchestrationThread>;
|
||||
readonly waitForDomainEvent: (
|
||||
predicate: (event: OrchestrationEvent) => boolean,
|
||||
timeoutMs?: number,
|
||||
) => Effect.Effect<ReadonlyArray<OrchestrationEvent>, never>;
|
||||
) => Effect.Effect<ReadonlyArray<OrchestrationEvent>>;
|
||||
readonly waitForPendingApproval: (
|
||||
requestId: string,
|
||||
predicate: (row: {
|
||||
@@ -187,25 +189,22 @@ export interface OrchestrationIntegrationHarness {
|
||||
readonly resolvedAt: string | null;
|
||||
}) => boolean,
|
||||
timeoutMs?: number,
|
||||
) => Effect.Effect<
|
||||
{
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
},
|
||||
never
|
||||
>;
|
||||
) => Effect.Effect<{
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
}>;
|
||||
readonly waitForReceipt: {
|
||||
(
|
||||
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<OrchestrationRuntimeReceipt, never>;
|
||||
): Effect.Effect<OrchestrationRuntimeReceipt>;
|
||||
<Receipt extends OrchestrationRuntimeReceipt>(
|
||||
predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<Receipt, never>;
|
||||
): Effect.Effect<Receipt>;
|
||||
};
|
||||
readonly dispose: Effect.Effect<void, never>;
|
||||
readonly dispose: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
interface MakeOrchestrationIntegrationHarnessOptions {
|
||||
@@ -317,6 +316,14 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(
|
||||
WorkspaceEntriesLive.pipe(
|
||||
Layer.provide(WorkspacePathsLive),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(WorkspacePathsLive),
|
||||
);
|
||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeIngestionLayer),
|
||||
@@ -384,7 +391,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
(thread): thread is OrchestrationThread => thread !== null && predicate(thread),
|
||||
`projected thread '${threadId}'`,
|
||||
timeoutMs,
|
||||
) as Effect.Effect<OrchestrationThread, never>;
|
||||
) as Effect.Effect<OrchestrationThread>;
|
||||
|
||||
const waitForDomainEvent: OrchestrationIntegrationHarness["waitForDomainEvent"] = (
|
||||
predicate,
|
||||
@@ -428,23 +435,20 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
} => row !== null && predicate(row),
|
||||
`pending approval '${requestId}'`,
|
||||
timeoutMs,
|
||||
) as Effect.Effect<
|
||||
{
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
},
|
||||
never
|
||||
>;
|
||||
) as Effect.Effect<{
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
}>;
|
||||
|
||||
function waitForReceipt(
|
||||
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<OrchestrationRuntimeReceipt, never>;
|
||||
): Effect.Effect<OrchestrationRuntimeReceipt>;
|
||||
function waitForReceipt<Receipt extends OrchestrationRuntimeReceipt>(
|
||||
predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<Receipt, never>;
|
||||
): Effect.Effect<Receipt>;
|
||||
function waitForReceipt(
|
||||
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
|
||||
timeoutMs?: number,
|
||||
|
||||
@@ -30,7 +30,7 @@ export interface TestTurnResponse {
|
||||
readonly mutateWorkspace?: (input: {
|
||||
readonly cwd: string;
|
||||
readonly turnCount: number;
|
||||
}) => Effect.Effect<void, never>;
|
||||
}) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export type FixtureProviderRuntimeEvent = {
|
||||
@@ -183,9 +183,7 @@ export interface TestProviderAdapterHarness {
|
||||
threadId: ThreadId,
|
||||
response: TestTurnResponse,
|
||||
) => Effect.Effect<void, ProviderAdapterSessionNotFoundError>;
|
||||
readonly queueTurnResponseForNextSession: (
|
||||
response: TestTurnResponse,
|
||||
) => Effect.Effect<void, never>;
|
||||
readonly queueTurnResponseForNextSession: (response: TestTurnResponse) => Effect.Effect<void>;
|
||||
readonly getStartCount: () => number;
|
||||
readonly getRollbackCalls: (threadId: ThreadId) => ReadonlyArray<number>;
|
||||
readonly getInterruptCalls: (threadId: ThreadId) => ReadonlyArray<TurnId | undefined>;
|
||||
@@ -337,7 +335,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
}
|
||||
|
||||
if (response.mutateWorkspace && state.session.cwd) {
|
||||
yield* response.mutateWorkspace({ cwd: state.session.cwd!, turnCount });
|
||||
yield* response.mutateWorkspace({ cwd: state.session.cwd, turnCount });
|
||||
}
|
||||
|
||||
const userItem = {
|
||||
@@ -505,9 +503,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
),
|
||||
);
|
||||
|
||||
const queueTurnResponseForNextSession = (
|
||||
response: TestTurnResponse,
|
||||
): Effect.Effect<void, never> =>
|
||||
const queueTurnResponseForNextSession = (response: TestTurnResponse): Effect.Effect<void> =>
|
||||
Effect.sync(() => {
|
||||
queuedResponsesForNextSession.push(response);
|
||||
});
|
||||
|
||||
@@ -57,8 +57,8 @@ function waitForSync<A>(
|
||||
read: () => A,
|
||||
predicate: (value: A) => boolean,
|
||||
description: string,
|
||||
timeoutMs = 3000,
|
||||
): Effect.Effect<A, never> {
|
||||
timeoutMs = 10_000,
|
||||
): Effect.Effect<A> {
|
||||
return Effect.gen(function* () {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
|
||||
@@ -226,9 +226,7 @@ it.live("runs a single turn end-to-end and persists checkpoint state in sqlite +
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.session?.status === "ready" &&
|
||||
entry.messages.some(
|
||||
(message) => message.role === "assistant" && message.streaming === false,
|
||||
) &&
|
||||
entry.messages.some((message) => message.role === "assistant" && !message.streaming) &&
|
||||
entry.checkpoints.length === 1,
|
||||
);
|
||||
assert.equal(thread.checkpoints[0]?.status, "ready");
|
||||
@@ -309,9 +307,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
(entry) =>
|
||||
entry.session?.status === "ready" &&
|
||||
entry.session.providerName === "codex" &&
|
||||
entry.messages.some(
|
||||
(message) => message.role === "assistant" && message.streaming === false,
|
||||
),
|
||||
entry.messages.some((message) => message.role === "assistant" && !message.streaming),
|
||||
180_000,
|
||||
);
|
||||
assert.equal(firstThread.session?.threadId, "thread-1");
|
||||
|
||||
@@ -40,7 +40,7 @@ const makeWorkspaceDirectory = Effect.gen(function* () {
|
||||
interface IntegrationFixture {
|
||||
readonly cwd: string;
|
||||
readonly harness: TestProviderAdapterHarness;
|
||||
readonly layer: Layer.Layer<ProviderService, unknown, never>;
|
||||
readonly layer: Layer.Layer<ProviderService, unknown>;
|
||||
}
|
||||
|
||||
const makeIntegrationFixture = Effect.gen(function* () {
|
||||
|
||||
@@ -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"
|
||||
"test": "vp test 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,10 +40,8 @@
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/bun": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"@types/ws": "^8.5.13",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
"vite-plus": "catalog:"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.16 || ^23.11 || >=24.10"
|
||||
|
||||
@@ -129,7 +129,7 @@ const buildCmd = Command.make(
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const serverDir = path.join(repoRoot, "apps/server");
|
||||
|
||||
yield* Effect.log("[cli] Running tsdown...");
|
||||
yield* Effect.log("[cli] Running vp pack...");
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
cwd: serverDir,
|
||||
@@ -137,7 +137,7 @@ const buildCmd = Command.make(
|
||||
stderr: "inherit",
|
||||
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
|
||||
shell: process.platform === "win32",
|
||||
})`bun tsdown`,
|
||||
})`vp pack`,
|
||||
);
|
||||
|
||||
const webDist = path.join(repoRoot, "apps/web/dist");
|
||||
@@ -151,7 +151,7 @@ const buildCmd = Command.make(
|
||||
yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
|
||||
}
|
||||
}),
|
||||
).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
|
||||
).pipe(Command.withDescription("Build the server package (vp pack + bundle web client)."));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// publish subcommand
|
||||
@@ -205,7 +205,7 @@ const publishCmd = Command.make(
|
||||
|
||||
pkg.dependencies = resolveCatalogDependencies(
|
||||
pkg.dependencies,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
rootPackageJson.catalog,
|
||||
"apps/server dependencies",
|
||||
);
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
createAttachmentId,
|
||||
|
||||
@@ -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,7 +8,7 @@ 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 { vi } from "vite-plus/test";
|
||||
|
||||
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap";
|
||||
import { assertNone, assertSome } from "@effect/vitest/utils";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { parseTurnDiffFilesFromUnifiedDiff } from "./Diffs.ts";
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Schema } from "effect";
|
||||
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
|
||||
import { GitCommandError } from "../git/Errors.ts";
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* CheckpointUnavailableError - Expected checkpoint does not exist.
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
type OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||
|
||||
@@ -3,14 +3,14 @@ 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 { describe, expect } from "vite-plus/test";
|
||||
|
||||
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 "../../git/Errors.ts";
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
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 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(),
|
||||
devUrl: Option.none(),
|
||||
noBrowser: Option.none(),
|
||||
authToken: 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_AUTH_TOKEN: "env-token",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
|
||||
T3CODE_LOG_WS_EVENTS: "true",
|
||||
},
|
||||
}),
|
||||
),
|
||||
NetService.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Warn",
|
||||
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,
|
||||
authToken: "env-token",
|
||||
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),
|
||||
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
|
||||
noBrowser: Option.some(true),
|
||||
authToken: Option.some("flag-token"),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.some(true),
|
||||
logWebSocketEvents: Option.some(true),
|
||||
},
|
||||
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_AUTH_TOKEN: "ignored-token",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
|
||||
T3CODE_LOG_WS_EVENTS: "false",
|
||||
},
|
||||
}),
|
||||
),
|
||||
NetService.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Debug",
|
||||
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,
|
||||
authToken: "flag-token",
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses bootstrap envelope values as fallbacks when flags and env are absent", () =>
|
||||
Effect.gen(function* () {
|
||||
const { join } = yield* Path.Path;
|
||||
const baseDir = "/tmp/t3-bootstrap-home";
|
||||
const fd = yield* openBootstrapFd({
|
||||
mode: "desktop",
|
||||
port: 4888,
|
||||
host: "127.0.0.2",
|
||||
t3Home: baseDir,
|
||||
devUrl: "http://127.0.0.1:5173",
|
||||
noBrowser: true,
|
||||
authToken: "bootstrap-token",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
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(),
|
||||
devUrl: Option.none(),
|
||||
noBrowser: Option.none(),
|
||||
authToken: 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",
|
||||
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,
|
||||
authToken: "bootstrap-token",
|
||||
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 resolved = yield* resolveServerConfig(
|
||||
{
|
||||
mode: Option.some("desktop"),
|
||||
port: Option.some(4888),
|
||||
host: Option.none(),
|
||||
baseDir: Option.some(baseDir),
|
||||
devUrl: Option.some(new URL("http://127.0.0.1:5173")),
|
||||
noBrowser: Option.none(),
|
||||
authToken: Option.none(),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
|
||||
NetService.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
for (const directory of [
|
||||
resolved.stateDir,
|
||||
resolved.logsDir,
|
||||
resolved.providerLogsDir,
|
||||
resolved.terminalLogsDir,
|
||||
resolved.attachmentsDir,
|
||||
resolved.worktreesDir,
|
||||
path.dirname(resolved.serverLogPath),
|
||||
]) {
|
||||
expect(yield* fs.exists(directory)).toBe(true);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
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,
|
||||
authToken: "bootstrap-token",
|
||||
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(),
|
||||
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
|
||||
noBrowser: Option.none(),
|
||||
authToken: Option.some("flag-token"),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
},
|
||||
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",
|
||||
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,
|
||||
authToken: "flag-token",
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
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 CliError from "effect/unstable/cli/CliError";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
|
||||
import { cli } from "./cli.ts";
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
|
||||
it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
|
||||
it.effect("accepts the built-in lowercase log-level flag values", () =>
|
||||
Command.runWith(cli, { version: "0.0.0" })(["--log-level", "debug", "--version"]).pipe(
|
||||
Effect.provide(CliRuntimeLayer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects invalid log-level casing before launching the server", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Command.runWith(cli, { version: "0.0.0" })([
|
||||
"--log-level",
|
||||
"Debug",
|
||||
]).pipe(Effect.provide(CliRuntimeLayer), Effect.flip);
|
||||
|
||||
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");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,292 @@
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { Config, Effect, LogLevel, Option, Schema } from "effect";
|
||||
import { Command, Flag, GlobalFlag } from "effect/unstable/cli";
|
||||
|
||||
import {
|
||||
DEFAULT_PORT,
|
||||
deriveServerPaths,
|
||||
ensureServerDirectories,
|
||||
resolveStaticDir,
|
||||
ServerConfig,
|
||||
RuntimeMode,
|
||||
type ServerConfigShape,
|
||||
} from "./config";
|
||||
import { readBootstrapEnvelope } from "./bootstrap";
|
||||
import { resolveBaseDir } from "./os-jank";
|
||||
import { runServer } from "./server";
|
||||
|
||||
const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
|
||||
|
||||
const BootstrapEnvelopeSchema = Schema.Struct({
|
||||
mode: Schema.optional(RuntimeMode),
|
||||
port: Schema.optional(PortSchema),
|
||||
host: Schema.optional(Schema.String),
|
||||
t3Home: Schema.optional(Schema.String),
|
||||
devUrl: Schema.optional(Schema.URLFromString),
|
||||
noBrowser: Schema.optional(Schema.Boolean),
|
||||
authToken: Schema.optional(Schema.String),
|
||||
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
|
||||
logWebSocketEvents: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
|
||||
const modeFlag = Flag.choice("mode", RuntimeMode.literals).pipe(
|
||||
Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
|
||||
Flag.optional,
|
||||
);
|
||||
const portFlag = Flag.integer("port").pipe(
|
||||
Flag.withSchema(PortSchema),
|
||||
Flag.withDescription("Port for the HTTP/WebSocket server."),
|
||||
Flag.optional,
|
||||
);
|
||||
const hostFlag = Flag.string("host").pipe(
|
||||
Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
|
||||
Flag.optional,
|
||||
);
|
||||
const baseDirFlag = Flag.string("base-dir").pipe(
|
||||
Flag.withDescription("Base directory path (equivalent to T3CODE_HOME)."),
|
||||
Flag.optional,
|
||||
);
|
||||
const devUrlFlag = Flag.string("dev-url").pipe(
|
||||
Flag.withSchema(Schema.URLFromString),
|
||||
Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
|
||||
Flag.optional,
|
||||
);
|
||||
const noBrowserFlag = Flag.boolean("no-browser").pipe(
|
||||
Flag.withDescription("Disable automatic browser opening."),
|
||||
Flag.optional,
|
||||
);
|
||||
const authTokenFlag = Flag.string("auth-token").pipe(
|
||||
Flag.withDescription("Auth token required for WebSocket connections."),
|
||||
Flag.withAlias("token"),
|
||||
Flag.optional,
|
||||
);
|
||||
const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
|
||||
Flag.withSchema(Schema.Int),
|
||||
Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
|
||||
Flag.optional,
|
||||
);
|
||||
const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
|
||||
Flag.withDescription(
|
||||
"Create a project for the current working directory on startup when missing.",
|
||||
),
|
||||
Flag.optional,
|
||||
);
|
||||
const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
|
||||
Flag.withDescription(
|
||||
"Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
|
||||
),
|
||||
Flag.withAlias("log-ws-events"),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
const EnvServerConfig = Config.all({
|
||||
logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
|
||||
mode: Config.schema(RuntimeMode, "T3CODE_MODE").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
authToken: Config.string("T3CODE_AUTH_TOKEN").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
});
|
||||
|
||||
interface CliServerFlags {
|
||||
readonly mode: Option.Option<RuntimeMode>;
|
||||
readonly port: Option.Option<number>;
|
||||
readonly host: Option.Option<string>;
|
||||
readonly baseDir: Option.Option<string>;
|
||||
readonly devUrl: Option.Option<URL>;
|
||||
readonly noBrowser: Option.Option<boolean>;
|
||||
readonly authToken: Option.Option<string>;
|
||||
readonly bootstrapFd: Option.Option<number>;
|
||||
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
|
||||
readonly logWebSocketEvents: Option.Option<boolean>;
|
||||
}
|
||||
|
||||
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
|
||||
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
|
||||
|
||||
const resolveOptionPrecedence = <Value>(
|
||||
...values: ReadonlyArray<Option.Option<Value>>
|
||||
): Option.Option<Value> => Option.firstSomeOf(values);
|
||||
|
||||
export const resolveServerConfig = (
|
||||
flags: CliServerFlags,
|
||||
cliLogLevel: Option.Option<LogLevel.LogLevel>,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const { findAvailablePort } = yield* NetService;
|
||||
const env = yield* EnvServerConfig;
|
||||
const bootstrapFd = Option.getOrUndefined(flags.bootstrapFd) ?? env.bootstrapFd;
|
||||
const bootstrapEnvelope =
|
||||
bootstrapFd !== undefined
|
||||
? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
|
||||
: Option.none();
|
||||
|
||||
const mode: RuntimeMode = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
flags.mode,
|
||||
Option.fromUndefinedOr(env.mode),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.mode)),
|
||||
),
|
||||
() => "web",
|
||||
);
|
||||
|
||||
const port = yield* Option.match(
|
||||
resolveOptionPrecedence(
|
||||
flags.port,
|
||||
Option.fromUndefinedOr(env.port),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.port)),
|
||||
),
|
||||
{
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
onNone: () => {
|
||||
if (mode === "desktop") {
|
||||
return Effect.succeed(DEFAULT_PORT);
|
||||
}
|
||||
return findAvailablePort(DEFAULT_PORT);
|
||||
},
|
||||
},
|
||||
);
|
||||
const devUrl = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
flags.devUrl,
|
||||
Option.fromUndefinedOr(env.devUrl),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.devUrl)),
|
||||
),
|
||||
() => undefined,
|
||||
);
|
||||
const baseDir = yield* resolveBaseDir(
|
||||
Option.getOrUndefined(
|
||||
resolveOptionPrecedence(
|
||||
flags.baseDir,
|
||||
Option.fromUndefinedOr(env.t3Home),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.t3Home),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
|
||||
yield* ensureServerDirectories(derivedPaths);
|
||||
const noBrowser = resolveBooleanFlag(
|
||||
flags.noBrowser,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.noBrowser),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.noBrowser),
|
||||
),
|
||||
),
|
||||
() => mode === "desktop",
|
||||
),
|
||||
);
|
||||
const authToken = Option.getOrUndefined(
|
||||
resolveOptionPrecedence(
|
||||
flags.authToken,
|
||||
Option.fromUndefinedOr(env.authToken),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.authToken),
|
||||
),
|
||||
),
|
||||
);
|
||||
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
|
||||
flags.autoBootstrapProjectFromCwd,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
|
||||
),
|
||||
),
|
||||
() => mode === "web",
|
||||
),
|
||||
);
|
||||
const logWebSocketEvents = resolveBooleanFlag(
|
||||
flags.logWebSocketEvents,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.logWebSocketEvents),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.logWebSocketEvents),
|
||||
),
|
||||
),
|
||||
() => Boolean(devUrl),
|
||||
),
|
||||
);
|
||||
const staticDir = devUrl ? undefined : yield* resolveStaticDir();
|
||||
const host = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
flags.host,
|
||||
Option.fromUndefinedOr(env.host),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
|
||||
),
|
||||
() => (mode === "desktop" ? "127.0.0.1" : undefined),
|
||||
);
|
||||
const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
|
||||
|
||||
const config: ServerConfigShape = {
|
||||
logLevel,
|
||||
mode,
|
||||
port,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
host,
|
||||
staticDir,
|
||||
devUrl,
|
||||
noBrowser,
|
||||
authToken,
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
};
|
||||
|
||||
return config;
|
||||
});
|
||||
|
||||
const commandFlags = {
|
||||
mode: modeFlag,
|
||||
port: portFlag,
|
||||
host: hostFlag,
|
||||
baseDir: baseDirFlag,
|
||||
devUrl: devUrlFlag,
|
||||
noBrowser: noBrowserFlag,
|
||||
authToken: authTokenFlag,
|
||||
bootstrapFd: bootstrapFdFlag,
|
||||
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
|
||||
logWebSocketEvents: logWebSocketEventsFlag,
|
||||
} as const;
|
||||
|
||||
const rootCommand = Command.make("t3", commandFlags).pipe(
|
||||
Command.withDescription("Run the T3 Code server."),
|
||||
Command.withHandler((flags) =>
|
||||
Effect.gen(function* () {
|
||||
const logLevel = yield* GlobalFlag.LogLevel;
|
||||
const config = yield* resolveServerConfig(flags, logLevel);
|
||||
return yield* runServer.pipe(Effect.provideService(ServerConfig, config));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
export const cli = rootCommand;
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
@@ -310,7 +310,7 @@ describe("readCodexAccountSnapshot", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps spark enabled for api key accounts", () => {
|
||||
it("disables spark for api key accounts", () => {
|
||||
expect(
|
||||
readCodexAccountSnapshot({
|
||||
type: "apiKey",
|
||||
@@ -318,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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -343,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", () => {
|
||||
|
||||
@@ -26,6 +26,15 @@ import {
|
||||
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;
|
||||
|
||||
@@ -96,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;
|
||||
@@ -162,50 +154,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.
|
||||
@@ -358,32 +306,13 @@ function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveCodexModelForAccount(
|
||||
model: string | undefined,
|
||||
account: CodexAccountSnapshot,
|
||||
): string | undefined {
|
||||
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
|
||||
return model;
|
||||
}
|
||||
|
||||
return CODEX_DEFAULT_MODEL;
|
||||
}
|
||||
|
||||
/**
|
||||
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
|
||||
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
|
||||
* 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 +331,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;
|
||||
@@ -516,7 +432,7 @@ export interface CodexAppServerManagerEvents {
|
||||
export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {
|
||||
private readonly sessions = new Map<ThreadId, CodexSessionContext>();
|
||||
|
||||
private runPromise: (effect: Effect.Effect<unknown, never>) => Promise<unknown>;
|
||||
private runPromise: (effect: Effect.Effect<unknown>) => Promise<unknown>;
|
||||
constructor(services?: ServiceMap.ServiceMap<never>) {
|
||||
super();
|
||||
this.runPromise = services ? Effect.runPromiseWith(services) : Effect.runPromise;
|
||||
|
||||
@@ -6,11 +6,12 @@
|
||||
*
|
||||
* @module ServerConfig
|
||||
*/
|
||||
import { Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
|
||||
import { Effect, FileSystem, Layer, LogLevel, Path, Schema, ServiceMap } 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;
|
||||
|
||||
/**
|
||||
* ServerDerivedPaths - Derived paths from the base directory.
|
||||
@@ -34,6 +35,7 @@ export interface ServerDerivedPaths {
|
||||
* ServerConfigShape - Process/runtime configuration required by the server.
|
||||
*/
|
||||
export interface ServerConfigShape extends ServerDerivedPaths {
|
||||
readonly logLevel: LogLevel.LogLevel;
|
||||
readonly mode: RuntimeMode;
|
||||
readonly port: number;
|
||||
readonly host: string | undefined;
|
||||
@@ -73,6 +75,26 @@ export const deriveServerPaths = Effect.fn(function* (
|
||||
};
|
||||
});
|
||||
|
||||
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 }),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* ServerConfig - Service tag for server runtime configuration.
|
||||
*/
|
||||
@@ -91,12 +113,10 @@ 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",
|
||||
cwd,
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
|
||||
@@ -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;
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import { expect } from "vitest";
|
||||
import { expect } from "vite-plus/test";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
|
||||
@@ -14,7 +14,7 @@ import { ClaudeModelSelection } from "@t3tools/contracts";
|
||||
import { resolveApiModelId } from "@t3tools/shared/model";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import {
|
||||
buildBranchNamePrompt,
|
||||
@@ -29,8 +29,9 @@ import {
|
||||
sanitizeThreadTitle,
|
||||
toJsonSchemaObject,
|
||||
} from "../Utils.ts";
|
||||
import { normalizeClaudeModelOptions } from "../../provider/Layers/ClaudeProvider.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;
|
||||
|
||||
@@ -84,8 +85,8 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
|
||||
const normalizedOptions = normalizeClaudeModelOptions(
|
||||
modelSelection.model,
|
||||
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
|
||||
getClaudeModelCapabilities(modelSelection.model),
|
||||
modelSelection.options,
|
||||
);
|
||||
const settings = {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path, Result } from "effect";
|
||||
import { expect } from "vitest";
|
||||
import { expect } from "vite-plus/test";
|
||||
|
||||
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";
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shar
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import {
|
||||
type BranchNameGenerationInput,
|
||||
type ThreadTitleGenerationResult,
|
||||
@@ -28,8 +28,9 @@ import {
|
||||
sanitizeThreadTitle,
|
||||
toJsonSchemaObject,
|
||||
} from "../Utils.ts";
|
||||
import { normalizeCodexModelOptions } from "../../provider/Layers/CodexProvider.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;
|
||||
@@ -81,7 +82,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
);
|
||||
};
|
||||
|
||||
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
||||
const safeUnlink = (filePath: string): Effect.Effect<void> =>
|
||||
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
const materializeImageAttachments = (
|
||||
@@ -156,8 +157,8 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
).pipe(Effect.catch(() => Effect.undefined));
|
||||
|
||||
const runCodexCommand = Effect.gen(function* () {
|
||||
const normalizedOptions = normalizeCodexModelOptions(
|
||||
modelSelection.model,
|
||||
const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
|
||||
getCodexModelCapabilities(modelSelection.model),
|
||||
modelSelection.options,
|
||||
);
|
||||
const reasoningEffort =
|
||||
|
||||
@@ -4,11 +4,11 @@ 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, vi } from "vitest";
|
||||
import { describe, expect, vi } from "vite-plus/test";
|
||||
|
||||
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";
|
||||
|
||||
@@ -138,6 +138,13 @@ function buildLargeText(lineCount = 20_000): string {
|
||||
.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) => {
|
||||
@@ -181,6 +188,55 @@ 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(" ") !== "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);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── listGitBranches ──
|
||||
|
||||
describe("listGitBranches", () => {
|
||||
@@ -313,12 +369,70 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
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();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const result = yield* (yield* GitCore).listBranches({ cwd: tmp });
|
||||
expect(result.branches.every((b) => b.isDefault === false)).toBe(true);
|
||||
expect(result.branches.every((b) => !b.isDefault)).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -457,12 +571,18 @@ 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 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,
|
||||
},
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -541,7 +661,13 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (input.args[0] === "fetch") {
|
||||
fetchArgs = [...input.args];
|
||||
return Effect.succeed({ code: 0, stdout: "", stderr: "" });
|
||||
return Effect.succeed({
|
||||
code: 0,
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
}
|
||||
return realGitCore.execute(input);
|
||||
});
|
||||
@@ -594,7 +720,13 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
if (input.args[0] === "fetch") {
|
||||
fetchStarted = true;
|
||||
return Effect.promise(() =>
|
||||
waitForReleasePromise.then(() => ({ code: 0, stdout: "", stderr: "" })),
|
||||
waitForReleasePromise.then(() => ({
|
||||
code: 0,
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
})),
|
||||
);
|
||||
}
|
||||
return realGitCore.execute(input);
|
||||
@@ -1824,7 +1956,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({
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
} from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { GitCommandError } from "../Errors.ts";
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
import {
|
||||
GitCore,
|
||||
type ExecuteGitProgress,
|
||||
@@ -37,6 +37,8 @@ const PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES = 49_000;
|
||||
const RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES = 19_000;
|
||||
const RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES = 19_000;
|
||||
const RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000;
|
||||
const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
|
||||
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
|
||||
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
|
||||
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
|
||||
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
|
||||
@@ -55,6 +57,7 @@ class StatusUpstreamRefreshCacheKey extends Data.Class<{
|
||||
}> {}
|
||||
|
||||
interface ExecuteGitOptions {
|
||||
stdin?: string | undefined;
|
||||
timeoutMs?: number | undefined;
|
||||
allowNonZeroExit?: boolean | undefined;
|
||||
fallbackErrorMessage?: string | undefined;
|
||||
@@ -96,6 +99,47 @@ function parseNumstatEntries(
|
||||
return entries;
|
||||
}
|
||||
|
||||
function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
|
||||
const parts = input.split("\0");
|
||||
if (parts.length === 0) return [];
|
||||
|
||||
if (truncated && parts[parts.length - 1]?.length) {
|
||||
parts.pop();
|
||||
}
|
||||
|
||||
return parts.filter((value) => value.length > 0);
|
||||
}
|
||||
|
||||
function chunkPathsForGitCheckIgnore(relativePaths: readonly string[]): string[][] {
|
||||
const chunks: string[][] = [];
|
||||
let chunk: string[] = [];
|
||||
let chunkBytes = 0;
|
||||
|
||||
for (const relativePath of relativePaths) {
|
||||
const relativePathBytes = Buffer.byteLength(relativePath) + 1;
|
||||
if (chunk.length > 0 && chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
|
||||
chunks.push(chunk);
|
||||
chunk = [];
|
||||
chunkBytes = 0;
|
||||
}
|
||||
|
||||
chunk.push(relativePath);
|
||||
chunkBytes += relativePathBytes;
|
||||
|
||||
if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
|
||||
chunks.push(chunk);
|
||||
chunk = [];
|
||||
chunkBytes = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (chunk.length > 0) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
|
||||
return chunks;
|
||||
}
|
||||
|
||||
function parsePorcelainPath(line: string): string | null {
|
||||
if (line.startsWith("? ") || line.startsWith("! ")) {
|
||||
const simple = line.slice(2).trim();
|
||||
@@ -280,7 +324,7 @@ function toGitCommandError(
|
||||
|
||||
interface Trace2Monitor {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly flush: Effect.Effect<void, never>;
|
||||
readonly flush: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
function trace2ChildKey(record: Record<string, unknown>): string | null {
|
||||
@@ -444,8 +488,8 @@ const collectOutput = Effect.fn("collectOutput")(function* <E>(
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
maxOutputBytes: number,
|
||||
truncateOutputAtMaxBytes: boolean,
|
||||
onLine: ((line: string) => Effect.Effect<void, never>) | undefined,
|
||||
): Effect.fn.Return<string, GitCommandError> {
|
||||
onLine: ((line: string) => Effect.Effect<void>) | undefined,
|
||||
): Effect.fn.Return<{ readonly text: string; readonly truncated: boolean }, GitCommandError> {
|
||||
const decoder = new TextDecoder();
|
||||
let bytes = 0;
|
||||
let text = "";
|
||||
@@ -507,7 +551,10 @@ const collectOutput = Effect.fn("collectOutput")(function* <E>(
|
||||
text += remainder;
|
||||
lineBuffer += remainder;
|
||||
yield* emitCompleteLines(true);
|
||||
return truncated ? `${text}${OUTPUT_TRUNCATED_MARKER}` : text;
|
||||
return {
|
||||
text,
|
||||
truncated,
|
||||
};
|
||||
});
|
||||
|
||||
export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
@@ -571,13 +618,18 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
Effect.map((value) => Number(value)),
|
||||
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
|
||||
),
|
||||
input.stdin === undefined
|
||||
? Effect.void
|
||||
: Stream.run(Stream.encodeText(Stream.make(input.stdin)), child.stdin).pipe(
|
||||
Effect.mapError(toGitCommandError(commandInput, "failed to write stdin.")),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
).pipe(Effect.map(([stdout, stderr, exitCode]) => [stdout, stderr, exitCode] as const));
|
||||
yield* trace2Monitor.flush;
|
||||
|
||||
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||
const trimmedStderr = stderr.trim();
|
||||
const trimmedStderr = stderr.text.trim();
|
||||
return yield* new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
@@ -589,7 +641,13 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
});
|
||||
}
|
||||
|
||||
return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
|
||||
return {
|
||||
code: exitCode,
|
||||
stdout: stdout.text,
|
||||
stderr: stderr.text,
|
||||
stdoutTruncated: stdout.truncated,
|
||||
stderrTruncated: stderr.truncated,
|
||||
} satisfies ExecuteGitResult;
|
||||
});
|
||||
|
||||
return yield* runGitCommand().pipe(
|
||||
@@ -618,11 +676,12 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
options: ExecuteGitOptions = {},
|
||||
): Effect.Effect<{ code: number; stdout: string; stderr: string }, GitCommandError> =>
|
||||
): Effect.Effect<ExecuteGitResult, GitCommandError> =>
|
||||
execute({
|
||||
operation,
|
||||
cwd,
|
||||
args,
|
||||
...(options.stdin !== undefined ? { stdin: options.stdin } : {}),
|
||||
allowNonZeroExit: true,
|
||||
...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
|
||||
...(options.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
|
||||
@@ -679,7 +738,11 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
args: readonly string[],
|
||||
options: ExecuteGitOptions = {},
|
||||
): Effect.Effect<string, GitCommandError> =>
|
||||
executeGit(operation, cwd, args, options).pipe(Effect.map((result) => result.stdout));
|
||||
executeGit(operation, cwd, args, options).pipe(
|
||||
Effect.map((result) =>
|
||||
result.stdoutTruncated ? `${result.stdout}${OUTPUT_TRUNCATED_MARKER}` : result.stdout,
|
||||
),
|
||||
);
|
||||
|
||||
const branchExists = (cwd: string, branch: string): Effect.Effect<boolean, GitCommandError> =>
|
||||
executeGit(
|
||||
@@ -1416,6 +1479,86 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)),
|
||||
);
|
||||
|
||||
const isInsideWorkTree: GitCoreShape["isInsideWorkTree"] = (cwd) =>
|
||||
executeGit("GitCore.isInsideWorkTree", cwd, ["rev-parse", "--is-inside-work-tree"], {
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 4_096,
|
||||
}).pipe(Effect.map((result) => result.code === 0 && result.stdout.trim() === "true"));
|
||||
|
||||
const listWorkspaceFiles: GitCoreShape["listWorkspaceFiles"] = (cwd) =>
|
||||
executeGit(
|
||||
"GitCore.listWorkspaceFiles",
|
||||
cwd,
|
||||
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.code === 0
|
||||
? Effect.succeed({
|
||||
paths: splitNullSeparatedPaths(result.stdout, result.stdoutTruncated),
|
||||
truncated: result.stdoutTruncated,
|
||||
})
|
||||
: Effect.fail(
|
||||
createGitCommandError(
|
||||
"GitCore.listWorkspaceFiles",
|
||||
cwd,
|
||||
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
||||
result.stderr.trim().length > 0 ? result.stderr.trim() : "git ls-files failed",
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const filterIgnoredPaths: GitCoreShape["filterIgnoredPaths"] = (cwd, relativePaths) =>
|
||||
Effect.gen(function* () {
|
||||
if (relativePaths.length === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
const ignoredPaths = new Set<string>();
|
||||
const chunks = chunkPathsForGitCheckIgnore(relativePaths);
|
||||
|
||||
for (const chunk of chunks) {
|
||||
const result = yield* executeGit(
|
||||
"GitCore.filterIgnoredPaths",
|
||||
cwd,
|
||||
["check-ignore", "--no-index", "-z", "--stdin"],
|
||||
{
|
||||
stdin: `${chunk.join("\0")}\0`,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
},
|
||||
);
|
||||
|
||||
if (result.code !== 0 && result.code !== 1) {
|
||||
return yield* createGitCommandError(
|
||||
"GitCore.filterIgnoredPaths",
|
||||
cwd,
|
||||
["check-ignore", "--no-index", "-z", "--stdin"],
|
||||
result.stderr.trim().length > 0 ? result.stderr.trim() : "git check-ignore failed",
|
||||
);
|
||||
}
|
||||
|
||||
for (const ignoredPath of splitNullSeparatedPaths(result.stdout, result.stdoutTruncated)) {
|
||||
ignoredPaths.add(ignoredPath);
|
||||
}
|
||||
}
|
||||
|
||||
if (ignoredPaths.size === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
|
||||
});
|
||||
|
||||
const listBranches: GitCoreShape["listBranches"] = Effect.fn("listBranches")(function* (input) {
|
||||
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
|
||||
Effect.catch(() => Effect.succeed(new Map<string, number>())),
|
||||
@@ -1423,7 +1566,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
const localBranchResult = yield* executeGit(
|
||||
"GitCore.listBranches.branchNoColor",
|
||||
input.cwd,
|
||||
["branch", "--no-color"],
|
||||
["branch", "--no-color", "--no-column"],
|
||||
{
|
||||
timeoutMs: 10_000,
|
||||
allowNonZeroExit: true,
|
||||
@@ -1438,7 +1581,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
return yield* createGitCommandError(
|
||||
"GitCore.listBranches",
|
||||
input.cwd,
|
||||
["branch", "--no-color"],
|
||||
["branch", "--no-color", "--no-column"],
|
||||
stderr || "git branch failed",
|
||||
);
|
||||
}
|
||||
@@ -1446,7 +1589,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
const remoteBranchResultEffect = executeGit(
|
||||
"GitCore.listBranches.remoteBranches",
|
||||
input.cwd,
|
||||
["branch", "--no-color", "--remotes"],
|
||||
["branch", "--no-color", "--no-column", "--remotes"],
|
||||
{
|
||||
timeoutMs: 10_000,
|
||||
allowNonZeroExit: true,
|
||||
@@ -1798,8 +1941,9 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
});
|
||||
|
||||
// Refresh upstream refs in the background so checkout remains responsive.
|
||||
yield* Effect.forkScoped(
|
||||
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.ignoreCause({ log: true })),
|
||||
yield* refreshCheckedOutBranchUpstream(input.cwd).pipe(
|
||||
Effect.ignoreCause({ log: true }),
|
||||
Effect.forkDetach({ startImmediately: true }),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -1814,6 +1958,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
runGitStdout("GitCore.listLocalBranchNames", cwd, [
|
||||
"branch",
|
||||
"--list",
|
||||
"--no-column",
|
||||
"--format=%(refname:short)",
|
||||
]).pipe(
|
||||
Effect.map((stdout) =>
|
||||
@@ -1834,6 +1979,9 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
pullCurrentBranch,
|
||||
readRangeContext,
|
||||
readConfigValue,
|
||||
isInsideWorkTree,
|
||||
listWorkspaceFiles,
|
||||
filterIgnoredPaths,
|
||||
listBranches,
|
||||
createWorktree,
|
||||
fetchPullRequestBranch,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect } from "effect";
|
||||
import { afterEach, expect, vi } from "vitest";
|
||||
import { afterEach, expect, vi } from "vite-plus/test";
|
||||
|
||||
vi.mock("../../processRunner", () => ({
|
||||
runProcess: vi.fn(),
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Effect, Layer, Schema } 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,
|
||||
|
||||
@@ -5,10 +5,10 @@ import { spawnSync } from "node:child_process";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
||||
import { expect } from "vitest";
|
||||
import { expect } from "vite-plus/test";
|
||||
import type { GitActionProgressEvent, ModelSelection } from "@t3tools/contracts";
|
||||
|
||||
import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts";
|
||||
import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts";
|
||||
import { type GitManagerShape } from "../Services/GitManager.ts";
|
||||
import {
|
||||
type GitHubCliShape,
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
sanitizeFeatureBranchName,
|
||||
} from "@t3tools/shared/git";
|
||||
|
||||
import { GitManagerError } from "../Errors.ts";
|
||||
import { GitManagerError } from "@t3tools/contracts";
|
||||
import {
|
||||
GitManager,
|
||||
type GitActionProgressReporter,
|
||||
@@ -25,7 +25,7 @@ import { GitCore } from "../Services/GitCore.ts";
|
||||
import { GitHubCli } from "../Services/GitHubCli.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import type { GitManagerServiceError } from "../Errors.ts";
|
||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||
|
||||
const COMMIT_TIMEOUT_MS = 10 * 60_000;
|
||||
const MAX_PROGRESS_TEXT_LENGTH = 500;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
buildBranchNamePrompt,
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
buildThreadTitlePrompt,
|
||||
} from "./Prompts.ts";
|
||||
import { normalizeCliError, sanitizeThreadTitle } from "./Utils.ts";
|
||||
import { TextGenerationError } from "./Errors.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
|
||||
describe("buildCommitMessagePrompt", () => {
|
||||
it("includes staged patch and summary in the prompt", () => {
|
||||
|
||||
@@ -22,12 +22,13 @@ import type {
|
||||
GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import type { GitCommandError } from "../Errors.ts";
|
||||
import type { GitCommandError } from "@t3tools/contracts";
|
||||
|
||||
export interface ExecuteGitInput {
|
||||
readonly operation: string;
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly stdin?: string;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
@@ -40,6 +41,8 @@ export interface ExecuteGitResult {
|
||||
readonly code: number;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly stdoutTruncated: boolean;
|
||||
readonly stderrTruncated: boolean;
|
||||
}
|
||||
|
||||
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
|
||||
@@ -52,27 +55,27 @@ export interface GitPreparedCommitContext {
|
||||
}
|
||||
|
||||
export interface ExecuteGitProgress {
|
||||
readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
|
||||
readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
|
||||
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
|
||||
readonly onStdoutLine?: (line: string) => Effect.Effect<void>;
|
||||
readonly onStderrLine?: (line: string) => Effect.Effect<void>;
|
||||
readonly onHookStarted?: (hookName: string) => Effect.Effect<void>;
|
||||
readonly onHookFinished?: (input: {
|
||||
hookName: string;
|
||||
exitCode: number | null;
|
||||
durationMs: number | null;
|
||||
}) => Effect.Effect<void, never>;
|
||||
}) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface GitCommitProgress {
|
||||
readonly onOutputLine?: (input: {
|
||||
stream: "stdout" | "stderr";
|
||||
text: string;
|
||||
}) => Effect.Effect<void, never>;
|
||||
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly onHookStarted?: (hookName: string) => Effect.Effect<void>;
|
||||
readonly onHookFinished?: (input: {
|
||||
hookName: string;
|
||||
exitCode: number | null;
|
||||
durationMs: number | null;
|
||||
}) => Effect.Effect<void, never>;
|
||||
}) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface GitCommitOptions {
|
||||
@@ -93,6 +96,11 @@ export interface GitRangeContext {
|
||||
diffPatch: string;
|
||||
}
|
||||
|
||||
export interface GitListWorkspaceFilesResult {
|
||||
readonly paths: ReadonlyArray<string>;
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
|
||||
export interface GitRenameBranchInput {
|
||||
cwd: string;
|
||||
oldBranch: string;
|
||||
@@ -190,6 +198,26 @@ export interface GitCoreShape {
|
||||
key: string,
|
||||
) => Effect.Effect<string | null, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Determine whether the provided cwd is inside a git work tree.
|
||||
*/
|
||||
readonly isInsideWorkTree: (cwd: string) => Effect.Effect<boolean, GitCommandError>;
|
||||
|
||||
/**
|
||||
* List tracked and untracked workspace file paths relative to cwd.
|
||||
*/
|
||||
readonly listWorkspaceFiles: (
|
||||
cwd: string,
|
||||
) => Effect.Effect<GitListWorkspaceFilesResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Remove gitignored paths from a relative path list.
|
||||
*/
|
||||
readonly filterIgnoredPaths: (
|
||||
cwd: string,
|
||||
relativePaths: ReadonlyArray<string>,
|
||||
) => Effect.Effect<ReadonlyArray<string>, GitCommandError>;
|
||||
|
||||
/**
|
||||
* List local + remote branches and branch metadata.
|
||||
*/
|
||||
|
||||
@@ -9,7 +9,7 @@ import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProcessRunResult } from "../../processRunner";
|
||||
import type { GitHubCliError } from "../Errors.ts";
|
||||
import type { GitHubCliError } from "@t3tools/contracts";
|
||||
|
||||
export interface GitHubPullRequestSummary {
|
||||
readonly number: number;
|
||||
|
||||
@@ -19,10 +19,10 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type { GitManagerServiceError } from "../Errors.ts";
|
||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||
|
||||
export interface GitActionProgressReporter {
|
||||
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
|
||||
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface GitRunStackedActionOptions {
|
||||
|
||||
@@ -10,7 +10,7 @@ import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
|
||||
|
||||
import type { TextGenerationError } from "../Errors.ts";
|
||||
import type { TextGenerationError } from "@t3tools/contracts";
|
||||
|
||||
/** Providers that support git text generation (commit messages, PR content, branch names). */
|
||||
export type TextGenerationProvider = "codex" | "claudeAgent";
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
import { Schema } from "effect";
|
||||
|
||||
import { TextGenerationError } from "./Errors.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
import Mime from "@effect/platform-node/Mime";
|
||||
import { Effect, FileSystem, Option, Path } from "effect";
|
||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
|
||||
import {
|
||||
ATTACHMENTS_ROUTE_PREFIX,
|
||||
normalizeAttachmentRelativePath,
|
||||
resolveAttachmentRelativePath,
|
||||
} from "./attachmentPaths";
|
||||
import { resolveAttachmentPathById } from "./attachmentStore";
|
||||
import { ServerConfig } from "./config";
|
||||
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver";
|
||||
|
||||
const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600";
|
||||
const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
|
||||
|
||||
export const attachmentsRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
`${ATTACHMENTS_ROUTE_PREFIX}/*`,
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const url = HttpServerRequest.toURL(request);
|
||||
if (Option.isNone(url)) {
|
||||
return HttpServerResponse.text("Bad Request", { status: 400 });
|
||||
}
|
||||
|
||||
const config = yield* ServerConfig;
|
||||
const rawRelativePath = url.value.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
|
||||
const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
|
||||
if (!normalizedRelativePath) {
|
||||
return HttpServerResponse.text("Invalid attachment path", { status: 400 });
|
||||
}
|
||||
|
||||
const isIdLookup =
|
||||
!normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
|
||||
const filePath = isIdLookup
|
||||
? resolveAttachmentPathById({
|
||||
attachmentsDir: config.attachmentsDir,
|
||||
attachmentId: normalizedRelativePath,
|
||||
})
|
||||
: resolveAttachmentRelativePath({
|
||||
attachmentsDir: config.attachmentsDir,
|
||||
relativePath: normalizedRelativePath,
|
||||
});
|
||||
if (!filePath) {
|
||||
return HttpServerResponse.text(isIdLookup ? "Not Found" : "Invalid attachment path", {
|
||||
status: isIdLookup ? 404 : 400,
|
||||
});
|
||||
}
|
||||
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(filePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
return HttpServerResponse.text("Not Found", { status: 404 });
|
||||
}
|
||||
|
||||
return yield* HttpServerResponse.file(filePath, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Cache-Control": "public, max-age=31536000, immutable",
|
||||
},
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
export const projectFaviconRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
"/api/project-favicon",
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const url = HttpServerRequest.toURL(request);
|
||||
if (Option.isNone(url)) {
|
||||
return HttpServerResponse.text("Bad Request", { status: 400 });
|
||||
}
|
||||
|
||||
const projectCwd = url.value.searchParams.get("cwd");
|
||||
if (!projectCwd) {
|
||||
return HttpServerResponse.text("Missing cwd parameter", { status: 400 });
|
||||
}
|
||||
|
||||
const faviconResolver = yield* ProjectFaviconResolver;
|
||||
const faviconFilePath = yield* faviconResolver.resolvePath(projectCwd);
|
||||
if (!faviconFilePath) {
|
||||
return HttpServerResponse.text(FALLBACK_PROJECT_FAVICON_SVG, {
|
||||
status: 200,
|
||||
contentType: "image/svg+xml",
|
||||
headers: {
|
||||
"Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return yield* HttpServerResponse.file(faviconFilePath, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
|
||||
},
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
"*",
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const url = HttpServerRequest.toURL(request);
|
||||
if (Option.isNone(url)) {
|
||||
return HttpServerResponse.text("Bad Request", { status: 400 });
|
||||
}
|
||||
|
||||
const config = yield* ServerConfig;
|
||||
if (config.devUrl) {
|
||||
return HttpServerResponse.redirect(config.devUrl.href, { status: 302 });
|
||||
}
|
||||
|
||||
if (!config.staticDir) {
|
||||
return HttpServerResponse.text("No static directory configured and no dev URL set.", {
|
||||
status: 503,
|
||||
});
|
||||
}
|
||||
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const staticRoot = path.resolve(config.staticDir);
|
||||
const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
|
||||
const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
|
||||
const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
|
||||
const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
|
||||
const hasPathTraversalSegment = staticRelativePath.startsWith("..");
|
||||
if (
|
||||
staticRelativePath.length === 0 ||
|
||||
hasRawLeadingParentSegment ||
|
||||
hasPathTraversalSegment ||
|
||||
staticRelativePath.includes("\0")
|
||||
) {
|
||||
return HttpServerResponse.text("Invalid static file path", { status: 400 });
|
||||
}
|
||||
|
||||
const isWithinStaticRoot = (candidate: string) =>
|
||||
candidate === staticRoot ||
|
||||
candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`);
|
||||
|
||||
let filePath = path.resolve(staticRoot, staticRelativePath);
|
||||
if (!isWithinStaticRoot(filePath)) {
|
||||
return HttpServerResponse.text("Invalid static file path", { status: 400 });
|
||||
}
|
||||
|
||||
const ext = path.extname(filePath);
|
||||
if (!ext) {
|
||||
filePath = path.resolve(filePath, "index.html");
|
||||
if (!isWithinStaticRoot(filePath)) {
|
||||
return HttpServerResponse.text("Invalid static file path", { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(filePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
const indexPath = path.resolve(staticRoot, "index.html");
|
||||
const indexData = yield* fileSystem
|
||||
.readFile(indexPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!indexData) {
|
||||
return HttpServerResponse.text("Not Found", { status: 404 });
|
||||
}
|
||||
return HttpServerResponse.uint8Array(indexData, {
|
||||
status: 200,
|
||||
contentType: "text/html; charset=utf-8",
|
||||
});
|
||||
}
|
||||
|
||||
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
|
||||
const data = yield* fileSystem
|
||||
.readFile(filePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!data) {
|
||||
return HttpServerResponse.text("Internal Server Error", { status: 500 });
|
||||
}
|
||||
|
||||
return HttpServerResponse.uint8Array(data, {
|
||||
status: 200,
|
||||
contentType,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
|
||||
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { CliConfig, t3Cli } from "./main";
|
||||
import { OpenLive } from "./open";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
import { version } from "../package.json" with { type: "json" };
|
||||
import { ServerLive } from "./wsServer";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
|
||||
const RuntimeLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(CliConfig.layer),
|
||||
Layer.provideMerge(ServerLive),
|
||||
Layer.provideMerge(OpenLive),
|
||||
Layer.provideMerge(NetService.layer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(FetchHttpClient.layer),
|
||||
);
|
||||
|
||||
Command.run(t3Cli, { version }).pipe(Effect.provide(RuntimeLayer), NodeRuntime.runMain);
|
||||
@@ -8,13 +8,13 @@ import { ServerConfig } from "./config";
|
||||
import {
|
||||
DEFAULT_KEYBINDINGS,
|
||||
Keybindings,
|
||||
KeybindingsConfigError,
|
||||
KeybindingsLive,
|
||||
ResolvedKeybindingFromConfig,
|
||||
compileResolvedKeybindingRule,
|
||||
compileResolvedKeybindingsConfig,
|
||||
parseKeybindingShortcut,
|
||||
} from "./keybindings";
|
||||
import { KeybindingsConfigError } from "@t3tools/contracts";
|
||||
|
||||
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
|
||||
const makeKeybindingsLayer = () => {
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
import {
|
||||
KeybindingRule,
|
||||
KeybindingsConfig,
|
||||
KeybindingsConfigError,
|
||||
KeybindingShortcut,
|
||||
KeybindingWhenNode,
|
||||
MAX_KEYBINDINGS_COUNT,
|
||||
@@ -46,19 +47,6 @@ import * as Semaphore from "effect/Semaphore";
|
||||
import { ServerConfig } from "./config";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
|
||||
export class KeybindingsConfigError extends Schema.TaggedErrorClass<KeybindingsConfigError>()(
|
||||
"KeybindingsConfigParseError",
|
||||
{
|
||||
configPath: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Unable to parse keybindings config at ${this.configPath}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
type WhenToken =
|
||||
| { type: "identifier"; value: string }
|
||||
| { type: "not" }
|
||||
|
||||
@@ -1,103 +0,0 @@
|
||||
import util from "node:util";
|
||||
|
||||
type LogLevel = "info" | "warn" | "error" | "event";
|
||||
|
||||
type LogContext = Record<string, unknown>;
|
||||
|
||||
const ANSI = {
|
||||
reset: "\u001b[0m",
|
||||
dim: "\u001b[2m",
|
||||
cyan: "\u001b[36m",
|
||||
yellow: "\u001b[33m",
|
||||
red: "\u001b[31m",
|
||||
magenta: "\u001b[35m",
|
||||
} as const;
|
||||
|
||||
const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||
info: "INFO",
|
||||
warn: "WARN",
|
||||
error: "ERROR",
|
||||
event: "EVENT",
|
||||
};
|
||||
|
||||
const LEVEL_COLOR: Record<LogLevel, string> = {
|
||||
info: ANSI.cyan,
|
||||
warn: ANSI.yellow,
|
||||
error: ANSI.red,
|
||||
event: ANSI.magenta,
|
||||
};
|
||||
|
||||
function useColors() {
|
||||
return Boolean(process.stdout.isTTY) && process.env.NO_COLOR === undefined;
|
||||
}
|
||||
|
||||
function colorize(value: string, color: string, enabled: boolean) {
|
||||
return enabled ? `${color}${value}${ANSI.reset}` : value;
|
||||
}
|
||||
|
||||
function timeStamp() {
|
||||
return new Date().toISOString().slice(11, 23);
|
||||
}
|
||||
|
||||
function formatValue(value: unknown) {
|
||||
if (typeof value === "string") {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
if (
|
||||
typeof value === "number" ||
|
||||
typeof value === "boolean" ||
|
||||
value === null ||
|
||||
value === undefined
|
||||
) {
|
||||
return String(value);
|
||||
}
|
||||
return util.inspect(value, {
|
||||
depth: 4,
|
||||
breakLength: Infinity,
|
||||
compact: true,
|
||||
maxArrayLength: 25,
|
||||
maxStringLength: 320,
|
||||
});
|
||||
}
|
||||
|
||||
function formatContext(context: LogContext | undefined) {
|
||||
if (!context) return "";
|
||||
const entries = Object.entries(context).filter(([, value]) => value !== undefined);
|
||||
if (entries.length === 0) return "";
|
||||
return entries.map(([key, value]) => `${key}=${formatValue(value)}`).join(" ");
|
||||
}
|
||||
|
||||
function write(level: LogLevel, scope: string, message: string, context?: LogContext) {
|
||||
const colorEnabled = useColors();
|
||||
const ts = colorize(timeStamp(), ANSI.dim, colorEnabled);
|
||||
const levelLabel = colorize(LEVEL_LABEL[level], LEVEL_COLOR[level], colorEnabled);
|
||||
const contextText = formatContext(context);
|
||||
const line = `${ts} ${levelLabel} [${scope}] ${message}${contextText ? ` ${contextText}` : ""}`;
|
||||
|
||||
if (level === "warn") {
|
||||
console.warn(line);
|
||||
return;
|
||||
}
|
||||
if (level === "error") {
|
||||
console.error(line);
|
||||
return;
|
||||
}
|
||||
console.log(line);
|
||||
}
|
||||
|
||||
export function createLogger(scope: string) {
|
||||
return {
|
||||
info(message: string, context?: LogContext) {
|
||||
write("info", scope, message, context);
|
||||
},
|
||||
warn(message: string, context?: LogContext) {
|
||||
write("warn", scope, message, context);
|
||||
},
|
||||
error(message: string, context?: LogContext) {
|
||||
write("error", scope, message, context);
|
||||
},
|
||||
event(message: string, context?: LogContext) {
|
||||
write("event", scope, message, context);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,413 +0,0 @@
|
||||
import * as Http from "node:http";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it, vi } from "@effect/vitest";
|
||||
import type { OrchestrationReadModel } from "@t3tools/contracts";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Command from "effect/unstable/cli/Command";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
import { beforeEach } from "vitest";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
import { CliConfig, recordStartupHeartbeat, t3Cli, type CliConfigShape } from "./main";
|
||||
import { ServerConfig, type ServerConfigShape } from "./config";
|
||||
import { Open, type OpenShape } from "./open";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
import { Server, type ServerShape } from "./wsServer";
|
||||
import { ServerSettingsService } from "./serverSettings";
|
||||
|
||||
const start = vi.fn(() => undefined);
|
||||
const stop = vi.fn(() => undefined);
|
||||
const fixPath = vi.fn(() => undefined);
|
||||
let resolvedConfig: ServerConfigShape | null = null;
|
||||
const serverStart = Effect.acquireRelease(
|
||||
Effect.gen(function* () {
|
||||
resolvedConfig = yield* ServerConfig;
|
||||
start();
|
||||
return {} as unknown as Http.Server;
|
||||
}),
|
||||
() => Effect.sync(() => stop()),
|
||||
);
|
||||
const findAvailablePort = vi.fn((preferred: number) => Effect.succeed(preferred));
|
||||
|
||||
// Shared service layer used by this CLI test suite.
|
||||
const testLayer = Layer.mergeAll(
|
||||
Layer.succeed(CliConfig, {
|
||||
cwd: "/tmp/t3-test-workspace",
|
||||
fixPath: Effect.sync(fixPath),
|
||||
resolveStaticDir: Effect.undefined,
|
||||
} satisfies CliConfigShape),
|
||||
Layer.succeed(NetService, {
|
||||
canListenOnHost: () => Effect.succeed(true),
|
||||
isPortAvailableOnLoopback: () => Effect.succeed(true),
|
||||
reserveLoopbackPort: () => Effect.succeed(0),
|
||||
findAvailablePort,
|
||||
}),
|
||||
Layer.succeed(Server, {
|
||||
start: serverStart,
|
||||
stopSignal: Effect.void,
|
||||
} satisfies ServerShape),
|
||||
Layer.succeed(Open, {
|
||||
openBrowser: (_target: string) => Effect.void,
|
||||
openInEditor: () => Effect.void,
|
||||
} satisfies OpenShape),
|
||||
ServerSettingsService.layerTest(),
|
||||
AnalyticsService.layerTest,
|
||||
FetchHttpClient.layer,
|
||||
NodeServices.layer,
|
||||
);
|
||||
|
||||
const runCli = (
|
||||
args: ReadonlyArray<string>,
|
||||
env: Record<string, string> = { T3CODE_NO_BROWSER: "true" },
|
||||
) => {
|
||||
return Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe(
|
||||
Effect.provide(
|
||||
ConfigProvider.layer(
|
||||
ConfigProvider.fromEnv({
|
||||
env: {
|
||||
...env,
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
resolvedConfig = null;
|
||||
start.mockImplementation(() => undefined);
|
||||
stop.mockImplementation(() => undefined);
|
||||
fixPath.mockImplementation(() => undefined);
|
||||
findAvailablePort.mockImplementation((preferred: number) => Effect.succeed(preferred));
|
||||
});
|
||||
|
||||
it.layer(testLayer)("server CLI command", (it) => {
|
||||
it.effect("parses all CLI flags and wires scoped start/stop", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli([
|
||||
"--mode",
|
||||
"desktop",
|
||||
"--port",
|
||||
"4010",
|
||||
"--host",
|
||||
"0.0.0.0",
|
||||
"--home-dir",
|
||||
"/tmp/t3-cli-home",
|
||||
"--dev-url",
|
||||
"http://127.0.0.1:5173",
|
||||
"--no-browser",
|
||||
"--auth-token",
|
||||
"auth-secret",
|
||||
]);
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "desktop");
|
||||
assert.equal(resolvedConfig?.port, 4010);
|
||||
assert.equal(resolvedConfig?.host, "0.0.0.0");
|
||||
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-cli-home");
|
||||
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-cli-home/dev");
|
||||
assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/");
|
||||
assert.equal(resolvedConfig?.noBrowser, true);
|
||||
assert.equal(resolvedConfig?.authToken, "auth-secret");
|
||||
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, false);
|
||||
assert.equal(resolvedConfig?.logWebSocketEvents, true);
|
||||
assert.equal(stop.mock.calls.length, 1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("supports --token as an alias for --auth-token", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--token", "token-secret"]);
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.authToken, "token-secret");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses env fallbacks when flags are not provided", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli([], {
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_PORT: "4999",
|
||||
T3CODE_HOST: "100.88.10.4",
|
||||
T3CODE_HOME: "/tmp/t3-env-home",
|
||||
VITE_DEV_SERVER_URL: "http://localhost:5173",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
T3CODE_AUTH_TOKEN: "env-token",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "desktop");
|
||||
assert.equal(resolvedConfig?.port, 4999);
|
||||
assert.equal(resolvedConfig?.host, "100.88.10.4");
|
||||
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-env-home");
|
||||
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-env-home/dev");
|
||||
assert.equal(resolvedConfig?.devUrl?.toString(), "http://localhost:5173/");
|
||||
assert.equal(resolvedConfig?.noBrowser, true);
|
||||
assert.equal(resolvedConfig?.authToken, "env-token");
|
||||
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, false);
|
||||
assert.equal(resolvedConfig?.logWebSocketEvents, true);
|
||||
assert.equal(findAvailablePort.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
const openBootstrapFd = Effect.fn(function* (payload: Record<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("recognizes bootstrap fd from environment config", () =>
|
||||
Effect.gen(function* () {
|
||||
const fd = yield* openBootstrapFd({ authToken: "bootstrap-token" });
|
||||
|
||||
yield* runCli([], {
|
||||
T3CODE_MODE: "web",
|
||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||
T3CODE_AUTH_TOKEN: "env-token",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
assert.equal(resolvedConfig?.authToken, "env-token");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses bootstrap envelope values as fallbacks when CLI and env are absent", () =>
|
||||
Effect.gen(function* () {
|
||||
const fd = yield* openBootstrapFd({
|
||||
mode: "desktop",
|
||||
port: 4888,
|
||||
host: "127.0.0.2",
|
||||
t3Home: "/tmp/t3-bootstrap-home",
|
||||
devUrl: "http://127.0.0.1:5173",
|
||||
noBrowser: true,
|
||||
authToken: "bootstrap-token",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
|
||||
yield* runCli([], {
|
||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "desktop");
|
||||
assert.equal(resolvedConfig?.port, 4888);
|
||||
assert.equal(resolvedConfig?.host, "127.0.0.2");
|
||||
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-bootstrap-home");
|
||||
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-bootstrap-home/dev");
|
||||
assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/");
|
||||
assert.equal(resolvedConfig?.noBrowser, true);
|
||||
assert.equal(resolvedConfig?.authToken, "bootstrap-token");
|
||||
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, false);
|
||||
assert.equal(resolvedConfig?.logWebSocketEvents, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("applies CLI then env precedence over bootstrap envelope values", () =>
|
||||
Effect.gen(function* () {
|
||||
const fd = yield* openBootstrapFd({
|
||||
mode: "desktop",
|
||||
port: 4888,
|
||||
host: "127.0.0.2",
|
||||
t3Home: "/tmp/t3-bootstrap-home",
|
||||
devUrl: "http://127.0.0.1:5173",
|
||||
noBrowser: false,
|
||||
authToken: "bootstrap-token",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
});
|
||||
|
||||
yield* runCli(["--port", "4999", "--host", "0.0.0.0", "--auth-token", "cli-token"], {
|
||||
T3CODE_MODE: "web",
|
||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||
T3CODE_HOME: "/tmp/t3-env-home",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
|
||||
T3CODE_LOG_WS_EVENTS: "true",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
assert.equal(resolvedConfig?.port, 4999);
|
||||
assert.equal(resolvedConfig?.host, "0.0.0.0");
|
||||
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-env-home");
|
||||
assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/");
|
||||
assert.equal(resolvedConfig?.noBrowser, true);
|
||||
assert.equal(resolvedConfig?.authToken, "cli-token");
|
||||
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, true);
|
||||
assert.equal(resolvedConfig?.logWebSocketEvents, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers --mode over T3CODE_MODE", () =>
|
||||
Effect.gen(function* () {
|
||||
findAvailablePort.mockImplementation((_preferred: number) => Effect.succeed(4666));
|
||||
yield* runCli(["--mode", "web"], {
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(findAvailablePort.mock.calls, [[3773]]);
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
assert.equal(resolvedConfig?.port, 4666);
|
||||
assert.equal(resolvedConfig?.host, undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers --no-browser over T3CODE_NO_BROWSER", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--no-browser"], {
|
||||
T3CODE_NO_BROWSER: "false",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.noBrowser, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses dynamic port discovery in web mode when port is omitted", () =>
|
||||
Effect.gen(function* () {
|
||||
findAvailablePort.mockImplementation((_preferred: number) => Effect.succeed(5444));
|
||||
yield* runCli([]);
|
||||
|
||||
assert.deepStrictEqual(findAvailablePort.mock.calls, [[3773]]);
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.port, 5444);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses fixed localhost defaults in desktop mode", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli([], {
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
});
|
||||
|
||||
assert.equal(findAvailablePort.mock.calls.length, 0);
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.port, 3773);
|
||||
assert.equal(resolvedConfig?.host, "127.0.0.1");
|
||||
assert.equal(resolvedConfig?.mode, "desktop");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("allows overriding desktop host with --host", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--host", "0.0.0.0"], {
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "desktop");
|
||||
assert.equal(resolvedConfig?.host, "0.0.0.0");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("supports CLI and env for bootstrap/log websocket toggles", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--auto-bootstrap-project-from-cwd"], {
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_LOG_WS_EVENTS: "false",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, true);
|
||||
assert.equal(resolvedConfig?.logWebSocketEvents, false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("hydrates PATH before server startup", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli([]);
|
||||
|
||||
assert.equal(fixPath.mock.calls.length, 1);
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
const fixPathOrder = fixPath.mock.invocationCallOrder[0];
|
||||
const startOrder = start.mock.invocationCallOrder[0];
|
||||
if (typeof fixPathOrder !== "number" || typeof startOrder !== "number") {
|
||||
assert.fail("Expected fixPath and start to be called");
|
||||
}
|
||||
assert.isTrue(fixPathOrder < startOrder);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("records a startup heartbeat with thread/project counts", () =>
|
||||
Effect.gen(function* () {
|
||||
const recordTelemetry = vi.fn(
|
||||
(_event: string, _properties?: Readonly<Record<string, unknown>>) => Effect.void,
|
||||
);
|
||||
const getSnapshot = vi.fn(() =>
|
||||
Effect.succeed({
|
||||
snapshotSequence: 2,
|
||||
projects: [{} as OrchestrationReadModel["projects"][number]],
|
||||
threads: [
|
||||
{} as OrchestrationReadModel["threads"][number],
|
||||
{} as OrchestrationReadModel["threads"][number],
|
||||
],
|
||||
updatedAt: new Date(1).toISOString(),
|
||||
} satisfies OrchestrationReadModel),
|
||||
);
|
||||
|
||||
yield* recordStartupHeartbeat.pipe(
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getSnapshot,
|
||||
}),
|
||||
Effect.provideService(AnalyticsService, {
|
||||
record: recordTelemetry,
|
||||
flush: Effect.void,
|
||||
}),
|
||||
);
|
||||
|
||||
assert.deepEqual(recordTelemetry.mock.calls[0], [
|
||||
"server.boot.heartbeat",
|
||||
{
|
||||
threadCount: 2,
|
||||
projectCount: 1,
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not start server for invalid --mode values", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--mode", "invalid"]).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
assert.equal(start.mock.calls.length, 0);
|
||||
assert.equal(stop.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not start server for invalid --dev-url values", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--dev-url", "not-a-url"]).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
assert.equal(start.mock.calls.length, 0);
|
||||
assert.equal(stop.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not start server for out-of-range --port values", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--port", "70000"]).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
// effect/unstable/cli renders help/errors for parse failures and returns success.
|
||||
assert.equal(start.mock.calls.length, 0);
|
||||
assert.equal(stop.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,456 +0,0 @@
|
||||
/**
|
||||
* CliConfig - CLI/runtime bootstrap service definitions.
|
||||
*
|
||||
* Defines startup-only service contracts used while resolving process config
|
||||
* and constructing server runtime layers.
|
||||
*
|
||||
* @module CliConfig
|
||||
*/
|
||||
import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceMap } from "effect";
|
||||
import { Command, Flag } from "effect/unstable/cli";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import {
|
||||
DEFAULT_PORT,
|
||||
deriveServerPaths,
|
||||
resolveStaticDir,
|
||||
ServerConfig,
|
||||
type RuntimeMode,
|
||||
type ServerConfigShape,
|
||||
} from "./config";
|
||||
import { fixPath, resolveBaseDir } from "./os-jank";
|
||||
import { Open } from "./open";
|
||||
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
|
||||
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry";
|
||||
import { Server } from "./wsServer";
|
||||
import { ServerLoggerLive } from "./serverLogger";
|
||||
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
import { readBootstrapEnvelope } from "./bootstrap";
|
||||
import { ServerSettingsLive } from "./serverSettings";
|
||||
|
||||
export class StartupError extends Data.TaggedError("StartupError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
|
||||
|
||||
const BootstrapEnvelopeSchema = Schema.Struct({
|
||||
mode: Schema.optional(Schema.String),
|
||||
port: Schema.optional(PortSchema),
|
||||
host: Schema.optional(Schema.String),
|
||||
t3Home: Schema.optional(Schema.String),
|
||||
devUrl: Schema.optional(Schema.URLFromString),
|
||||
noBrowser: Schema.optional(Schema.Boolean),
|
||||
authToken: Schema.optional(Schema.String),
|
||||
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
|
||||
logWebSocketEvents: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
|
||||
interface CliInput {
|
||||
readonly mode: Option.Option<RuntimeMode>;
|
||||
readonly port: Option.Option<number>;
|
||||
readonly host: Option.Option<string>;
|
||||
readonly t3Home: Option.Option<string>;
|
||||
readonly devUrl: Option.Option<URL>;
|
||||
readonly noBrowser: Option.Option<boolean>;
|
||||
readonly authToken: Option.Option<string>;
|
||||
readonly bootstrapFd: Option.Option<number>;
|
||||
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
|
||||
readonly logWebSocketEvents: Option.Option<boolean>;
|
||||
}
|
||||
|
||||
/**
|
||||
* CliConfigShape - Startup helpers required while building server layers.
|
||||
*/
|
||||
export interface CliConfigShape {
|
||||
/**
|
||||
* Current process working directory.
|
||||
*/
|
||||
readonly cwd: string;
|
||||
|
||||
/**
|
||||
* Apply OS-specific PATH normalization.
|
||||
*/
|
||||
readonly fixPath: Effect.Effect<void>;
|
||||
|
||||
/**
|
||||
* Resolve static web asset directory for server mode.
|
||||
*/
|
||||
readonly resolveStaticDir: Effect.Effect<string | undefined>;
|
||||
}
|
||||
|
||||
/**
|
||||
* CliConfig - Service tag for startup CLI/runtime helpers.
|
||||
*/
|
||||
export class CliConfig extends ServiceMap.Service<CliConfig, CliConfigShape>()(
|
||||
"t3/main/CliConfig",
|
||||
) {
|
||||
static readonly layer = Layer.effect(
|
||||
CliConfig,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
return {
|
||||
cwd: process.cwd(),
|
||||
fixPath: Effect.sync(fixPath),
|
||||
resolveStaticDir: resolveStaticDir().pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
),
|
||||
} satisfies CliConfigShape;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const CliEnvConfig = Config.all({
|
||||
mode: Config.string("T3CODE_MODE").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.map((value) => (value === "desktop" ? "desktop" : "web"))),
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
authToken: Config.string("T3CODE_AUTH_TOKEN").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
});
|
||||
|
||||
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
|
||||
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
|
||||
|
||||
const resolveOptionPrecedence = <Value>(
|
||||
...values: ReadonlyArray<Option.Option<Value>>
|
||||
): Option.Option<Value> => Option.firstSomeOf(values);
|
||||
|
||||
const isValidPort = (value: number): boolean => value >= 1 && value <= 65_535;
|
||||
const isRuntimeMode = (value: string): value is RuntimeMode =>
|
||||
value === "web" || value === "desktop";
|
||||
|
||||
const ServerConfigLive = (input: CliInput) =>
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const cliConfig = yield* CliConfig;
|
||||
const { findAvailablePort } = yield* NetService;
|
||||
const env = yield* CliEnvConfig.asEffect().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new StartupError({ message: "Failed to read environment configuration", cause }),
|
||||
),
|
||||
);
|
||||
|
||||
const bootstrapFd = Option.getOrUndefined(input.bootstrapFd) ?? env.bootstrapFd;
|
||||
const bootstrapEnvelope =
|
||||
bootstrapFd !== undefined
|
||||
? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
|
||||
: Option.none();
|
||||
|
||||
const mode: RuntimeMode = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
input.mode,
|
||||
Option.fromUndefinedOr(env.mode),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.filter(Option.fromUndefinedOr(bootstrap.mode), isRuntimeMode),
|
||||
),
|
||||
),
|
||||
() => "web",
|
||||
);
|
||||
const port = yield* Option.match(
|
||||
resolveOptionPrecedence(
|
||||
input.port,
|
||||
Option.fromUndefinedOr(env.port),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.filter(Option.fromUndefinedOr(bootstrap.port), isValidPort),
|
||||
),
|
||||
),
|
||||
{
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
onNone: () => {
|
||||
if (mode === "desktop") {
|
||||
return Effect.succeed(DEFAULT_PORT);
|
||||
}
|
||||
return findAvailablePort(DEFAULT_PORT);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const devUrl = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
input.devUrl,
|
||||
Option.fromUndefinedOr(env.devUrl),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.devUrl),
|
||||
),
|
||||
),
|
||||
() => undefined,
|
||||
);
|
||||
const baseDir = yield* resolveBaseDir(
|
||||
Option.getOrUndefined(
|
||||
resolveOptionPrecedence(
|
||||
input.t3Home,
|
||||
Option.fromUndefinedOr(env.t3Home),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.t3Home),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
|
||||
const noBrowser = resolveBooleanFlag(
|
||||
input.noBrowser,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.noBrowser),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.noBrowser),
|
||||
),
|
||||
),
|
||||
() => mode === "desktop",
|
||||
),
|
||||
);
|
||||
const authToken = resolveOptionPrecedence(
|
||||
input.authToken,
|
||||
Option.fromUndefinedOr(env.authToken),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.authToken),
|
||||
),
|
||||
);
|
||||
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
|
||||
input.autoBootstrapProjectFromCwd,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
|
||||
),
|
||||
),
|
||||
() => mode === "web",
|
||||
),
|
||||
);
|
||||
const logWebSocketEvents = resolveBooleanFlag(
|
||||
input.logWebSocketEvents,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.logWebSocketEvents),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.logWebSocketEvents),
|
||||
),
|
||||
),
|
||||
() => Boolean(devUrl),
|
||||
),
|
||||
);
|
||||
const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
|
||||
const host = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
input.host,
|
||||
Option.fromUndefinedOr(env.host),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
|
||||
),
|
||||
() => (mode === "desktop" ? "127.0.0.1" : undefined),
|
||||
);
|
||||
|
||||
const config: ServerConfigShape = {
|
||||
mode,
|
||||
port,
|
||||
cwd: cliConfig.cwd,
|
||||
host,
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
staticDir,
|
||||
devUrl,
|
||||
noBrowser,
|
||||
authToken: Option.getOrUndefined(authToken),
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
} satisfies ServerConfigShape;
|
||||
|
||||
return config;
|
||||
}),
|
||||
);
|
||||
|
||||
const LayerLive = (input: CliInput) =>
|
||||
Layer.empty.pipe(
|
||||
Layer.provideMerge(makeServerRuntimeServicesLayer()),
|
||||
Layer.provideMerge(makeServerProviderLayer()),
|
||||
Layer.provideMerge(ProviderRegistryLive),
|
||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||
Layer.provideMerge(ServerLoggerLive),
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(ServerConfigLive(input)),
|
||||
);
|
||||
|
||||
const isWildcardHost = (host: string | undefined): boolean =>
|
||||
host === "0.0.0.0" || host === "::" || host === "[::]";
|
||||
|
||||
const formatHostForUrl = (host: string): string =>
|
||||
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
||||
|
||||
export const recordStartupHeartbeat = Effect.gen(function* () {
|
||||
const analytics = yield* AnalyticsService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
|
||||
const { threadCount, projectCount } = yield* projectionSnapshotQuery.getSnapshot().pipe(
|
||||
Effect.map((snapshot) => ({
|
||||
threadCount: snapshot.threads.length,
|
||||
projectCount: snapshot.projects.length,
|
||||
})),
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("failed to gather startup snapshot for telemetry", { cause }).pipe(
|
||||
Effect.as({
|
||||
threadCount: 0,
|
||||
projectCount: 0,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* analytics.record("server.boot.heartbeat", {
|
||||
threadCount,
|
||||
projectCount,
|
||||
});
|
||||
});
|
||||
|
||||
const makeServerRuntimeProgram = (input: CliInput) =>
|
||||
Effect.gen(function* () {
|
||||
const { start, stopSignal } = yield* Server;
|
||||
const openDeps = yield* Open;
|
||||
|
||||
const config = yield* ServerConfig;
|
||||
|
||||
if (!config.devUrl && !config.staticDir) {
|
||||
yield* Effect.logWarning(
|
||||
"web bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable",
|
||||
{
|
||||
hint: "Run `bun run --cwd apps/web build` or set VITE_DEV_SERVER_URL for dev mode.",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
yield* start;
|
||||
yield* Effect.forkChild(recordStartupHeartbeat);
|
||||
|
||||
const localUrl = `http://localhost:${config.port}`;
|
||||
const bindUrl =
|
||||
config.host && !isWildcardHost(config.host)
|
||||
? `http://${formatHostForUrl(config.host)}:${config.port}`
|
||||
: localUrl;
|
||||
const { authToken, devUrl, ...safeConfig } = config;
|
||||
yield* Effect.logInfo("T3 Code running", {
|
||||
...safeConfig,
|
||||
devUrl: devUrl?.toString(),
|
||||
authEnabled: Boolean(authToken),
|
||||
});
|
||||
|
||||
if (!config.noBrowser) {
|
||||
const target = config.devUrl?.toString() ?? bindUrl;
|
||||
yield* openDeps.openBrowser(target).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.logInfo("browser auto-open unavailable", {
|
||||
hint: `Open ${target} in your browser.`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return yield* stopSignal;
|
||||
}).pipe(Effect.provide(LayerLive(input)));
|
||||
|
||||
const makeServerProgram = (input: CliInput) =>
|
||||
Effect.gen(function* () {
|
||||
const cliConfig = yield* CliConfig;
|
||||
yield* cliConfig.fixPath;
|
||||
return yield* makeServerRuntimeProgram(input);
|
||||
});
|
||||
|
||||
/**
|
||||
* These flags mirrors the environment variables and the config shape.
|
||||
*/
|
||||
|
||||
const modeFlag = Flag.choice("mode", ["web", "desktop"]).pipe(
|
||||
Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
|
||||
Flag.optional,
|
||||
);
|
||||
const portFlag = Flag.integer("port").pipe(
|
||||
Flag.withSchema(PortSchema),
|
||||
Flag.withDescription("Port for the HTTP/WebSocket server."),
|
||||
Flag.optional,
|
||||
);
|
||||
const hostFlag = Flag.string("host").pipe(
|
||||
Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
|
||||
Flag.optional,
|
||||
);
|
||||
const t3HomeFlag = Flag.string("home-dir").pipe(
|
||||
Flag.withDescription("Base directory for all T3 Code data (equivalent to T3CODE_HOME)."),
|
||||
Flag.optional,
|
||||
);
|
||||
const devUrlFlag = Flag.string("dev-url").pipe(
|
||||
Flag.withSchema(Schema.URLFromString),
|
||||
Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
|
||||
Flag.optional,
|
||||
);
|
||||
const noBrowserFlag = Flag.boolean("no-browser").pipe(
|
||||
Flag.withDescription("Disable automatic browser opening."),
|
||||
Flag.optional,
|
||||
);
|
||||
const authTokenFlag = Flag.string("auth-token").pipe(
|
||||
Flag.withDescription("Auth token required for WebSocket connections."),
|
||||
Flag.withAlias("token"),
|
||||
Flag.optional,
|
||||
);
|
||||
const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
|
||||
Flag.withSchema(Schema.Int),
|
||||
Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
|
||||
Flag.optional,
|
||||
);
|
||||
const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
|
||||
Flag.withDescription(
|
||||
"Create a project for the current working directory on startup when missing.",
|
||||
),
|
||||
Flag.optional,
|
||||
);
|
||||
const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
|
||||
Flag.withDescription(
|
||||
"Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
|
||||
),
|
||||
Flag.withAlias("log-ws-events"),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
export const t3Cli = Command.make("t3", {
|
||||
mode: modeFlag,
|
||||
port: portFlag,
|
||||
host: hostFlag,
|
||||
t3Home: t3HomeFlag,
|
||||
devUrl: devUrlFlag,
|
||||
noBrowser: noBrowserFlag,
|
||||
authToken: authTokenFlag,
|
||||
bootstrapFd: bootstrapFdFlag,
|
||||
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
|
||||
logWebSocketEvents: logWebSocketEventsFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("Run the T3 Code server."),
|
||||
Command.withHandler((input) => Effect.scoped(makeServerProgram(input))),
|
||||
);
|
||||
@@ -10,17 +10,14 @@ import { spawn } from "node:child_process";
|
||||
import { accessSync, constants, statSync } from "node:fs";
|
||||
import { extname, join } from "node:path";
|
||||
|
||||
import { EDITORS, type EditorId } from "@t3tools/contracts";
|
||||
import { ServiceMap, Schema, Effect, Layer } from "effect";
|
||||
import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
|
||||
import { ServiceMap, Effect, Layer } from "effect";
|
||||
|
||||
// ==============================
|
||||
// Definitions
|
||||
// ==============================
|
||||
|
||||
export class OpenError extends Schema.TaggedErrorClass<OpenError>()("OpenError", {
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {}
|
||||
export { OpenError };
|
||||
|
||||
export interface OpenInEditorInput {
|
||||
readonly cwd: string;
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
|
||||
@@ -38,6 +38,8 @@ import {
|
||||
} from "../../provider/Services/ProviderService.ts";
|
||||
import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { WorkspaceEntriesLive } from "../../workspace/Layers/WorkspaceEntries.ts";
|
||||
import { WorkspacePathsLive } from "../../workspace/Layers/WorkspacePaths.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
@@ -68,7 +70,7 @@ function createProviderServiceHarness(
|
||||
);
|
||||
|
||||
const unsupported = <A>() =>
|
||||
Effect.die(new Error("Unsupported provider call in test")) as Effect.Effect<A, never>;
|
||||
Effect.die(new Error("Unsupported provider call in test")) as Effect.Effect<A>;
|
||||
const listSessions = () =>
|
||||
hasSession
|
||||
? Effect.succeed([
|
||||
@@ -114,7 +116,7 @@ async function waitForThread(
|
||||
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
||||
activities: ReadonlyArray<{ kind: string }>;
|
||||
}) => boolean,
|
||||
timeoutMs = 5000,
|
||||
timeoutMs = 15_000,
|
||||
) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const poll = async (): Promise<{
|
||||
@@ -139,7 +141,7 @@ async function waitForThread(
|
||||
async function waitForEvent(
|
||||
engine: OrchestrationEngineShape,
|
||||
predicate: (event: { type: string }) => boolean,
|
||||
timeoutMs = 5000,
|
||||
timeoutMs = 15_000,
|
||||
) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const poll = async () => {
|
||||
@@ -190,7 +192,7 @@ function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string {
|
||||
return runGit(cwd, ["show", `${ref}:${filePath}`]);
|
||||
}
|
||||
|
||||
async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 5000) {
|
||||
async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 15_000) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const poll = async (): Promise<void> => {
|
||||
if (gitRefExists(cwd, ref)) {
|
||||
@@ -261,7 +263,10 @@ describe("CheckpointReactor", () => {
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(RuntimeReceiptBusLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(GitCoreLive))),
|
||||
Layer.provideMerge(CheckpointStoreLive),
|
||||
Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
|
||||
Layer.provideMerge(WorkspacePathsLive),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provideMerge(ServerConfigLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
@@ -1004,18 +1009,7 @@ describe("CheckpointReactor", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const deadline = Date.now() + 2000;
|
||||
const waitForRollbackCalls = async (): Promise<void> => {
|
||||
if (harness.provider.rollbackConversation.mock.calls.length >= 2) {
|
||||
return;
|
||||
}
|
||||
if (Date.now() >= deadline) {
|
||||
throw new Error("Timed out waiting for rollbackConversation calls.");
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
return waitForRollbackCalls();
|
||||
};
|
||||
await waitForRollbackCalls();
|
||||
await harness.drain();
|
||||
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(2);
|
||||
expect(harness.provider.rollbackConversation.mock.calls[0]?.[0]).toEqual({
|
||||
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
checkpointRefForThreadTurn,
|
||||
resolveThreadWorkspaceCwd,
|
||||
} from "../../checkpointing/Utils.ts";
|
||||
import { clearWorkspaceIndexCache } from "../../workspaceEntries.ts";
|
||||
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
|
||||
@@ -25,6 +24,7 @@ import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
|
||||
import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
|
||||
import { OrchestrationDispatchError } from "../Errors.ts";
|
||||
import { isGitRepository } from "../../git/Utils.ts";
|
||||
import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts";
|
||||
|
||||
type ReactorInput =
|
||||
| {
|
||||
@@ -68,6 +68,7 @@ const make = Effect.gen(function* () {
|
||||
const providerService = yield* ProviderService;
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
const receiptBus = yield* RuntimeReceiptBus;
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
|
||||
const appendRevertFailureActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
@@ -226,7 +227,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
// Invalidate the workspace entry cache so the @-mention file picker
|
||||
// reflects files created or deleted during this turn.
|
||||
clearWorkspaceIndexCache(input.cwd);
|
||||
yield* workspaceEntries.invalidate(input.cwd);
|
||||
|
||||
const files = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
@@ -642,7 +643,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
// Invalidate the workspace entry cache so the @-mention file picker
|
||||
// reflects the reverted filesystem state.
|
||||
clearWorkspaceIndexCache(sessionRuntime.value.cwd);
|
||||
yield* workspaceEntries.invalidate(sessionRuntime.value.cwd);
|
||||
|
||||
const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount);
|
||||
if (rolledBackTurns > 0) {
|
||||
@@ -747,7 +748,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const processInput = (
|
||||
input: ReactorInput,
|
||||
): Effect.Effect<void, CheckpointStoreError | OrchestrationDispatchError, never> =>
|
||||
): Effect.Effect<void, CheckpointStoreError | OrchestrationDispatchError> =>
|
||||
input.source === "domain" ? processDomainEvent(input.event) : processRuntimeEvent(input.event);
|
||||
|
||||
const processInputSafely = (input: ReactorInput) =>
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
type OrchestrationEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, ManagedRuntime, Queue, Stream } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { PersistenceSqlError } from "../../persistence/Errors.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
|
||||
@@ -205,7 +205,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
|
||||
const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
|
||||
yield* Effect.forkScoped(worker);
|
||||
yield* Effect.log("orchestration engine started").pipe(
|
||||
yield* Effect.logDebug("orchestration engine started").pipe(
|
||||
Effect.annotateLogs({ sequence: readModel.snapshotSequence }),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Effect, Exit, Layer, ManagedRuntime, Scope } from "effect";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { afterEach, describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
|
||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
type ChatAttachment,
|
||||
type OrchestrationEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
@@ -1271,7 +1270,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
Effect.provideService(ServerConfig, serverConfig),
|
||||
Effect.asVoid,
|
||||
Effect.tap(() =>
|
||||
Effect.log("orchestration projection pipeline bootstrapped").pipe(
|
||||
Effect.logDebug("orchestration projection pipeline bootstrapped").pipe(
|
||||
Effect.annotateLogs({ projectors: projectors.length }),
|
||||
),
|
||||
),
|
||||
@@ -1291,7 +1290,6 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
|
||||
OrchestrationProjectionPipeline,
|
||||
makeOrchestrationProjectionPipeline(),
|
||||
).pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(ProjectionProjectRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
|
||||
|
||||
@@ -14,10 +14,10 @@ import {
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { deriveServerPaths, ServerConfig } from "../../config.ts";
|
||||
import { TextGenerationError } from "../../git/Errors.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
|
||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { afterEach, describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
@@ -1626,8 +1626,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
event.payload.messageId === "assistant:item-complete-dedup" &&
|
||||
event.payload.streaming === false
|
||||
event.payload.messageId === "assistant:item-complete-dedup" && !event.payload.streaming
|
||||
);
|
||||
});
|
||||
expect(completionEvents).toHaveLength(1);
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { Effect, FileSystem, Path } from "effect";
|
||||
import {
|
||||
type ClientOrchestrationCommand,
|
||||
type OrchestrationCommand,
|
||||
OrchestrationDispatchCommandError,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { createAttachmentId, resolveAttachmentPath } from "../attachmentStore";
|
||||
import { ServerConfig } from "../config";
|
||||
import { parseBase64DataUrl } from "../imageMime";
|
||||
import { WorkspacePaths } from "../workspace/Services/WorkspacePaths";
|
||||
|
||||
export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
|
||||
const normalizeProjectWorkspaceRoot = (workspaceRoot: string) =>
|
||||
workspacePaths.normalizeWorkspaceRoot(workspaceRoot).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationDispatchCommandError({
|
||||
message: cause.message,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (command.type === "project.create") {
|
||||
return {
|
||||
...command,
|
||||
workspaceRoot: yield* normalizeProjectWorkspaceRoot(command.workspaceRoot),
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
if (command.type === "project.meta.update" && command.workspaceRoot !== undefined) {
|
||||
return {
|
||||
...command,
|
||||
workspaceRoot: yield* normalizeProjectWorkspaceRoot(command.workspaceRoot),
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
if (command.type !== "thread.turn.start") {
|
||||
return command as OrchestrationCommand;
|
||||
}
|
||||
|
||||
const normalizedAttachments = yield* Effect.forEach(
|
||||
command.message.attachments,
|
||||
(attachment) =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = parseBase64DataUrl(attachment.dataUrl);
|
||||
if (!parsed || !parsed.mimeType.startsWith("image/")) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: `Invalid image attachment payload for '${attachment.name}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
const bytes = Buffer.from(parsed.base64, "base64");
|
||||
if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: `Image attachment '${attachment.name}' is empty or too large.`,
|
||||
});
|
||||
}
|
||||
|
||||
const attachmentId = createAttachmentId(command.threadId);
|
||||
if (!attachmentId) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: "Failed to create a safe attachment id.",
|
||||
});
|
||||
}
|
||||
|
||||
const persistedAttachment = {
|
||||
type: "image" as const,
|
||||
id: attachmentId,
|
||||
name: attachment.name,
|
||||
mimeType: parsed.mimeType.toLowerCase(),
|
||||
sizeBytes: bytes.byteLength,
|
||||
};
|
||||
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment: persistedAttachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: `Failed to resolve persisted path for '${attachment.name}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
() =>
|
||||
new OrchestrationDispatchCommandError({
|
||||
message: `Failed to create attachment directory for '${attachment.name}'.`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* fileSystem.writeFile(attachmentPath, bytes).pipe(
|
||||
Effect.mapError(
|
||||
() =>
|
||||
new OrchestrationDispatchCommandError({
|
||||
message: `Failed to persist attachment '${attachment.name}'.`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return persistedAttachment;
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
return {
|
||||
...command,
|
||||
message: {
|
||||
...command.message,
|
||||
attachments: normalizedAttachments,
|
||||
},
|
||||
} satisfies OrchestrationCommand;
|
||||
});
|
||||
@@ -30,7 +30,7 @@ export interface OrchestrationEngineShape {
|
||||
*
|
||||
* @returns Effect containing the latest read model.
|
||||
*/
|
||||
readonly getReadModel: () => Effect.Effect<OrchestrationReadModel, never, never>;
|
||||
readonly getReadModel: () => Effect.Effect<OrchestrationReadModel, never>;
|
||||
|
||||
/**
|
||||
* Replay persisted orchestration events from an exclusive sequence cursor.
|
||||
@@ -40,7 +40,7 @@ export interface OrchestrationEngineShape {
|
||||
*/
|
||||
readonly readEvents: (
|
||||
fromSequenceExclusive: number,
|
||||
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError, never>;
|
||||
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError>;
|
||||
|
||||
/**
|
||||
* Dispatch a validated orchestration command.
|
||||
@@ -53,7 +53,7 @@ export interface OrchestrationEngineShape {
|
||||
*/
|
||||
readonly dispatch: (
|
||||
command: OrchestrationCommand,
|
||||
) => Effect.Effect<{ sequence: number }, OrchestrationDispatchError, never>;
|
||||
) => Effect.Effect<{ sequence: number }, OrchestrationDispatchError>;
|
||||
|
||||
/**
|
||||
* Stream persisted domain events in dispatch order.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import {
|
||||
MessageId,
|
||||
CommandId,
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { Effect } from "effect";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
|
||||
@@ -679,7 +679,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
|
||||
default: {
|
||||
command satisfies never;
|
||||
const fallback = command as never as { type: string };
|
||||
const fallback = command as { type: string };
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: fallback.type,
|
||||
detail: `Unknown command type: ${fallback.type}`,
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
type OrchestrationEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { createEmptyReadModel, projectEvent } from "./projector.ts";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { fixPath } from "./os-jank";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { runProcess } from "./processRunner";
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it, describe, expect } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
|
||||
import { ProjectFaviconResolver } from "../Services/ProjectFaviconResolver.ts";
|
||||
import { ProjectFaviconResolverLive } from "./ProjectFaviconResolver.ts";
|
||||
|
||||
const TestLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(ProjectFaviconResolverLive),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const makeTempDir = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3code-project-favicon-",
|
||||
});
|
||||
});
|
||||
|
||||
const writeTextFile = Effect.fn("writeTextFile")(function* (
|
||||
cwd: string,
|
||||
relativePath: string,
|
||||
contents: string,
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const absolutePath = path.join(cwd, relativePath);
|
||||
yield* fileSystem
|
||||
.makeDirectory(path.dirname(absolutePath), { recursive: true })
|
||||
.pipe(Effect.orDie);
|
||||
yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie);
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("ProjectFaviconResolverLive", (it) => {
|
||||
describe("resolvePath", () => {
|
||||
it.effect("prefers well-known favicon files", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(cwd, "favicon.svg", "<svg>favicon</svg>");
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
|
||||
expect(resolved).not.toBeNull();
|
||||
expect(resolved).toContain("favicon.svg");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolves icon hrefs from project source files", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(cwd, "index.html", '<link rel="icon" href="/brand/logo.svg">');
|
||||
yield* writeTextFile(cwd, "public/brand/logo.svg", "<svg>brand</svg>");
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
|
||||
expect(resolved).not.toBeNull();
|
||||
expect(resolved).toContain("public/brand/logo.svg");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns null when no icon is present", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
|
||||
expect(resolved).toBeNull();
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
|
||||
import {
|
||||
ProjectFaviconResolver,
|
||||
type ProjectFaviconResolverShape,
|
||||
} from "../Services/ProjectFaviconResolver.ts";
|
||||
|
||||
// Well-known favicon paths checked in order.
|
||||
const FAVICON_CANDIDATES = [
|
||||
"favicon.svg",
|
||||
"favicon.ico",
|
||||
"favicon.png",
|
||||
"public/favicon.svg",
|
||||
"public/favicon.ico",
|
||||
"public/favicon.png",
|
||||
"app/favicon.ico",
|
||||
"app/favicon.png",
|
||||
"app/icon.svg",
|
||||
"app/icon.png",
|
||||
"app/icon.ico",
|
||||
"src/favicon.ico",
|
||||
"src/favicon.svg",
|
||||
"src/app/favicon.ico",
|
||||
"src/app/icon.svg",
|
||||
"src/app/icon.png",
|
||||
"assets/icon.svg",
|
||||
"assets/icon.png",
|
||||
"assets/logo.svg",
|
||||
"assets/logo.png",
|
||||
] as const;
|
||||
|
||||
// Files that may contain a <link rel="icon"> or icon metadata declaration.
|
||||
const ICON_SOURCE_FILES = [
|
||||
"index.html",
|
||||
"public/index.html",
|
||||
"app/routes/__root.tsx",
|
||||
"src/routes/__root.tsx",
|
||||
"app/root.tsx",
|
||||
"src/root.tsx",
|
||||
"src/index.html",
|
||||
] as const;
|
||||
|
||||
// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
|
||||
const LINK_ICON_HTML_RE =
|
||||
/<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
|
||||
const LINK_ICON_OBJ_RE =
|
||||
/(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i;
|
||||
|
||||
function extractIconHref(source: string): string | null {
|
||||
const htmlMatch = source.match(LINK_ICON_HTML_RE);
|
||||
if (htmlMatch?.[1]) return htmlMatch[1];
|
||||
const objMatch = source.match(LINK_ICON_OBJ_RE);
|
||||
if (objMatch?.[1]) return objMatch[1];
|
||||
return null;
|
||||
}
|
||||
|
||||
export const makeProjectFaviconResolver = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const resolveIconHref = (projectCwd: string, href: string): string[] => {
|
||||
const clean = href.replace(/^\//, "");
|
||||
return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
|
||||
};
|
||||
|
||||
const isPathWithinProject = (projectCwd: string, candidatePath: string): boolean => {
|
||||
const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath));
|
||||
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
||||
};
|
||||
|
||||
const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* (
|
||||
projectCwd: string,
|
||||
candidates: ReadonlyArray<string>,
|
||||
): Effect.fn.Return<string | null> {
|
||||
for (const candidate of candidates) {
|
||||
if (!isPathWithinProject(projectCwd, candidate)) {
|
||||
continue;
|
||||
}
|
||||
const stats = yield* fileSystem
|
||||
.stat(candidate)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (stats?.type === "File") {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const resolvePath: ProjectFaviconResolverShape["resolvePath"] = Effect.fn(
|
||||
"ProjectFaviconResolver.resolvePath",
|
||||
)(function* (cwd: string): Effect.fn.Return<string | null> {
|
||||
for (const candidate of FAVICON_CANDIDATES) {
|
||||
const resolved = path.join(cwd, candidate);
|
||||
const existing = yield* findExistingFile(cwd, [resolved]);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
|
||||
for (const sourceFile of ICON_SOURCE_FILES) {
|
||||
const sourcePath = path.join(cwd, sourceFile);
|
||||
const source = yield* fileSystem
|
||||
.readFileString(sourcePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!source) {
|
||||
continue;
|
||||
}
|
||||
const href = extractIconHref(source);
|
||||
if (!href) {
|
||||
continue;
|
||||
}
|
||||
const existing = yield* findExistingFile(cwd, resolveIconHref(cwd, href));
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
return {
|
||||
resolvePath,
|
||||
} satisfies ProjectFaviconResolverShape;
|
||||
});
|
||||
|
||||
export const ProjectFaviconResolverLive = Layer.effect(
|
||||
ProjectFaviconResolver,
|
||||
makeProjectFaviconResolver,
|
||||
);
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* ProjectFaviconResolver - Effect service contract for project icon discovery.
|
||||
*
|
||||
* Resolves a representative favicon or app icon file for a workspace by
|
||||
* checking common file locations and project source metadata.
|
||||
*
|
||||
* @module ProjectFaviconResolver
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
/**
|
||||
* ProjectFaviconResolverShape - Service API for project favicon lookup.
|
||||
*/
|
||||
export interface ProjectFaviconResolverShape {
|
||||
/**
|
||||
* Resolve a favicon or icon file path for the provided workspace root.
|
||||
*
|
||||
* Returns `null` when no candidate icon file can be found.
|
||||
*/
|
||||
readonly resolvePath: (cwd: string) => Effect.Effect<string | null>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProjectFaviconResolver - Service tag for project favicon resolution.
|
||||
*/
|
||||
export class ProjectFaviconResolver extends ServiceMap.Service<
|
||||
ProjectFaviconResolver,
|
||||
ProjectFaviconResolverShape
|
||||
>()("t3/project/Services/ProjectFaviconResolver") {}
|
||||
@@ -1,171 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||
|
||||
interface HttpResponse {
|
||||
statusCode: number;
|
||||
contentType: string | null;
|
||||
body: string;
|
||||
}
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
async function withRouteServer(run: (baseUrl: string) => Promise<void>): Promise<void> {
|
||||
const server = http.createServer((req, res) => {
|
||||
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
||||
if (tryHandleProjectFaviconRequest(url, res)) {
|
||||
return;
|
||||
}
|
||||
res.writeHead(404, { "Content-Type": "text/plain" });
|
||||
res.end("Not Found");
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.listen(0, "127.0.0.1", (error?: Error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
const address = server.address();
|
||||
if (typeof address !== "object" || address === null) {
|
||||
throw new Error("Expected server address to be an object");
|
||||
}
|
||||
const baseUrl = `http://127.0.0.1:${address.port}`;
|
||||
|
||||
try {
|
||||
await run(baseUrl);
|
||||
} finally {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.close((error?: Error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function request(baseUrl: string, pathname: string): Promise<HttpResponse> {
|
||||
const response = await fetch(`${baseUrl}${pathname}`);
|
||||
return {
|
||||
statusCode: response.status,
|
||||
contentType: response.headers.get("content-type"),
|
||||
body: await response.text(),
|
||||
};
|
||||
}
|
||||
|
||||
describe("tryHandleProjectFaviconRequest", () => {
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns 400 when cwd is missing", async () => {
|
||||
await withRouteServer(async (baseUrl) => {
|
||||
const response = await request(baseUrl, "/api/project-favicon");
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.body).toBe("Missing cwd parameter");
|
||||
});
|
||||
});
|
||||
|
||||
it("serves a well-known favicon file from the project root", async () => {
|
||||
const projectDir = makeTempDir("t3code-favicon-route-root-");
|
||||
fs.writeFileSync(path.join(projectDir, "favicon.svg"), "<svg>favicon</svg>", "utf8");
|
||||
|
||||
await withRouteServer(async (baseUrl) => {
|
||||
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
|
||||
const response = await request(baseUrl, pathname);
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.contentType).toContain("image/svg+xml");
|
||||
expect(response.body).toBe("<svg>favicon</svg>");
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves icon href from source files when no well-known favicon exists", async () => {
|
||||
const projectDir = makeTempDir("t3code-favicon-route-source-");
|
||||
const iconPath = path.join(projectDir, "public", "brand", "logo.svg");
|
||||
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(projectDir, "index.html"),
|
||||
'<link rel="icon" href="/brand/logo.svg">',
|
||||
);
|
||||
fs.writeFileSync(iconPath, "<svg>brand</svg>", "utf8");
|
||||
|
||||
await withRouteServer(async (baseUrl) => {
|
||||
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
|
||||
const response = await request(baseUrl, pathname);
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.contentType).toContain("image/svg+xml");
|
||||
expect(response.body).toBe("<svg>brand</svg>");
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves icon link when href appears before rel in HTML", async () => {
|
||||
const projectDir = makeTempDir("t3code-favicon-route-html-order-");
|
||||
const iconPath = path.join(projectDir, "public", "brand", "logo.svg");
|
||||
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(projectDir, "index.html"),
|
||||
'<link href="/brand/logo.svg" rel="icon">',
|
||||
);
|
||||
fs.writeFileSync(iconPath, "<svg>brand-html-order</svg>", "utf8");
|
||||
|
||||
await withRouteServer(async (baseUrl) => {
|
||||
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
|
||||
const response = await request(baseUrl, pathname);
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.contentType).toContain("image/svg+xml");
|
||||
expect(response.body).toBe("<svg>brand-html-order</svg>");
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves object-style icon metadata when href appears before rel", async () => {
|
||||
const projectDir = makeTempDir("t3code-favicon-route-obj-order-");
|
||||
const iconPath = path.join(projectDir, "public", "brand", "obj.svg");
|
||||
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
|
||||
fs.mkdirSync(path.join(projectDir, "src"), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(projectDir, "src", "root.tsx"),
|
||||
'const links = [{ href: "/brand/obj.svg", rel: "icon" }];',
|
||||
"utf8",
|
||||
);
|
||||
fs.writeFileSync(iconPath, "<svg>brand-obj-order</svg>", "utf8");
|
||||
|
||||
await withRouteServer(async (baseUrl) => {
|
||||
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
|
||||
const response = await request(baseUrl, pathname);
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.contentType).toContain("image/svg+xml");
|
||||
expect(response.body).toBe("<svg>brand-obj-order</svg>");
|
||||
});
|
||||
});
|
||||
|
||||
it("serves a fallback favicon when no icon exists", async () => {
|
||||
const projectDir = makeTempDir("t3code-favicon-route-fallback-");
|
||||
|
||||
await withRouteServer(async (baseUrl) => {
|
||||
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
|
||||
const response = await request(baseUrl, pathname);
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.contentType).toContain("image/svg+xml");
|
||||
expect(response.body).toContain('data-fallback="project-favicon"');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,171 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import path from "node:path";
|
||||
|
||||
const FAVICON_MIME_TYPES: Record<string, string> = {
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".svg": "image/svg+xml",
|
||||
".ico": "image/x-icon",
|
||||
};
|
||||
|
||||
const FALLBACK_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
|
||||
|
||||
// Well-known favicon paths checked in order.
|
||||
const FAVICON_CANDIDATES = [
|
||||
"favicon.svg",
|
||||
"favicon.ico",
|
||||
"favicon.png",
|
||||
"public/favicon.svg",
|
||||
"public/favicon.ico",
|
||||
"public/favicon.png",
|
||||
"app/favicon.ico",
|
||||
"app/favicon.png",
|
||||
"app/icon.svg",
|
||||
"app/icon.png",
|
||||
"app/icon.ico",
|
||||
"src/favicon.ico",
|
||||
"src/favicon.svg",
|
||||
"src/app/favicon.ico",
|
||||
"src/app/icon.svg",
|
||||
"src/app/icon.png",
|
||||
"assets/icon.svg",
|
||||
"assets/icon.png",
|
||||
"assets/logo.svg",
|
||||
"assets/logo.png",
|
||||
];
|
||||
|
||||
// Files that may contain a <link rel="icon"> or icon metadata declaration.
|
||||
const ICON_SOURCE_FILES = [
|
||||
"index.html",
|
||||
"public/index.html",
|
||||
"app/routes/__root.tsx",
|
||||
"src/routes/__root.tsx",
|
||||
"app/root.tsx",
|
||||
"src/root.tsx",
|
||||
"src/index.html",
|
||||
];
|
||||
|
||||
// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
|
||||
const LINK_ICON_HTML_RE =
|
||||
/<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
|
||||
const LINK_ICON_OBJ_RE =
|
||||
/(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i;
|
||||
|
||||
function extractIconHref(source: string): string | null {
|
||||
const htmlMatch = source.match(LINK_ICON_HTML_RE);
|
||||
if (htmlMatch?.[1]) return htmlMatch[1];
|
||||
const objMatch = source.match(LINK_ICON_OBJ_RE);
|
||||
if (objMatch?.[1]) return objMatch[1];
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveIconHref(projectCwd: string, href: string): string[] {
|
||||
const clean = href.replace(/^\//, "");
|
||||
return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
|
||||
}
|
||||
|
||||
function isPathWithinProject(projectCwd: string, candidatePath: string): boolean {
|
||||
const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath));
|
||||
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
||||
}
|
||||
|
||||
function serveFaviconFile(filePath: string, res: http.ServerResponse): void {
|
||||
const ext = path.extname(filePath).toLowerCase();
|
||||
const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream";
|
||||
fs.readFile(filePath, (readErr, data) => {
|
||||
if (readErr) {
|
||||
res.writeHead(500, { "Content-Type": "text/plain" });
|
||||
res.end("Read error");
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, {
|
||||
"Content-Type": contentType,
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
});
|
||||
res.end(data);
|
||||
});
|
||||
}
|
||||
|
||||
function serveFallbackFavicon(res: http.ServerResponse): void {
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "image/svg+xml",
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
});
|
||||
res.end(FALLBACK_FAVICON_SVG);
|
||||
}
|
||||
|
||||
export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean {
|
||||
if (url.pathname !== "/api/project-favicon") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const projectCwd = url.searchParams.get("cwd");
|
||||
if (!projectCwd) {
|
||||
res.writeHead(400, { "Content-Type": "text/plain" });
|
||||
res.end("Missing cwd parameter");
|
||||
return true;
|
||||
}
|
||||
|
||||
const tryResolvedPaths = (paths: string[], index: number, onExhausted: () => void): void => {
|
||||
if (index >= paths.length) {
|
||||
onExhausted();
|
||||
return;
|
||||
}
|
||||
const candidate = paths[index]!;
|
||||
if (!isPathWithinProject(projectCwd, candidate)) {
|
||||
tryResolvedPaths(paths, index + 1, onExhausted);
|
||||
return;
|
||||
}
|
||||
fs.stat(candidate, (err, stats) => {
|
||||
if (err || !stats?.isFile()) {
|
||||
tryResolvedPaths(paths, index + 1, onExhausted);
|
||||
return;
|
||||
}
|
||||
serveFaviconFile(candidate, res);
|
||||
});
|
||||
};
|
||||
|
||||
const trySourceFiles = (index: number): void => {
|
||||
if (index >= ICON_SOURCE_FILES.length) {
|
||||
serveFallbackFavicon(res);
|
||||
return;
|
||||
}
|
||||
const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
|
||||
fs.readFile(sourceFile, "utf8", (err, content) => {
|
||||
if (err) {
|
||||
trySourceFiles(index + 1);
|
||||
return;
|
||||
}
|
||||
const href = extractIconHref(content);
|
||||
if (!href) {
|
||||
trySourceFiles(index + 1);
|
||||
return;
|
||||
}
|
||||
const candidates = resolveIconHref(projectCwd, href);
|
||||
tryResolvedPaths(candidates, 0, () => trySourceFiles(index + 1));
|
||||
});
|
||||
};
|
||||
|
||||
const tryCandidates = (index: number): void => {
|
||||
if (index >= FAVICON_CANDIDATES.length) {
|
||||
trySourceFiles(0);
|
||||
return;
|
||||
}
|
||||
const candidate = path.join(projectCwd, FAVICON_CANDIDATES[index]!);
|
||||
if (!isPathWithinProject(projectCwd, candidate)) {
|
||||
tryCandidates(index + 1);
|
||||
return;
|
||||
}
|
||||
fs.stat(candidate, (err, stats) => {
|
||||
if (err || !stats?.isFile()) {
|
||||
tryCandidates(index + 1);
|
||||
return;
|
||||
}
|
||||
serveFaviconFile(candidate, res);
|
||||
});
|
||||
};
|
||||
|
||||
tryCandidates(0);
|
||||
return true;
|
||||
}
|
||||
@@ -208,6 +208,9 @@ async function readFirstPromptText(
|
||||
if (next.done) {
|
||||
return undefined;
|
||||
}
|
||||
if (typeof next.value.message.content === "string") {
|
||||
return next.value.message.content;
|
||||
}
|
||||
const content = next.value.message.content[0];
|
||||
if (!content || content.type !== "text") {
|
||||
return undefined;
|
||||
@@ -2134,7 +2137,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
});
|
||||
|
||||
const permissionResult = yield* Effect.promise(() => permissionPromise);
|
||||
assert.equal((permissionResult as PermissionResult).behavior, "allow");
|
||||
assert.equal(permissionResult.behavior, "allow");
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
@@ -2623,7 +2626,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
});
|
||||
|
||||
const permissionResult = yield* Effect.promise(() => permissionPromise);
|
||||
assert.equal((permissionResult as PermissionResult).behavior, "deny");
|
||||
assert.equal(permissionResult.behavior, "deny");
|
||||
const deniedResult = permissionResult as PermissionResult & {
|
||||
message?: string;
|
||||
};
|
||||
@@ -2817,7 +2820,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
|
||||
// The canUseTool promise should resolve with the answers in SDK format.
|
||||
const permissionResult = yield* Effect.promise(() => permissionPromise);
|
||||
assert.equal((permissionResult as PermissionResult).behavior, "allow");
|
||||
assert.equal(permissionResult.behavior, "allow");
|
||||
const updatedInput = (permissionResult as { updatedInput: Record<string, unknown> })
|
||||
.updatedInput;
|
||||
assert.deepEqual(updatedInput.answers, { "Which framework?": "React" });
|
||||
@@ -2889,7 +2892,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* Stream.runHead(adapter.streamEvents);
|
||||
|
||||
const permissionResult = yield* Effect.promise(() => permissionPromise);
|
||||
assert.equal((permissionResult as PermissionResult).behavior, "allow");
|
||||
assert.equal(permissionResult.behavior, "allow");
|
||||
const updatedInput = (permissionResult as { updatedInput: Record<string, unknown> })
|
||||
.updatedInput;
|
||||
assert.deepEqual(updatedInput.answers, { "Deploy to which env?": "Staging" });
|
||||
|
||||
@@ -261,7 +261,7 @@ function isInterruptedResult(result: SDKResultMessage): boolean {
|
||||
|
||||
return (
|
||||
result.subtype === "error_during_execution" &&
|
||||
result.is_error === false &&
|
||||
!result.is_error &&
|
||||
(errors.includes("request was aborted") ||
|
||||
errors.includes("interrupted by user") ||
|
||||
errors.includes("aborted"))
|
||||
@@ -533,7 +533,7 @@ function buildUserMessage(input: {
|
||||
parent_tool_use_id: null,
|
||||
message: {
|
||||
role: "user",
|
||||
content: input.sdkContent,
|
||||
content: input.sdkContent as unknown as SDKUserMessage["message"]["content"],
|
||||
},
|
||||
} as SDKUserMessage;
|
||||
}
|
||||
@@ -2817,7 +2817,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
providerRefs: {},
|
||||
});
|
||||
|
||||
let streamFiber: Fiber.Fiber<void, never>;
|
||||
let streamFiber: Fiber.Fiber<void>;
|
||||
streamFiber = runFork(
|
||||
Effect.exit(runSdkStream(context)).pipe(
|
||||
Effect.flatMap((exit) => {
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import type {
|
||||
ClaudeSettings,
|
||||
ClaudeModelOptions,
|
||||
ModelCapabilities,
|
||||
ServerProvider,
|
||||
ServerProviderModel,
|
||||
ServerProviderAuthStatus,
|
||||
ServerProviderAuth,
|
||||
ServerProviderState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Equal, Layer, Option, Result, Stream } from "effect";
|
||||
import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { resolveContextWindow, resolveEffort } from "@t3tools/shared/model";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
import { query as claudeQuery } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
import {
|
||||
buildServerProvider,
|
||||
@@ -24,7 +24,8 @@ import {
|
||||
} from "../providerSnapshot";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider";
|
||||
import { ClaudeProvider } from "../Services/ClaudeProvider";
|
||||
import { ServerSettingsError, ServerSettingsService } from "../../serverSettings";
|
||||
import { ServerSettingsService } from "../../serverSettings";
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
const PROVIDER = "claudeAgent" as const;
|
||||
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
@@ -43,8 +44,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
} satisfies ModelCapabilities,
|
||||
@@ -63,8 +64,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
} satisfies ModelCapabilities,
|
||||
@@ -96,28 +97,9 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo
|
||||
);
|
||||
}
|
||||
|
||||
export function normalizeClaudeModelOptions(
|
||||
model: string | null | undefined,
|
||||
modelOptions: ClaudeModelOptions | null | undefined,
|
||||
): ClaudeModelOptions | undefined {
|
||||
const caps = getClaudeModelCapabilities(model);
|
||||
const effort = resolveEffort(caps, modelOptions?.effort);
|
||||
const thinking =
|
||||
caps.supportsThinkingToggle && modelOptions?.thinking === false ? false : undefined;
|
||||
const fastMode = caps.supportsFastMode && modelOptions?.fastMode === true ? true : undefined;
|
||||
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
|
||||
const nextOptions: ClaudeModelOptions = {
|
||||
...(thinking === false ? { thinking: false } : {}),
|
||||
...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
...(contextWindow ? { contextWindow } : {}),
|
||||
};
|
||||
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
|
||||
}
|
||||
|
||||
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
|
||||
readonly status: Exclude<ServerProviderState, "disabled">;
|
||||
readonly authStatus: ServerProviderAuthStatus;
|
||||
readonly auth: Pick<ServerProviderAuth, "status">;
|
||||
readonly message?: string;
|
||||
} {
|
||||
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
|
||||
@@ -129,7 +111,7 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
|
||||
) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
auth: { status: "unknown" },
|
||||
message:
|
||||
"Claude Agent authentication status command is unavailable in this version of Claude.",
|
||||
};
|
||||
@@ -144,7 +126,7 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
|
||||
) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
auth: { status: "unauthenticated" },
|
||||
message: "Claude is not authenticated. Run `claude auth login` and try again.",
|
||||
};
|
||||
}
|
||||
@@ -165,37 +147,286 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
|
||||
})();
|
||||
|
||||
if (parsedAuth.auth === true) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
return { status: "ready", auth: { status: "authenticated" } };
|
||||
}
|
||||
if (parsedAuth.auth === false) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
auth: { status: "unauthenticated" },
|
||||
message: "Claude is not authenticated. Run `claude auth login` and try again.",
|
||||
};
|
||||
}
|
||||
if (parsedAuth.attemptedJsonParse) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
auth: { status: "unknown" },
|
||||
message:
|
||||
"Could not verify Claude authentication status from JSON output (missing auth marker).",
|
||||
};
|
||||
}
|
||||
if (result.code === 0) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
return { status: "ready", auth: { status: "authenticated" } };
|
||||
}
|
||||
|
||||
const detail = detailFromResult(result);
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
auth: { status: "unknown" },
|
||||
message: detail
|
||||
? `Could not verify Claude authentication status. ${detail}`
|
||||
: "Could not verify Claude authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
// ── Subscription type detection ─────────────────────────────────────
|
||||
//
|
||||
// The SDK probe returns typed `AccountInfo.subscriptionType` directly.
|
||||
// This walker is a best-effort fallback for the `claude auth status`
|
||||
// JSON output whose shape is not guaranteed.
|
||||
|
||||
/** Keys that directly hold a subscription/plan identifier. */
|
||||
const SUBSCRIPTION_TYPE_KEYS = [
|
||||
"subscriptionType",
|
||||
"subscription_type",
|
||||
"plan",
|
||||
"tier",
|
||||
"planType",
|
||||
"plan_type",
|
||||
] as const;
|
||||
|
||||
/** Keys whose value may be a nested object containing subscription info. */
|
||||
const SUBSCRIPTION_CONTAINER_KEYS = ["account", "subscription", "user", "billing"] as const;
|
||||
const AUTH_METHOD_KEYS = ["authMethod", "auth_method"] as const;
|
||||
const AUTH_METHOD_CONTAINER_KEYS = ["auth", "account", "session"] as const;
|
||||
|
||||
/** Lift an unknown value into `Option<string>` if it is a non-empty string. */
|
||||
const asNonEmptyString = (v: unknown): Option.Option<string> =>
|
||||
typeof v === "string" && v.length > 0 ? Option.some(v) : Option.none();
|
||||
|
||||
/** Lift an unknown value into `Option<Record>` if it is a plain object. */
|
||||
const asRecord = (v: unknown): Option.Option<Record<string, unknown>> =>
|
||||
typeof v === "object" && v !== null && !globalThis.Array.isArray(v)
|
||||
? Option.some(v as Record<string, unknown>)
|
||||
: Option.none();
|
||||
|
||||
/**
|
||||
* Walk an unknown parsed JSON value looking for a subscription/plan
|
||||
* identifier, returning the first match as an `Option`.
|
||||
*/
|
||||
function findSubscriptionType(value: unknown): Option.Option<string> {
|
||||
if (globalThis.Array.isArray(value)) {
|
||||
return Option.firstSomeOf(value.map(findSubscriptionType));
|
||||
}
|
||||
|
||||
return asRecord(value).pipe(
|
||||
Option.flatMap((record) => {
|
||||
const direct = Option.firstSomeOf(
|
||||
SUBSCRIPTION_TYPE_KEYS.map((key) => asNonEmptyString(record[key])),
|
||||
);
|
||||
if (Option.isSome(direct)) return direct;
|
||||
|
||||
return Option.firstSomeOf(
|
||||
SUBSCRIPTION_CONTAINER_KEYS.map((key) =>
|
||||
asRecord(record[key]).pipe(Option.flatMap(findSubscriptionType)),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function findAuthMethod(value: unknown): Option.Option<string> {
|
||||
if (globalThis.Array.isArray(value)) {
|
||||
return Option.firstSomeOf(value.map(findAuthMethod));
|
||||
}
|
||||
|
||||
return asRecord(value).pipe(
|
||||
Option.flatMap((record) => {
|
||||
const direct = Option.firstSomeOf(
|
||||
AUTH_METHOD_KEYS.map((key) => asNonEmptyString(record[key])),
|
||||
);
|
||||
if (Option.isSome(direct)) return direct;
|
||||
|
||||
return Option.firstSomeOf(
|
||||
AUTH_METHOD_CONTAINER_KEYS.map((key) =>
|
||||
asRecord(record[key]).pipe(Option.flatMap(findAuthMethod)),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to extract a subscription type from the `claude auth status` JSON
|
||||
* output. This is a zero-cost operation on data we already have.
|
||||
*/
|
||||
const decodeUnknownJson = decodeJsonResult(Schema.Unknown);
|
||||
|
||||
function extractSubscriptionTypeFromOutput(result: CommandResult): string | undefined {
|
||||
const parsed = decodeUnknownJson(result.stdout.trim());
|
||||
if (Result.isFailure(parsed)) return undefined;
|
||||
return Option.getOrUndefined(findSubscriptionType(parsed.success));
|
||||
}
|
||||
|
||||
function extractClaudeAuthMethodFromOutput(result: CommandResult): string | undefined {
|
||||
const parsed = decodeUnknownJson(result.stdout.trim());
|
||||
if (Result.isFailure(parsed)) return undefined;
|
||||
return Option.getOrUndefined(findAuthMethod(parsed.success));
|
||||
}
|
||||
|
||||
// ── Dynamic model capability adjustment ─────────────────────────────
|
||||
|
||||
/** Subscription types where the 1M context window is included in the plan. */
|
||||
const PREMIUM_SUBSCRIPTION_TYPES = new Set([
|
||||
"max",
|
||||
"maxplan",
|
||||
"max5",
|
||||
"max20",
|
||||
"enterprise",
|
||||
"team",
|
||||
]);
|
||||
|
||||
function toTitleCaseWords(value: string): string {
|
||||
return value
|
||||
.split(/[\s_-]+/g)
|
||||
.filter(Boolean)
|
||||
.map((part) => part[0]!.toUpperCase() + part.slice(1).toLowerCase())
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
function claudeSubscriptionLabel(subscriptionType: string | undefined): string | undefined {
|
||||
const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
|
||||
if (!normalized) return undefined;
|
||||
|
||||
switch (normalized) {
|
||||
case "max":
|
||||
case "maxplan":
|
||||
case "max5":
|
||||
case "max20":
|
||||
return "Max";
|
||||
case "enterprise":
|
||||
return "Enterprise";
|
||||
case "team":
|
||||
return "Team";
|
||||
case "pro":
|
||||
return "Pro";
|
||||
case "free":
|
||||
return "Free";
|
||||
default:
|
||||
return toTitleCaseWords(subscriptionType!);
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeClaudeAuthMethod(authMethod: string | undefined): string | undefined {
|
||||
const normalized = authMethod?.toLowerCase().replace(/[\s_-]+/g, "");
|
||||
if (!normalized) return undefined;
|
||||
if (normalized === "apikey") return "apiKey";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function claudeAuthMetadata(input: {
|
||||
readonly subscriptionType: string | undefined;
|
||||
readonly authMethod: string | undefined;
|
||||
}): { readonly type: string; readonly label: string } | undefined {
|
||||
if (normalizeClaudeAuthMethod(input.authMethod) === "apiKey") {
|
||||
return {
|
||||
type: "apiKey",
|
||||
label: "Claude API Key",
|
||||
};
|
||||
}
|
||||
|
||||
if (input.subscriptionType) {
|
||||
const subscriptionLabel = claudeSubscriptionLabel(input.subscriptionType);
|
||||
return {
|
||||
type: input.subscriptionType,
|
||||
label: `Claude ${subscriptionLabel ?? toTitleCaseWords(input.subscriptionType)} Subscription`,
|
||||
};
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adjust the built-in model list based on the user's detected subscription.
|
||||
*
|
||||
* - Premium tiers (Max, Enterprise, Team): 1M context becomes the default.
|
||||
* - Other tiers (Pro, free, unknown): 200k context stays the default;
|
||||
* 1M remains available as a manual option so users can still enable it.
|
||||
*/
|
||||
export function adjustModelsForSubscription(
|
||||
baseModels: ReadonlyArray<ServerProviderModel>,
|
||||
subscriptionType: string | undefined,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
|
||||
if (!normalized || !PREMIUM_SUBSCRIPTION_TYPES.has(normalized)) {
|
||||
return baseModels;
|
||||
}
|
||||
|
||||
// Flip 1M to be the default for premium users
|
||||
return baseModels.map((model) => {
|
||||
const caps = model.capabilities;
|
||||
if (!caps || caps.contextWindowOptions.length === 0) return model;
|
||||
|
||||
return {
|
||||
...model,
|
||||
capabilities: {
|
||||
...caps,
|
||||
contextWindowOptions: caps.contextWindowOptions.map((opt) =>
|
||||
opt.value === "1m"
|
||||
? { value: opt.value, label: opt.label, isDefault: true as const }
|
||||
: { value: opt.value, label: opt.label },
|
||||
),
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// ── SDK capability probe ────────────────────────────────────────────
|
||||
|
||||
const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
|
||||
|
||||
/**
|
||||
* Probe account information by spawning a lightweight Claude Agent SDK
|
||||
* session and reading the initialization result.
|
||||
*
|
||||
* The prompt is never sent to the Anthropic API — we abort immediately
|
||||
* after the local initialization phase completes. This gives us the
|
||||
* user's subscription type without incurring any token cost.
|
||||
*
|
||||
* This is used as a fallback when `claude auth status` does not include
|
||||
* subscription type information.
|
||||
*/
|
||||
const probeClaudeCapabilities = (binaryPath: string) => {
|
||||
const abort = new AbortController();
|
||||
return Effect.tryPromise(async () => {
|
||||
const q = claudeQuery({
|
||||
prompt: ".",
|
||||
options: {
|
||||
persistSession: false,
|
||||
pathToClaudeCodeExecutable: binaryPath,
|
||||
abortController: abort,
|
||||
maxTurns: 0,
|
||||
settingSources: [],
|
||||
allowedTools: [],
|
||||
stderr: () => {},
|
||||
},
|
||||
});
|
||||
const init = await q.initializationResult();
|
||||
return { subscriptionType: init.account?.subscriptionType };
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
if (!abort.signal.aborted) abort.abort();
|
||||
}),
|
||||
),
|
||||
Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
Effect.map((result) => {
|
||||
if (Result.isFailure(result)) return undefined;
|
||||
return Option.isSome(result.success) ? result.success.value : undefined;
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const runClaudeCommand = (args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
|
||||
@@ -208,144 +439,81 @@ const runClaudeCommand = (args: ReadonlyArray<string>) =>
|
||||
return yield* spawnAndCollect(claudeSettings.binaryPath, command);
|
||||
});
|
||||
|
||||
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
function* (): Effect.fn.Return<
|
||||
ServerProvider,
|
||||
ServerSettingsError,
|
||||
ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
|
||||
> {
|
||||
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
|
||||
Effect.flatMap((service) => service.getSettings),
|
||||
Effect.map((settings) => settings.providers.claudeAgent),
|
||||
);
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(
|
||||
BUILT_IN_MODELS,
|
||||
PROVIDER,
|
||||
claudeSettings.customModels,
|
||||
);
|
||||
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
|
||||
resolveSubscriptionType?: (binaryPath: string) => Effect.Effect<string | undefined>,
|
||||
): Effect.fn.Return<
|
||||
ServerProvider,
|
||||
ServerSettingsError,
|
||||
ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
|
||||
> {
|
||||
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
|
||||
Effect.flatMap((service) => service.getSettings),
|
||||
Effect.map((settings) => settings.providers.claudeAgent),
|
||||
);
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, claudeSettings.customModels);
|
||||
|
||||
if (!claudeSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Claude is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
if (!claudeSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Claude is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: !isCommandMissingCause(error),
|
||||
version: null,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: isCommandMissingCause(error)
|
||||
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
|
||||
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: !isCommandMissingCause(error),
|
||||
version: null,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: isCommandMissingCause(error)
|
||||
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
|
||||
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (Option.isNone(versionProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
"Claude Agent CLI is installed but failed to run. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
if (Option.isNone(versionProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message:
|
||||
"Claude Agent CLI is installed but failed to run. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const version = versionProbe.success.value;
|
||||
const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
|
||||
if (version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: detail
|
||||
? `Claude Agent CLI is installed but failed to run. ${detail}`
|
||||
: "Claude Agent CLI is installed but failed to run.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
error instanceof Error
|
||||
? `Could not verify Claude authentication status: ${error.message}.`
|
||||
: "Could not verify Claude authentication status.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (Option.isNone(authProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
"Could not verify Claude authentication status. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
|
||||
const version = versionProbe.success.value;
|
||||
const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
|
||||
if (version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
@@ -354,13 +522,99 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: parsed.status,
|
||||
authStatus: parsed.authStatus,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: detail
|
||||
? `Claude Agent CLI is installed but failed to run. ${detail}`
|
||||
: "Claude Agent CLI is installed but failed to run.",
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// ── Auth check + subscription detection ────────────────────────────
|
||||
|
||||
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
// Determine subscription type from multiple sources (cheapest first):
|
||||
// 1. `claude auth status` JSON output (may or may not contain it)
|
||||
// 2. Cached SDK probe (spawns a Claude process on miss, reads
|
||||
// `initializationResult()` for account metadata, then aborts
|
||||
// immediately — no API tokens are consumed)
|
||||
|
||||
let subscriptionType: string | undefined;
|
||||
let authMethod: string | undefined;
|
||||
|
||||
if (Result.isSuccess(authProbe) && Option.isSome(authProbe.success)) {
|
||||
subscriptionType = extractSubscriptionTypeFromOutput(authProbe.success.value);
|
||||
authMethod = extractClaudeAuthMethodFromOutput(authProbe.success.value);
|
||||
}
|
||||
|
||||
if (!subscriptionType && resolveSubscriptionType) {
|
||||
subscriptionType = yield* resolveSubscriptionType(claudeSettings.binaryPath);
|
||||
}
|
||||
|
||||
const resolvedModels = adjustModelsForSubscription(models, subscriptionType);
|
||||
|
||||
// ── Handle auth results (same logic as before, adjusted models) ──
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message:
|
||||
error instanceof Error
|
||||
? `Could not verify Claude authentication status: ${error.message}.`
|
||||
: "Could not verify Claude authentication status.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (Option.isNone(authProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Could not verify Claude authentication status. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
|
||||
const authMetadata = claudeAuthMetadata({ subscriptionType, authMethod });
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: parsed.status,
|
||||
auth: {
|
||||
...parsed.auth,
|
||||
...(authMetadata ? authMetadata : {}),
|
||||
},
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
export const ClaudeProviderLive = Layer.effect(
|
||||
ClaudeProvider,
|
||||
@@ -368,7 +622,16 @@ export const ClaudeProviderLive = Layer.effect(
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const checkProvider = checkClaudeProviderStatus().pipe(
|
||||
const subscriptionProbeCache = yield* Cache.make({
|
||||
capacity: 1,
|
||||
timeToLive: Duration.minutes(5),
|
||||
lookup: (binaryPath: string) =>
|
||||
probeClaudeCapabilities(binaryPath).pipe(Effect.map((r) => r?.subscriptionType)),
|
||||
});
|
||||
|
||||
const checkProvider = checkClaudeProviderStatus((binaryPath) =>
|
||||
Cache.get(subscriptionProbeCache, binaryPath),
|
||||
).pipe(
|
||||
Effect.provideService(ServerSettingsService, serverSettings),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
|
||||
@@ -508,6 +508,42 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps fatal websocket stderr notifications to runtime.error", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
|
||||
|
||||
lifecycleManager.emit("event", {
|
||||
id: asEventId("evt-process-stderr-websocket"),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "process/stderr",
|
||||
turnId: asTurnId("turn-1"),
|
||||
message:
|
||||
"2026-03-31T18:14:06.833399Z ERROR codex_api::endpoint::responses_websocket: failed to connect to websocket: HTTP error: 503 Service Unavailable, url: wss://chatgpt.com/backend-api/codex/responses",
|
||||
} satisfies ProviderEvent);
|
||||
|
||||
const firstEvent = yield* Fiber.join(firstEventFiber);
|
||||
|
||||
assert.equal(firstEvent._tag, "Some");
|
||||
if (firstEvent._tag !== "Some") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.type, "runtime.error");
|
||||
if (firstEvent.value.type !== "runtime.error") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.turnId, "turn-1");
|
||||
assert.equal(firstEvent.value.payload.class, "provider_error");
|
||||
assert.equal(
|
||||
firstEvent.value.payload.message,
|
||||
"2026-03-31T18:14:06.833399Z ERROR codex_api::endpoint::responses_websocket: failed to connect to websocket: HTTP error: 503 Service Unavailable, url: wss://chatgpt.com/backend-api/codex/responses",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves request type when mapping serverRequest/resolved", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
|
||||
@@ -112,6 +112,13 @@ function asNumber(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
|
||||
const FATAL_CODEX_STDERR_SNIPPETS = ["failed to connect to websocket"];
|
||||
|
||||
function isFatalCodexProcessStderrMessage(message: string): boolean {
|
||||
const normalized = message.toLowerCase();
|
||||
return FATAL_CODEX_STDERR_SNIPPETS.some((snippet) => normalized.includes(snippet));
|
||||
}
|
||||
|
||||
function normalizeCodexTokenUsage(value: unknown): ThreadTokenUsageSnapshot | undefined {
|
||||
const usage = asObject(value);
|
||||
const totalUsage = asObject(usage?.total_token_usage ?? usage?.total);
|
||||
@@ -1269,15 +1276,27 @@ function mapToRuntimeEvents(
|
||||
}
|
||||
|
||||
if (event.method === "process/stderr") {
|
||||
const message = event.message ?? "Codex process stderr";
|
||||
const isFatal = isFatalCodexProcessStderrMessage(message);
|
||||
return [
|
||||
{
|
||||
type: "runtime.warning",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
message: event.message ?? "Codex process stderr",
|
||||
...(event.payload !== undefined ? { detail: event.payload } : {}),
|
||||
},
|
||||
},
|
||||
isFatal
|
||||
? {
|
||||
type: "runtime.error",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
message,
|
||||
class: "provider_error" as const,
|
||||
...(event.payload !== undefined ? { detail: event.payload } : {}),
|
||||
},
|
||||
}
|
||||
: {
|
||||
type: "runtime.warning",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
message,
|
||||
...(event.payload !== undefined ? { detail: event.payload } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1345,7 +1364,7 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
if (options?.manager) {
|
||||
return options.manager;
|
||||
}
|
||||
const services = yield* Effect.services<never>();
|
||||
const services = yield* Effect.services();
|
||||
return options?.makeManager?.(services) ?? new CodexAppServerManager(services);
|
||||
});
|
||||
|
||||
@@ -1564,7 +1583,7 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
});
|
||||
|
||||
const registerListener = Effect.fn("registerListener")(function* () {
|
||||
const services = yield* Effect.services<never>();
|
||||
const services = yield* Effect.services();
|
||||
const listenerEffect = Effect.fn("listener")(function* (event: ProviderEvent) {
|
||||
yield* writeNativeEvent(event);
|
||||
const runtimeEvents = mapToRuntimeEvents(event, event.threadId);
|
||||
|
||||
@@ -1,16 +1,25 @@
|
||||
import * as OS from "node:os";
|
||||
import type {
|
||||
ModelCapabilities,
|
||||
CodexModelOptions,
|
||||
CodexSettings,
|
||||
ServerProvider,
|
||||
ServerProviderModel,
|
||||
ServerProviderAuthStatus,
|
||||
ServerProviderAuth,
|
||||
ServerProviderState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Equal, FileSystem, Layer, Option, Path, Result, Stream } from "effect";
|
||||
import {
|
||||
Cache,
|
||||
Duration,
|
||||
Effect,
|
||||
Equal,
|
||||
FileSystem,
|
||||
Layer,
|
||||
Option,
|
||||
Path,
|
||||
Result,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { resolveEffort } from "@t3tools/shared/model";
|
||||
|
||||
import {
|
||||
buildServerProvider,
|
||||
@@ -29,8 +38,16 @@ import {
|
||||
isCodexCliVersionSupported,
|
||||
parseCodexCliVersion,
|
||||
} from "../codexCliVersion";
|
||||
import {
|
||||
adjustCodexModelsForAccount,
|
||||
codexAuthSubLabel,
|
||||
codexAuthSubType,
|
||||
type CodexAccountSnapshot,
|
||||
} from "../codexAccount";
|
||||
import { probeCodexAccount } from "../codexAppServer";
|
||||
import { CodexProvider } from "../Services/CodexProvider";
|
||||
import { ServerSettingsError, ServerSettingsService } from "../../serverSettings";
|
||||
import { ServerSettingsService } from "../../serverSettings";
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
const PROVIDER = "codex" as const;
|
||||
const OPENAI_AUTH_PROVIDERS = new Set(["openai"]);
|
||||
@@ -152,25 +169,9 @@ export function getCodexModelCapabilities(model: string | null | undefined): Mod
|
||||
);
|
||||
}
|
||||
|
||||
export function normalizeCodexModelOptions(
|
||||
model: string | null | undefined,
|
||||
modelOptions: CodexModelOptions | null | undefined,
|
||||
): CodexModelOptions | undefined {
|
||||
const caps = getCodexModelCapabilities(model);
|
||||
const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort);
|
||||
const fastModeEnabled = modelOptions?.fastMode === true;
|
||||
const nextOptions: CodexModelOptions = {
|
||||
...(reasoningEffort
|
||||
? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] }
|
||||
: {}),
|
||||
...(fastModeEnabled ? { fastMode: true } : {}),
|
||||
};
|
||||
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
|
||||
}
|
||||
|
||||
export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
readonly status: Exclude<ServerProviderState, "disabled">;
|
||||
readonly authStatus: ServerProviderAuthStatus;
|
||||
readonly auth: Pick<ServerProviderAuth, "status">;
|
||||
readonly message?: string;
|
||||
} {
|
||||
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
|
||||
@@ -182,7 +183,7 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
auth: { status: "unknown" },
|
||||
message: "Codex CLI authentication status command is unavailable in this Codex version.",
|
||||
};
|
||||
}
|
||||
@@ -196,7 +197,7 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
auth: { status: "unauthenticated" },
|
||||
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
};
|
||||
}
|
||||
@@ -217,31 +218,31 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
})();
|
||||
|
||||
if (parsedAuth.auth === true) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
return { status: "ready", auth: { status: "authenticated" } };
|
||||
}
|
||||
if (parsedAuth.auth === false) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
auth: { status: "unauthenticated" },
|
||||
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
};
|
||||
}
|
||||
if (parsedAuth.attemptedJsonParse) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
auth: { status: "unknown" },
|
||||
message:
|
||||
"Could not verify Codex authentication status from JSON output (missing auth marker).",
|
||||
};
|
||||
}
|
||||
if (result.code === 0) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
return { status: "ready", auth: { status: "authenticated" } };
|
||||
}
|
||||
|
||||
const detail = detailFromResult(result);
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
auth: { status: "unknown" },
|
||||
message: detail
|
||||
? `Could not verify Codex authentication status. ${detail}`
|
||||
: "Could not verify Codex authentication status.",
|
||||
@@ -290,6 +291,21 @@ export const hasCustomModelProvider = readCodexConfigModelProvider().pipe(
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
|
||||
const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
|
||||
|
||||
const probeCodexCapabilities = (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
}) =>
|
||||
Effect.tryPromise((signal) => probeCodexAccount({ ...input, signal })).pipe(
|
||||
Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
Effect.map((result) => {
|
||||
if (Result.isFailure(result)) return undefined;
|
||||
return Option.isSome(result.success) ? result.success.value : undefined;
|
||||
}),
|
||||
);
|
||||
|
||||
const runCodexCommand = (args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const settingsService = yield* ServerSettingsService;
|
||||
@@ -306,179 +322,88 @@ const runCodexCommand = (args: ReadonlyArray<string>) =>
|
||||
return yield* spawnAndCollect(codexSettings.binaryPath, command);
|
||||
});
|
||||
|
||||
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(
|
||||
function* (): Effect.fn.Return<
|
||||
ServerProvider,
|
||||
ServerSettingsError,
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| Path.Path
|
||||
| ServerSettingsService
|
||||
> {
|
||||
const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
|
||||
Effect.flatMap((service) => service.getSettings),
|
||||
Effect.map((settings) => settings.providers.codex),
|
||||
);
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(
|
||||
BUILT_IN_MODELS,
|
||||
PROVIDER,
|
||||
codexSettings.customModels,
|
||||
);
|
||||
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
|
||||
resolveAccount?: (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
}) => Effect.Effect<CodexAccountSnapshot | undefined>,
|
||||
): Effect.fn.Return<
|
||||
ServerProvider,
|
||||
ServerSettingsError,
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| Path.Path
|
||||
| ServerSettingsService
|
||||
> {
|
||||
const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
|
||||
Effect.flatMap((service) => service.getSettings),
|
||||
Effect.map((settings) => settings.providers.codex),
|
||||
);
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, codexSettings.customModels);
|
||||
|
||||
if (!codexSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Codex is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
if (!codexSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Codex is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: !isCommandMissingCause(error),
|
||||
version: null,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: isCommandMissingCause(error)
|
||||
? "Codex CLI (`codex`) is not installed or not on PATH."
|
||||
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: !isCommandMissingCause(error),
|
||||
version: null,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: isCommandMissingCause(error)
|
||||
? "Codex CLI (`codex`) is not installed or not on PATH."
|
||||
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (Option.isNone(versionProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: "Codex CLI is installed but failed to run. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
if (Option.isNone(versionProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: "Codex CLI is installed but failed to run. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const version = versionProbe.success.value;
|
||||
const parsedVersion =
|
||||
parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ??
|
||||
parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
|
||||
if (version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: detail
|
||||
? `Codex CLI is installed but failed to run. ${detail}`
|
||||
: "Codex CLI is installed but failed to run.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: formatCodexCliUpgradeMessage(parsedVersion),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (yield* hasCustomModelProvider) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "ready",
|
||||
authStatus: "unknown",
|
||||
message: "Using a custom Codex model provider; OpenAI login check skipped.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
error instanceof Error
|
||||
? `Could not verify Codex authentication status: ${error.message}.`
|
||||
: "Could not verify Codex authentication status.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (Option.isNone(authProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Could not verify Codex authentication status. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
|
||||
const version = versionProbe.success.value;
|
||||
const parsedVersion =
|
||||
parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ??
|
||||
parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
|
||||
if (version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
@@ -487,13 +412,116 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: parsed.status,
|
||||
authStatus: parsed.authStatus,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: detail
|
||||
? `Codex CLI is installed but failed to run. ${detail}`
|
||||
: "Codex CLI is installed but failed to run.",
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: formatCodexCliUpgradeMessage(parsedVersion),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (yield* hasCustomModelProvider) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "ready",
|
||||
auth: { status: "unknown" },
|
||||
message: "Using a custom Codex model provider; OpenAI login check skipped.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
const account = resolveAccount
|
||||
? yield* resolveAccount({
|
||||
binaryPath: codexSettings.binaryPath,
|
||||
homePath: codexSettings.homePath,
|
||||
})
|
||||
: undefined;
|
||||
const resolvedModels = adjustCodexModelsForAccount(models, account);
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message:
|
||||
error instanceof Error
|
||||
? `Could not verify Codex authentication status: ${error.message}.`
|
||||
: "Could not verify Codex authentication status.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (Option.isNone(authProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Could not verify Codex authentication status. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
|
||||
const authType = codexAuthSubType(account);
|
||||
const authLabel = codexAuthSubLabel(account);
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: parsed.status,
|
||||
auth: {
|
||||
...parsed.auth,
|
||||
...(authType ? { type: authType } : {}),
|
||||
...(authLabel ? { label: authLabel } : {}),
|
||||
},
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
export const CodexProviderLive = Layer.effect(
|
||||
CodexProvider,
|
||||
@@ -502,8 +530,21 @@ export const CodexProviderLive = Layer.effect(
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const accountProbeCache = yield* Cache.make({
|
||||
capacity: 4,
|
||||
timeToLive: Duration.minutes(5),
|
||||
lookup: (key: string) => {
|
||||
const [binaryPath, homePath] = JSON.parse(key) as [string, string | undefined];
|
||||
return probeCodexCapabilities({
|
||||
binaryPath,
|
||||
...(homePath ? { homePath } : {}),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const checkProvider = checkCodexProviderStatus().pipe(
|
||||
const checkProvider = checkCodexProviderStatus((input) =>
|
||||
Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath])),
|
||||
).pipe(
|
||||
Effect.provideService(ServerSettingsService, serverSettings),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
|
||||
@@ -173,7 +173,133 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns the codex plan type in auth and keeps spark for supported plans", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus(() =>
|
||||
Effect.succeed({
|
||||
type: "chatgpt" as const,
|
||||
planType: "pro" as const,
|
||||
sparkEnabled: true,
|
||||
}),
|
||||
);
|
||||
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
assert.strictEqual(status.auth.type, "pro");
|
||||
assert.strictEqual(status.auth.label, "ChatGPT Pro Subscription");
|
||||
assert.deepStrictEqual(
|
||||
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
|
||||
true,
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("hides spark from codex models for unsupported chatgpt plans", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus(() =>
|
||||
Effect.succeed({
|
||||
type: "chatgpt" as const,
|
||||
planType: "plus" as const,
|
||||
sparkEnabled: false,
|
||||
}),
|
||||
);
|
||||
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
assert.strictEqual(status.auth.type, "plus");
|
||||
assert.strictEqual(status.auth.label, "ChatGPT Plus Subscription");
|
||||
assert.deepStrictEqual(
|
||||
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
|
||||
false,
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("hides spark from codex models for non-pro chatgpt subscriptions", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus(() =>
|
||||
Effect.succeed({
|
||||
type: "chatgpt" as const,
|
||||
planType: "team" as const,
|
||||
sparkEnabled: false,
|
||||
}),
|
||||
);
|
||||
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.auth.type, "team");
|
||||
assert.strictEqual(status.auth.label, "ChatGPT Team Subscription");
|
||||
assert.deepStrictEqual(
|
||||
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
|
||||
false,
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns an api key label for codex api key auth", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus(() =>
|
||||
Effect.succeed({
|
||||
type: "apiKey" as const,
|
||||
planType: null,
|
||||
sparkEnabled: false,
|
||||
}),
|
||||
);
|
||||
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
assert.strictEqual(status.auth.type, "apiKey");
|
||||
assert.strictEqual(status.auth.label, "OpenAI API Key");
|
||||
assert.deepStrictEqual(
|
||||
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
|
||||
false,
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
@@ -235,7 +361,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
} finally {
|
||||
process.env.PATH = previousPath;
|
||||
}
|
||||
@@ -249,7 +375,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, false);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(status.auth.status, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI (`codex`) is not installed or not on PATH.",
|
||||
@@ -264,7 +390,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(status.auth.status, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
|
||||
@@ -287,7 +413,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(status.auth.status, "unauthenticated");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
@@ -313,7 +439,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(status.auth.status, "unauthenticated");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
@@ -338,7 +464,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "warning");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(status.auth.status, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI authentication status command is unavailable in this Codex version.",
|
||||
@@ -366,7 +492,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
authStatus: "authenticated",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-03-25T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
@@ -376,7 +502,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
status: "warning",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
authStatus: "unknown",
|
||||
auth: { status: "unknown" },
|
||||
checkedAt: "2026-03-25T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
@@ -494,7 +620,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(status.auth.status, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Using a custom Codex model provider; OpenAI login check skipped.",
|
||||
@@ -537,7 +663,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
const status = yield* checkCodexProviderStatus();
|
||||
// The auth probe runs and sees "not logged in" → error
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(status.auth.status, "unauthenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
@@ -558,7 +684,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
it("exit code 0 with no auth markers is ready", () => {
|
||||
const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
|
||||
assert.strictEqual(parsed.status, "ready");
|
||||
assert.strictEqual(parsed.authStatus, "authenticated");
|
||||
assert.strictEqual(parsed.auth.status, "authenticated");
|
||||
});
|
||||
|
||||
it("JSON with authenticated=false is unauthenticated", () => {
|
||||
@@ -568,7 +694,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "error");
|
||||
assert.strictEqual(parsed.authStatus, "unauthenticated");
|
||||
assert.strictEqual(parsed.auth.status, "unauthenticated");
|
||||
});
|
||||
|
||||
it("JSON without auth marker is warning", () => {
|
||||
@@ -578,7 +704,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "warning");
|
||||
assert.strictEqual(parsed.authStatus, "unknown");
|
||||
assert.strictEqual(parsed.auth.status, "unknown");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -715,7 +841,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
@@ -733,13 +859,63 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns a display label for claude subscription types", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus(() => Effect.succeed("maxplan"));
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
assert.strictEqual(status.auth.type, "maxplan");
|
||||
assert.strictEqual(status.auth.label, "Claude Max Subscription");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns an api key label for claude api key auth", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus();
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
assert.strictEqual(status.auth.type, "apiKey");
|
||||
assert.strictEqual(status.auth.label, "Claude API Key");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"api-key"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when claude is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus();
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, false);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(status.auth.status, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude Agent CLI (`claude`) is not installed or not on PATH.",
|
||||
@@ -771,7 +947,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(status.auth.status, "unauthenticated");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude is not authenticated. Run `claude auth login` and try again.",
|
||||
@@ -799,7 +975,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(status.auth.status, "unauthenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
@@ -819,7 +995,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "warning");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(status.auth.status, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude Agent authentication status command is unavailable in this version of Claude.",
|
||||
@@ -844,7 +1020,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
it("exit code 0 with no auth markers is ready", () => {
|
||||
const parsed = parseClaudeAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
|
||||
assert.strictEqual(parsed.status, "ready");
|
||||
assert.strictEqual(parsed.authStatus, "authenticated");
|
||||
assert.strictEqual(parsed.auth.status, "authenticated");
|
||||
});
|
||||
|
||||
it("JSON with loggedIn=true is authenticated", () => {
|
||||
@@ -854,7 +1030,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "ready");
|
||||
assert.strictEqual(parsed.authStatus, "authenticated");
|
||||
assert.strictEqual(parsed.auth.status, "authenticated");
|
||||
});
|
||||
|
||||
it("JSON with loggedIn=false is unauthenticated", () => {
|
||||
@@ -864,7 +1040,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "error");
|
||||
assert.strictEqual(parsed.authStatus, "unauthenticated");
|
||||
assert.strictEqual(parsed.auth.status, "unauthenticated");
|
||||
});
|
||||
|
||||
it("JSON without auth marker is warning", () => {
|
||||
@@ -874,7 +1050,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "warning");
|
||||
assert.strictEqual(parsed.authStatus, "unknown");
|
||||
assert.strictEqual(parsed.auth.status, "unknown");
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import type { ServerProviderModel } from "@t3tools/contracts";
|
||||
|
||||
export type CodexPlanType =
|
||||
| "free"
|
||||
| "go"
|
||||
| "plus"
|
||||
| "pro"
|
||||
| "team"
|
||||
| "business"
|
||||
| "enterprise"
|
||||
| "edu"
|
||||
| "unknown";
|
||||
|
||||
export interface CodexAccountSnapshot {
|
||||
readonly type: "apiKey" | "chatgpt" | "unknown";
|
||||
readonly planType: CodexPlanType | null;
|
||||
readonly sparkEnabled: boolean;
|
||||
}
|
||||
|
||||
export const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
|
||||
export const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
|
||||
const CODEX_SPARK_ENABLED_PLAN_TYPES = new Set<CodexPlanType>(["pro"]);
|
||||
|
||||
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: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (accountType === "chatgpt") {
|
||||
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
|
||||
return {
|
||||
type: "chatgpt",
|
||||
planType,
|
||||
sparkEnabled: CODEX_SPARK_ENABLED_PLAN_TYPES.has(planType),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
type: "unknown",
|
||||
planType: null,
|
||||
sparkEnabled: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function codexAuthSubType(account: CodexAccountSnapshot | undefined): string | undefined {
|
||||
if (account?.type === "apiKey") {
|
||||
return "apiKey";
|
||||
}
|
||||
|
||||
if (account?.type !== "chatgpt") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return account.planType && account.planType !== "unknown" ? account.planType : "chatgpt";
|
||||
}
|
||||
|
||||
export function codexAuthSubLabel(account: CodexAccountSnapshot | undefined): string | undefined {
|
||||
switch (codexAuthSubType(account)) {
|
||||
case "apiKey":
|
||||
return "OpenAI API Key";
|
||||
case "chatgpt":
|
||||
return "ChatGPT Subscription";
|
||||
case "free":
|
||||
return "ChatGPT Free Subscription";
|
||||
case "go":
|
||||
return "ChatGPT Go Subscription";
|
||||
case "plus":
|
||||
return "ChatGPT Plus Subscription";
|
||||
case "pro":
|
||||
return "ChatGPT Pro Subscription";
|
||||
case "team":
|
||||
return "ChatGPT Team Subscription";
|
||||
case "business":
|
||||
return "ChatGPT Business Subscription";
|
||||
case "enterprise":
|
||||
return "ChatGPT Enterprise Subscription";
|
||||
case "edu":
|
||||
return "ChatGPT Edu Subscription";
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function adjustCodexModelsForAccount(
|
||||
baseModels: ReadonlyArray<ServerProviderModel>,
|
||||
account: CodexAccountSnapshot | undefined,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
if (account?.sparkEnabled !== false) {
|
||||
return baseModels;
|
||||
}
|
||||
|
||||
return baseModels.filter((model) => model.isCustom || model.slug !== CODEX_SPARK_MODEL);
|
||||
}
|
||||
|
||||
export function resolveCodexModelForAccount(
|
||||
model: string | undefined,
|
||||
account: CodexAccountSnapshot,
|
||||
): string | undefined {
|
||||
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
|
||||
return model;
|
||||
}
|
||||
|
||||
return CODEX_DEFAULT_MODEL;
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import readline from "node:readline";
|
||||
import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount";
|
||||
|
||||
interface JsonRpcProbeResponse {
|
||||
readonly id?: unknown;
|
||||
readonly result?: unknown;
|
||||
readonly error?: {
|
||||
readonly message?: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
function readErrorMessage(response: JsonRpcProbeResponse): string | undefined {
|
||||
return typeof response.error?.message === "string" ? response.error.message : undefined;
|
||||
}
|
||||
|
||||
export function buildCodexInitializeParams() {
|
||||
return {
|
||||
clientInfo: {
|
||||
name: "t3code_desktop",
|
||||
title: "T3 Code Desktop",
|
||||
version: "0.1.0",
|
||||
},
|
||||
capabilities: {
|
||||
experimentalApi: true,
|
||||
},
|
||||
} as const;
|
||||
}
|
||||
|
||||
export function killCodexChildProcess(child: ChildProcessWithoutNullStreams): void {
|
||||
if (process.platform === "win32" && child.pid !== undefined) {
|
||||
try {
|
||||
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
||||
return;
|
||||
} catch {
|
||||
// Fall through to direct kill when taskkill is unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
child.kill();
|
||||
}
|
||||
|
||||
export async function probeCodexAccount(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
readonly signal?: AbortSignal;
|
||||
}): Promise<CodexAccountSnapshot> {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const child = spawn(input.binaryPath, ["app-server"], {
|
||||
env: {
|
||||
...process.env,
|
||||
...(input.homePath ? { CODEX_HOME: input.homePath } : {}),
|
||||
},
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
|
||||
let completed = false;
|
||||
|
||||
const cleanup = () => {
|
||||
output.removeAllListeners();
|
||||
output.close();
|
||||
child.removeAllListeners();
|
||||
if (!child.killed) {
|
||||
killCodexChildProcess(child);
|
||||
}
|
||||
};
|
||||
|
||||
const finish = (callback: () => void) => {
|
||||
if (completed) return;
|
||||
completed = true;
|
||||
cleanup();
|
||||
callback();
|
||||
};
|
||||
|
||||
const fail = (error: unknown) =>
|
||||
finish(() =>
|
||||
reject(
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error(`Codex account probe failed: ${String(error)}.`),
|
||||
),
|
||||
);
|
||||
|
||||
if (input.signal?.aborted) {
|
||||
fail(new Error("Codex account probe aborted."));
|
||||
return;
|
||||
}
|
||||
input.signal?.addEventListener("abort", () => fail(new Error("Codex account probe aborted.")));
|
||||
|
||||
const writeMessage = (message: unknown) => {
|
||||
if (!child.stdin.writable) {
|
||||
fail(new Error("Cannot write to codex app-server stdin."));
|
||||
return;
|
||||
}
|
||||
|
||||
child.stdin.write(`${JSON.stringify(message)}\n`);
|
||||
};
|
||||
|
||||
output.on("line", (line) => {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(line);
|
||||
} catch {
|
||||
fail(new Error("Received invalid JSON from codex app-server during account probe."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!parsed || typeof parsed !== "object") {
|
||||
return;
|
||||
}
|
||||
|
||||
const response = parsed as JsonRpcProbeResponse;
|
||||
if (response.id === 1) {
|
||||
const errorMessage = readErrorMessage(response);
|
||||
if (errorMessage) {
|
||||
fail(new Error(`initialize failed: ${errorMessage}`));
|
||||
return;
|
||||
}
|
||||
|
||||
writeMessage({ method: "initialized" });
|
||||
writeMessage({ id: 2, method: "account/read", params: {} });
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.id === 2) {
|
||||
const errorMessage = readErrorMessage(response);
|
||||
if (errorMessage) {
|
||||
fail(new Error(`account/read failed: ${errorMessage}`));
|
||||
return;
|
||||
}
|
||||
|
||||
finish(() => resolve(readCodexAccountSnapshot(response.result)));
|
||||
}
|
||||
});
|
||||
|
||||
child.once("error", fail);
|
||||
child.once("exit", (code, signal) => {
|
||||
if (completed) return;
|
||||
fail(
|
||||
new Error(
|
||||
`codex app-server exited before probe completed (code=${code ?? "null"}, signal=${signal ?? "null"}).`,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
writeMessage({
|
||||
id: 1,
|
||||
method: "initialize",
|
||||
params: buildCodexInitializeParams(),
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { Duration, Effect, PubSub, Ref, Scope, Stream } from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import type { ServerProviderShape } from "./Services/ServerProvider";
|
||||
import { ServerSettingsError } from "../serverSettings";
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
export function makeManagedServerProvider<Settings>(input: {
|
||||
readonly getSettings: Effect.Effect<Settings>;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type {
|
||||
ServerProvider,
|
||||
ServerProviderAuthStatus,
|
||||
ServerProviderAuth,
|
||||
ServerProviderModel,
|
||||
ServerProviderState,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -21,7 +21,7 @@ export interface ProviderProbeResult {
|
||||
readonly installed: boolean;
|
||||
readonly version: string | null;
|
||||
readonly status: Exclude<ServerProviderState, "disabled">;
|
||||
readonly authStatus: ServerProviderAuthStatus;
|
||||
readonly auth: ServerProviderAuth;
|
||||
readonly message?: string;
|
||||
}
|
||||
|
||||
@@ -137,7 +137,7 @@ export function buildServerProvider(input: {
|
||||
installed: input.probe.installed,
|
||||
version: input.probe.version,
|
||||
status: input.enabled ? input.probe.status : "disabled",
|
||||
authStatus: input.probe.authStatus,
|
||||
auth: input.probe.auth,
|
||||
checkedAt: input.checkedAt,
|
||||
...(input.probe.message ? { message: input.probe.message } : {}),
|
||||
models: input.models,
|
||||
|
||||
Loaded 100 of 295 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user