Compare commits

..
Author SHA1 Message Date
Cursor Agent cbe73cb407 Remove debug test artifacts and use consistent byte tracking in processChunk
- Delete spawned2.txt and tmp-test.cmd (debug/test leftovers from manual process spawn testing)
- Use limitedChunk.nextBytes uniformly in both truncate and non-truncate paths in GitCore processChunk
2026-04-11 06:04:05 +00:00
julius 8d257e2c2e Open VS Code on Windows via protocol URI
- Launch `explorer.exe` with a `vscode://file/...` target for Windows editor opens
- Improve Windows spawn handling with `windowsHide` and protocol URI coverage
2026-04-10 22:57:57 -07:00
julius 1218eff099 Launch Windows shims through PowerShell Start-Process
- Prefer PowerShell for detached Windows batch shim launches
- Preserve literal args in the encoded Start-Process command
- Update launcher tests for the new spawn path
2026-03-31 07:51:50 -07:00
Julius Marminge 72c3478719 naming 2026-03-31 14:31:01 -07:00
Julius Marminge 9b3394c1d6 rm aliases 2026-03-31 14:30:06 -07:00
Cursor Agent c5472479b6 fix: detect immediate exit failures in detached launches and handle empty app lists
- defaultSpawnDetached now waits a grace period after spawn to catch
  processes that exit non-zero immediately, allowing runFirstAvailablePlan
  to fall through to the next strategy instead of silently succeeding.
- normalizeAppCandidates returns [undefined] (the platform-default branch)
  when the resolved candidate list is empty, so an empty app array behaves
  the same as omitting app entirely.

Applied via @cursor push command
2026-03-31 21:15:09 +00:00
Julius Marminge 0cdb35e73b Skip WSL browser launch in containers
- Treat container env detection consistently when resolving desktop launch options
- Fall back to direct kill if `taskkill` exits nonzero or cannot spawn
- Add coverage for the WSL container and taskkill fallback cases
2026-03-31 12:56:35 -07:00
Julius Marminge 935e7c6cea Refactor process helpers for Windows handling and output limits
- Extract shared Windows command/process utilities
- Add process tree kill and probe process wrappers
- Cover output truncation and Windows command behavior with tests
2026-03-31 12:15:04 -07:00
Julius Marminge 439e8bcd42 Preserve waited app launch exit errors
- Map spawn failures before nonzero-exit checks in desktop launcher
- Add regression coverage for waited direct app launches on Linux
2026-03-31 11:34:21 -07:00
Julius Marminge 7fa5304e87 Detach direct app launches on Windows when not waiting
- Preserve app launch arguments while passing the target URL
- Run non-waited direct launches detached with ignored stdio
2026-03-31 11:15:19 -07:00
Julius Marmingeandcodex d358a66439 Merge origin/main into t3code/open-service-effect-api
Co-authored-by: codex <[email protected]>
2026-03-31 10:57:50 -07:00
Julius Marminge d7257df2ae Extract desktop launcher service layer
- Move browser/editor launch logic out of `open.ts`
- Wire server startup and WebSocket tests to `DesktopLauncher`
- Add validation and fallback error coverage for launch attempts
2026-03-31 10:54:26 -07:00
Julius Marminge 2ade03788b Refactor open service onto Effect-backed process spawning
- Add external opener support alongside browser/editor launches
- Remove the `open` dependency and cover platform behavior in tests
2026-03-31 00:31:41 -07:00
Julius Marminge 2d03847ccd Extract project/workspace related functionality to Effect services (#1524) 2026-03-31 00:08:51 -07:00
Julius Marminge d303ac39cb Replace wait-on with internal desktop resource polling (#1600) 2026-03-30 23:17:33 -07:00
Julius Marminge 48fc85e7fe Bump Effect catalog dependencies (#1594) 2026-03-30 22:08:25 +00:00
0ea639196a Refactor web orchestration sync to incremental events and isolated recovery (#1560)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-03-30 12:51:49 -07:00
Utkarsh Patil 6f51725732 refactor(web): remove redundant add-project cancel button (#1302) 2026-03-30 10:31:38 -07:00
Julius Marminge 8622b952ca Refactor terminal manager onto Effect runtime (#1525) 2026-03-30 10:19:11 -07:00
Julius Marminge f47c1f1046 Update README.md (#1565) 2026-03-30 05:37:28 +00:00
Julius Marminge 145ddfc408 Document T3 Code install methods (#1564) 2026-03-29 22:33:05 -07:00
Ivor 0bb787b90d Clarify provider setup in README (#1406) 2026-03-29 22:09:23 -07:00
Julius Marminge 59f23d7bfd Show archive action on hover with confirm focus (#1561) 2026-03-29 18:36:53 -07:00
Naufal PutraandJulius Marminge 4a4795e5f0 Scroll active item into view in composer menu (#1557)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-30 01:33:47 +00:00
Efroim-PropelandJulius Marminge 5b58f74e9a fix(desktop): default confirm dialog selection to "No" (#1400)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-29 18:20:56 -07:00
Julius Marmingeandcodex 32dca3b76b [codex] debounce thread jump hint pills (#1526)
Co-authored-by: codex <[email protected]>
2026-03-29 18:19:37 -07:00
Abdulelah Hajjar 6358444900 fix(web): Fix duplicate highlight in composer slash command menu (#1445) 2026-03-29 18:14:59 -07:00
Alexander VostresandJulius Marminge 792ad4b5c1 Fix model settings getting stuck (#1538)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-30 01:13:16 +00:00
Craig d41781987c fix(web): preserve scroll when collapsing large changed-files trees (#1113) 2026-03-29 17:53:21 -07:00
shivamandEwan fc6507066e fix(windows): hover-effect-fix-in-the-branch-ui (#1559)
Co-authored-by: Ewan <[email protected]>
2026-03-29 17:53:03 -07:00
bf9c828aef Make provider model lists dynamic based on auth context (#1556)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-03-29 17:51:05 -07:00
shivam 7b676b76de fix: show empty project thread state in sidebar (#1546) 2026-03-29 11:47:51 -07:00
Julius Marminge d5f2333173 Show hidden thread status in sidebar (#1517) 2026-03-29 11:47:17 -07:00
Alexander Vostres 40e7dbdae9 Fix for broken Codex model selection for 'Text Generation Model' (#1543) 2026-03-29 11:27:20 -07:00
Julius Marminge a60daa1c76 Wrap orchestration reactor starts in Effect.fn (#1513) 2026-03-29 05:57:32 +00:00
Julius Marminge bc1024caf0 Inline sqlite error classification (#1515) 2026-03-29 05:55:18 +00:00
Julius Marminge a1c428b6e2 Refactor projection pipeline side effects (#1512) 2026-03-28 22:54:37 -07:00
Julius Marminge 00f3efb95b Make DrainableWorker drain off outstanding count (#1514) 2026-03-28 22:52:39 -07:00
Julius Marminge 7f3387a86c Annotate Git core Effect.fn helpers (#1511) 2026-03-28 22:35:18 -07:00
t3-code[bot] 5462d50177 chore(release): prepare v0.0.15 2026-03-29 04:52:14 +00:00
f82bae1668 Update system overhaul (#1505)
Co-authored-by: Jono Kemball <[email protected]>
Co-authored-by: Ariaj Sarkar <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-03-29 04:23:10 +00:00
Julius Marminge 9e60597174 Truncate oversized git diffs instead of failing (#1499) 2026-03-28 20:50:23 -07:00
Julius Marminge afc807ac3f Add new GitHub users to VOUCHED.td (#1508) 2026-03-29 01:28:52 +00:00
Theo BrowneandJulius Marminge 58ba4f1263 Add keyboard shortcuts for jumping to sidebar threads (#1456)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-28 18:23:30 -07:00
maria 5513845fd5 feat(threads): auto-generate first-turn thread titles (#1375) 2026-03-28 17:03:01 -07:00
Julius Marminge 33773ff17e Harden Claude stream exit handling (#1504) 2026-03-28 16:13:52 -07:00
Jono KemballandJulius Marminge 64d21bd6d2 fix: Prevent sidebar project dragging when using macos control+click to open context menu (#873)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-28 23:09:19 +00:00
shivamandJulius Marminge 5210a833a5 Fix sidebar thread panel weird states. (#1497)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-28 15:58:37 -07:00
maria 5b1d5c1220 fix(ci): use whitespace-insensitive PR size diff (#1500) 2026-03-28 15:49:53 -07:00
Noah GregoryandJulius Marminge f4617e7b19 feat: add mock update server (#1180)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-28 15:44:13 -07:00
Julius Marminge c426452239 Tighten settings nav and add Escape back navigation (#1503) 2026-03-28 22:01:37 +00:00
Danila YudinandJulius Marminge 73b2f255a9 fix: add noopener to external chat markdown links (#1315)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-28 11:59:56 -07:00
FllipandJulius Marminge ce463a5360 fix(web): add project path action to sidebar menu (#1436)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-28 18:56:46 +00:00
DanielsandDaniel Schwarz 52fa6a7333 fix(desktop): ensure all windows are destroyed before launching the NSIS installer during update process (#1461)
Co-authored-by: Daniel Schwarz <[email protected]>
2026-03-28 11:51:44 -07:00
Rishi Raj Singh ChauhanandJulius Marminge 04298962be Fix server fallback to direct fd read on /proc/self/fd failure (#1488)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-28 18:41:26 +00:00
Ibrahim Elkamali 61f983098b fix(web): allow switching away from Ultrathink without manual prompt editing (#1307) 2026-03-28 11:38:29 -07:00
Ryan GastandJulius Marminge 32c1f98a02 Fix Linux desktop Codex CLI detection at startup (#1100)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-28 18:21:56 +00:00
smalitobulesandsmalitobules 5851b8aca4 fix: trust node-pty install scripts on linux (#1451)
Co-authored-by: smalitobules <[email protected]>
2026-03-28 17:53:29 +00:00
Julius Marminge 3e2df5a782 Normalize typed provider runtime ingestion (#1475) 2026-03-28 10:51:01 -07:00
shivamandJulius Marminge f0cdaf94c2 Add thread archiving and settings navigation (#1359)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-28 10:48:34 -07:00
Maansen 48196e67a7 fix(web): linkify Windows C:/ paths in terminal output (#1483) 2026-03-28 10:37:36 -07:00
Alexander Vostres 80a176fe1f Add eol=lf to .gitattributes for Windows users (#1491) 2026-03-28 10:34:00 -07:00
Alexander Vostres 42ea7cfae1 Detect command not found when checking codex/claude CLI on Windows (#1492) 2026-03-28 17:28:56 +00:00
Alexander Vostres d2e6c82709 Skip a unit test that is using a bash script on Windows (#1490) 2026-03-28 10:26:13 -07:00
Julius Marminge 23b3f0c3d0 Refactor Codex adapter lifecycle helpers (#1478) 2026-03-27 18:43:35 -07:00
Maxwell BrownandJulius Marminge e08cea3a23 Improve drain semantics via STM in DrainableWorker (#1474)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-27 18:05:14 -07:00
Snowy 83eb396c40 fix(threads): Keep active-turn runtime errors from ending sessions (#1261) 2026-03-27 17:38:31 -07:00
Julius Marminge 59a383e1ea Add Effect.fn refactor checklist (#1476) 2026-03-27 17:35:49 -07:00
Harshit Agarwal fb7260792f fix(claude): avoid resetting the Claude model on every turn (#1466) 2026-03-27 12:04:28 -07:00
Julius Marminge d8a485ea7e Support gh pr checkout pull request references (#1457) 2026-03-27 00:08:45 -07:00
Guilherme Vieira 02989fe600 fix(web): improve chat header badge and title flex distribution (#1309) 2026-03-26 21:47:57 -07:00
Nassim Najjar 648f0676bd Add VS Code Insiders and VSCodium to Open In editor picker (#1392) 2026-03-27 04:46:43 +00:00
Julius Marminge add5f34619 Add Claude context window selection support (#1422) 2026-03-26 14:31:35 -07:00
Julius Marminge 9403429a7a Make server settings authoritative for runtime behavior (#1421) 2026-03-25 23:58:58 -07:00
BeckWangthumboon 37cf0c1144 fix(web): add pointer cursor to composer send button (#1415) 2026-03-26 02:02:18 +00:00
Abdulelah Hajjar bf1f3e1c4f fix(web): clear composer border after picker dismissal (#1382) 2026-03-26 02:01:53 +00:00
morganyandmorgan ye 2aa11ae076 fix(desktop): prevent git actions and terminal toggle from overlapping (#1423)
Co-authored-by: morgan ye <[email protected]>
2026-03-25 23:59:12 +00:00
8888f6a0c9 Add copy action to error toast messages (#1416)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-03-25 13:01:04 -07:00
254 changed files with 28303 additions and 13874 deletions

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
# git autocrlf=true converts LF to CRLF on Windows, causing issues with oxfmt
* text=auto eol=lf
+2 -1
View File
@@ -28,4 +28,5 @@ github:realAhmedRoach
github:shiroyasha9
github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
github:Ymit24
github:shivamhwp
+68 -31
View File
@@ -124,25 +124,49 @@ jobs:
group: pr-size-${{ github.event.pull_request.number }}
cancel-in-progress: true
steps:
- name: Checkout base repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Sync PR size label
uses: actions/github-script@v8
env:
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
with:
script: |
const { execFileSync } = require("node:child_process");
const issueNumber = context.payload.pull_request.number;
const baseSha = context.payload.pull_request.base.sha;
const headSha = context.payload.pull_request.head.sha;
const headTrackingRef = `refs/remotes/pr-size/${issueNumber}`;
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
// Keep this aligned with the repo's test entrypoints and test-only support files.
const testFilePatterns = [
/(^|\/)__tests__(\/|$)/,
/(^|\/)tests?(\/|$)/,
/^apps\/server\/integration\//,
/\.(test|spec|browser|integration)\.[^.\/]+$/,
const testExcludePathspecs = [
":(glob,exclude)**/__tests__/**",
":(glob,exclude)**/test/**",
":(glob,exclude)**/tests/**",
":(glob,exclude)apps/server/integration/**",
":(glob,exclude)**/*.test.*",
":(glob,exclude)**/*.spec.*",
":(glob,exclude)**/*.browser.*",
":(glob,exclude)**/*.integration.*",
];
const isTestFile = (filename) =>
testFilePatterns.some((pattern) => pattern.test(filename));
const sumNumstat = (text) =>
text
.split("\n")
.filter(Boolean)
.reduce((total, line) => {
const [insertionsRaw = "0", deletionsRaw = "0"] = line.split("\t");
const additions =
insertionsRaw === "-" ? 0 : Number.parseInt(insertionsRaw, 10) || 0;
const deletions =
deletionsRaw === "-" ? 0 : Number.parseInt(deletionsRaw, 10) || 0;
return total + additions + deletions;
}, 0);
const resolveSizeLabel = (totalChangedLines) => {
if (totalChangedLines < 10) {
@@ -168,40 +192,53 @@ jobs:
return "size:XXL";
};
const files = await github.paginate(
github.rest.pulls.listFiles,
execFileSync("git", ["fetch", "--no-tags", "origin", baseSha], {
stdio: "inherit",
});
execFileSync(
"git",
["fetch", "--no-tags", "origin", `+refs/pull/${issueNumber}/head:${headTrackingRef}`],
{
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: issueNumber,
per_page: 100,
stdio: "inherit",
},
(response) => response.data,
);
if (files.length >= 3000) {
const resolvedHeadSha = execFileSync("git", ["rev-parse", headTrackingRef], {
encoding: "utf8",
}).trim();
if (resolvedHeadSha !== headSha) {
core.warning(
"The GitHub pull request files API may truncate results at 3,000 files; PR size may be undercounted.",
`Fetched head SHA ${resolvedHeadSha} does not match pull request head SHA ${headSha}; using fetched ref for sizing.`,
);
}
let testChangedLines = 0;
let nonTestChangedLines = 0;
execFileSync("git", ["cat-file", "-e", `${baseSha}^{commit}`], {
stdio: "inherit",
});
for (const file of files) {
const changedLinesForFile = (file.additions ?? 0) + (file.deletions ?? 0);
const diffArgs = [
"diff",
"--numstat",
"--ignore-all-space",
"--ignore-blank-lines",
`${baseSha}...${resolvedHeadSha}`,
];
if (changedLinesForFile === 0) {
continue;
}
if (isTestFile(file.filename)) {
testChangedLines += changedLinesForFile;
continue;
}
nonTestChangedLines += changedLinesForFile;
}
const totalChangedLines = sumNumstat(
execFileSync(
"git",
diffArgs,
{ encoding: "utf8" },
),
);
const nonTestChangedLines = sumNumstat(
execFileSync("git", [...diffArgs, "--", ".", ...testExcludePathspecs], {
encoding: "utf8",
}),
);
const testChangedLines = Math.max(0, totalChangedLines - nonTestChangedLines);
const changedLines = nonTestChangedLines === 0 ? testChangedLines : nonTestChangedLines;
const nextLabelName = resolveSizeLabel(changedLines);
+1
View File
@@ -12,6 +12,7 @@ packages/*/dist
build/
.logs/
release/
release-mock/
.t3
.idea/
apps/web/.playwright
+1 -1
View File
@@ -1 +1 @@
AGENTS.md
AGENTS.md
+28 -4
View File
@@ -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
+2 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.14",
"version": "0.0.15",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
@@ -24,8 +24,7 @@
"@types/node": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:",
"wait-on": "^8.0.2"
"vitest": "catalog:"
},
"productName": "T3 Code (Alpha)"
}
+5 -3
View File
@@ -1,9 +1,9 @@
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}`;
@@ -20,8 +20,10 @@ 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 };
+119
View File
@@ -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 -1
View File
@@ -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,
+53 -6
View File
@@ -20,6 +20,7 @@ import * as Effect from "effect/Effect";
import type {
DesktopTheme,
DesktopUpdateActionResult,
DesktopUpdateCheckResult,
DesktopUpdateState,
} from "@t3tools/contracts";
import { autoUpdater } from "electron-updater";
@@ -56,6 +57,7 @@ const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
const STATE_DIR = Path.join(BASE_DIR, "userdata");
@@ -287,10 +289,12 @@ let updatePollTimer: ReturnType<typeof setInterval> | null = null;
let updateStartupTimer: ReturnType<typeof setTimeout> | null = null;
let updateCheckInFlight = false;
let updateDownloadInFlight = false;
let updateInstallInFlight = false;
let updaterConfigured = false;
let updateState: DesktopUpdateState = initialUpdateState();
function resolveUpdaterErrorContext(): DesktopUpdateErrorContext {
if (updateInstallInFlight) return "install";
if (updateDownloadInFlight) return "download";
if (updateCheckInFlight) return "check";
return updateState.errorContext;
@@ -754,13 +758,13 @@ function shouldEnableAutoUpdates(): boolean {
);
}
async function checkForUpdates(reason: string): Promise<void> {
if (isQuitting || !updaterConfigured || updateCheckInFlight) return;
async function checkForUpdates(reason: string): Promise<boolean> {
if (isQuitting || !updaterConfigured || updateCheckInFlight) return false;
if (updateState.status === "downloading" || updateState.status === "downloaded") {
console.info(
`[desktop-updater] Skipping update check (${reason}) while status=${updateState.status}.`,
);
return;
return false;
}
updateCheckInFlight = true;
setUpdateState(reduceDesktopUpdateStateOnCheckStart(updateState, new Date().toISOString()));
@@ -768,12 +772,14 @@ async function checkForUpdates(reason: string): Promise<void> {
try {
await autoUpdater.checkForUpdates();
return true;
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
setUpdateState(
reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()),
);
console.error(`[desktop-updater] Failed to check for updates: ${message}`);
return true;
} finally {
updateCheckInFlight = false;
}
@@ -807,13 +813,22 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed
}
isQuitting = true;
updateInstallInFlight = true;
clearUpdatePollTimer();
try {
await stopBackendAndWaitForExit();
autoUpdater.quitAndInstall();
return { accepted: true, completed: true };
// Destroy all windows before launching the NSIS installer to avoid the installer finding live windows it needs to close.
for (const win of BrowserWindow.getAllWindows()) {
win.destroy();
}
// `quitAndInstall()` only starts the handoff to the updater. The actual
// install may still fail asynchronously, so keep the action incomplete
// until we either quit or receive an updater error.
autoUpdater.quitAndInstall(true, true);
return { accepted: true, completed: false };
} catch (error: unknown) {
const message = formatErrorMessage(error);
updateInstallInFlight = false;
isQuitting = false;
setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
console.error(`[desktop-updater] Failed to install update: ${message}`);
@@ -850,6 +865,13 @@ function configureAutoUpdater(): void {
}
}
if (process.env.T3CODE_DESKTOP_MOCK_UPDATES) {
autoUpdater.setFeedURL({
provider: "generic",
url: `http://localhost:${process.env.T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT ?? 3000}`,
});
}
autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = false;
// Keep alpha branding, but force all installs onto the stable update track.
@@ -886,6 +908,13 @@ function configureAutoUpdater(): void {
});
autoUpdater.on("error", (error) => {
const message = formatErrorMessage(error);
if (updateInstallInFlight) {
updateInstallInFlight = false;
isQuitting = false;
setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
console.error(`[desktop-updater] Updater error: ${message}`);
return;
}
if (!updateCheckInFlight && !updateDownloadInFlight) {
setUpdateState({
status: "error",
@@ -1141,6 +1170,7 @@ function registerIpcHandlers(): void {
id: item.id,
label: item.label,
destructive: item.destructive === true,
disabled: item.disabled === true,
}));
if (normalizedItems.length === 0) {
return null;
@@ -1171,6 +1201,7 @@ function registerIpcHandlers(): void {
}
const itemOption: MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
click: () => resolve(item.id),
};
if (item.destructive) {
@@ -1236,6 +1267,21 @@ function registerIpcHandlers(): void {
state: updateState,
} satisfies DesktopUpdateActionResult;
});
ipcMain.removeHandler(UPDATE_CHECK_CHANNEL);
ipcMain.handle(UPDATE_CHECK_CHANNEL, async () => {
if (!updaterConfigured) {
return {
checked: false,
state: updateState,
} satisfies DesktopUpdateCheckResult;
}
const checked = await checkForUpdates("web-ui");
return {
checked,
state: updateState,
} satisfies DesktopUpdateCheckResult;
});
}
function getIconOption(): { icon: string } | Record<string, never> {
@@ -1359,6 +1405,7 @@ async function bootstrap(): Promise<void> {
app.on("before-quit", () => {
isQuitting = true;
updateInstallInFlight = false;
writeDesktopLogHeader("before-quit received");
clearUpdatePollTimer();
stopBackend();
@@ -1388,7 +1435,7 @@ app
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
if (process.platform !== "darwin" && !isQuitting) {
app.quit();
}
});
+2
View File
@@ -9,6 +9,7 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
@@ -35,6 +36,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
};
},
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL),
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
onUpdateState: (listener) => {
+24 -4
View File
@@ -62,14 +62,13 @@ describe("syncShellEnvironment", () => {
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
it("does nothing outside macOS", () => {
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
}));
@@ -78,8 +77,29 @@ describe("syncShellEnvironment", () => {
readEnvironment,
});
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
expect(env.PATH).toBe("/home/linuxbrew/.linuxbrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
});
it("does nothing outside macOS and linux", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "C:/Program Files/Git/bin/bash.exe",
PATH: "C:\\Windows\\System32",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/usr/local/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
}));
syncShellEnvironment(env, {
platform: "win32",
readEnvironment,
});
expect(readEnvironment).not.toHaveBeenCalled();
expect(env.PATH).toBe("/usr/bin");
expect(env.PATH).toBe("C:\\Windows\\System32");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
});
+10 -3
View File
@@ -1,4 +1,8 @@
import { readEnvironmentFromLoginShell, ShellEnvironmentReader } from "@t3tools/shared/shell";
import {
readEnvironmentFromLoginShell,
resolveLoginShell,
ShellEnvironmentReader,
} from "@t3tools/shared/shell";
export function syncShellEnvironment(
env: NodeJS.ProcessEnv = process.env,
@@ -7,10 +11,13 @@ export function syncShellEnvironment(
readEnvironment?: ShellEnvironmentReader;
} = {},
): void {
if ((options.platform ?? process.platform) !== "darwin") return;
const platform = options.platform ?? process.platform;
if (platform !== "darwin" && platform !== "linux") return;
try {
const shell = env.SHELL ?? "/bin/zsh";
const shell = resolveLoginShell(platform, env.SHELL);
if (!shell) return;
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
"PATH",
"SSH_AUTH_SOCK",
@@ -38,6 +38,7 @@ import { ProjectionPendingApprovalRepository } from "../src/persistence/Services
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
@@ -67,7 +68,7 @@ import {
type TestProviderAdapterHarness,
} from "./TestProviderAdapter.integration.ts";
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
function runGit(cwd: string, args: ReadonlyArray<string>) {
return execFileSync("git", args, {
@@ -306,7 +307,8 @@ export const makeOrchestrationIntegrationHarness = (
Effect.succeed({ branch: input.newBranch }),
} as unknown as GitCoreShape);
const textGenerationLayer = Layer.succeed(TextGeneration, {
generateBranchName: () => Effect.succeed({ branch: null }),
generateBranchName: () => Effect.succeed({ branch: "update" }),
generateThreadTitle: () => Effect.succeed({ title: "New thread" }),
} as unknown as TextGenerationShape);
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
@@ -316,6 +318,12 @@ export const makeOrchestrationIntegrationHarness = (
);
const checkpointReactorLayer = CheckpointReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(
WorkspaceEntriesLive.pipe(
Layer.provideMerge(gitCoreLayer),
Layer.provide(NodeServices.layer),
),
),
);
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
Layer.provideMerge(runtimeIngestionLayer),
@@ -324,6 +332,7 @@ export const makeOrchestrationIntegrationHarness = (
);
const layer = orchestrationReactorLayer.pipe(
Layer.provide(persistenceLayer),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(NodeServices.layer),
);
@@ -358,7 +367,7 @@ export const makeOrchestrationIntegrationHarness = (
const scope = yield* Scope.make("sequential");
yield* tryRuntimePromise("start OrchestrationReactor", () =>
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
runtime.runPromise(reactor.start().pipe(Scope.provide(scope))),
).pipe(Effect.orDie);
const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
@@ -1,5 +1,6 @@
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
import { ThreadId } from "@t3tools/contracts";
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
@@ -12,6 +13,7 @@ import {
ProviderService,
type ProviderServiceShape,
} from "../src/provider/Services/ProviderService.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
@@ -60,6 +62,7 @@ const makeIntegrationFixture = Effect.gen(function* () {
const shared = Layer.mergeAll(
directoryLayer,
Layer.succeed(ProviderAdapterRegistry, registry),
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
AnalyticsService.layerTest,
).pipe(Layer.provide(SqlitePersistenceMemory));
+1 -2
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.14",
"version": "0.0.15",
"license": "MIT",
"repository": {
"type": "git",
@@ -29,7 +29,6 @@
"@pierre/diffs": "^1.1.0-beta.16",
"effect": "catalog:",
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0"
},
"devDependencies": {
+53
View File
@@ -8,10 +8,33 @@ import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import { TestClock } from "effect/testing";
import { vi } from "vitest";
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap";
import { assertNone, assertSome } from "@effect/vitest/utils";
const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null }));
vi.mock("node:fs", async (importOriginal) => {
const actual = await importOriginal<typeof import("node:fs")>();
return {
...actual,
openSync: (...args: Parameters<typeof actual.openSync>) => {
const [filePath, flags] = args;
if (
typeof filePath === "string" &&
filePath === openSyncInterceptor.failPath &&
flags === "r"
) {
const error = new Error("no such device or address");
Object.assign(error, { code: "ENXIO" });
throw error;
}
return (actual.openSync as (...a: typeof args) => number)(...args);
},
};
});
const TestEnvelopeSchema = Schema.Struct({ mode: Schema.String });
it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
@@ -47,6 +70,36 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
}),
);
it.effect("falls back to reading the inherited fd when path duplication fails", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
yield* fs.writeFileString(
filePath,
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
mode: "desktop",
})}\n`,
);
// Open without acquireRelease: the direct-stream fallback uses autoClose: true,
// so the stream owns the fd lifecycle and closes it asynchronously on end.
// Attempting to also close it synchronously in a finalizer races with the
// stream's async close and produces an uncaught EBADF.
const fd = NFS.openSync(filePath, "r");
openSyncInterceptor.failPath = `/proc/self/fd/${fd}`;
try {
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
assertSome(payload, {
mode: "desktop",
});
} finally {
openSyncInterceptor.failPath = null;
}
}),
);
it.effect("returns none when the fd is unavailable", () =>
Effect.gen(function* () {
const fd = NFS.openSync("/dev/null", "r");
+41 -13
View File
@@ -108,21 +108,26 @@ const makeBootstrapInputStream = (fd: number) =>
try: () => {
const fdPath = resolveFdPath(fd);
if (fdPath === undefined) {
const stream = new Net.Socket({
fd,
readable: true,
writable: false,
});
stream.setEncoding("utf8");
return stream;
return makeDirectBootstrapStream(fd);
}
const streamFd = NFS.openSync(fdPath, "r");
return NFS.createReadStream("", {
fd: streamFd,
encoding: "utf8",
autoClose: true,
});
let streamFd: number | undefined;
try {
streamFd = NFS.openSync(fdPath, "r");
return NFS.createReadStream("", {
fd: streamFd,
encoding: "utf8",
autoClose: true,
});
} catch (error) {
if (isBootstrapFdPathDuplicationError(error)) {
if (streamFd !== undefined) {
NFS.closeSync(streamFd);
}
return makeDirectBootstrapStream(fd);
}
throw error;
}
},
catch: (error) =>
new BootstrapError({
@@ -131,6 +136,29 @@ const makeBootstrapInputStream = (fd: number) =>
}),
});
const makeDirectBootstrapStream = (fd: number): Readable => {
try {
return NFS.createReadStream("", {
fd,
encoding: "utf8",
autoClose: true,
});
} catch {
const stream = new Net.Socket({
fd,
readable: true,
writable: false,
});
stream.setEncoding("utf8");
return stream;
}
};
const isBootstrapFdPathDuplicationError = Predicate.compose(
Predicate.hasProperty("code"),
(_) => _.code === "ENXIO" || _.code === "EINVAL" || _.code === "EPERM",
);
export function resolveFdPath(
fd: number,
platform: NodeJS.Platform = process.platform,
@@ -61,6 +61,7 @@ function makeSnapshot(input: {
},
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
archivedAt: null,
deletedAt: null,
messages: [],
activities: [],
@@ -0,0 +1,122 @@
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
import { describe, expect } from "vitest";
import { checkpointRefForThreadTurn } from "../Utils.ts";
import { CheckpointStoreLive } from "./CheckpointStore.ts";
import { CheckpointStore } from "../Services/CheckpointStore.ts";
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { GitCommandError } from "../../git/Errors.ts";
import { ServerConfig } from "../../config.ts";
import { ThreadId } from "@t3tools/contracts";
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-checkpoint-store-test-",
});
const GitCoreTestLayer = GitCoreLive.pipe(
Layer.provide(ServerConfigLayer),
Layer.provide(NodeServices.layer),
);
const CheckpointStoreTestLayer = CheckpointStoreLive.pipe(
Layer.provide(GitCoreTestLayer),
Layer.provide(NodeServices.layer),
);
const TestLayer = Layer.mergeAll(NodeServices.layer, GitCoreTestLayer, CheckpointStoreTestLayer);
function makeTmpDir(
prefix = "checkpoint-store-test-",
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> {
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return yield* fileSystem.makeTempDirectoryScoped({ prefix });
});
}
function writeTextFile(
filePath: string,
contents: string,
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
yield* fileSystem.writeFileString(filePath, contents);
});
}
function git(
cwd: string,
args: ReadonlyArray<string>,
): Effect.Effect<string, GitCommandError, GitCore> {
return Effect.gen(function* () {
const gitCore = yield* GitCore;
const result = yield* gitCore.execute({
operation: "CheckpointStore.test.git",
cwd,
args,
timeoutMs: 10_000,
});
return result.stdout.trim();
});
}
function initRepoWithCommit(
cwd: string,
): Effect.Effect<
void,
GitCommandError | PlatformError.PlatformError,
GitCore | FileSystem.FileSystem
> {
return Effect.gen(function* () {
const core = yield* GitCore;
yield* core.initRepo({ cwd });
yield* git(cwd, ["config", "user.email", "[email protected]"]);
yield* git(cwd, ["config", "user.name", "Test"]);
yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
yield* git(cwd, ["add", "."]);
yield* git(cwd, ["commit", "-m", "initial commit"]);
});
}
function buildLargeText(lineCount = 20_000): string {
return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`)
.join("\n")
.concat("\n");
}
it.layer(TestLayer)("CheckpointStoreLive", (it) => {
describe("diffCheckpoints", () => {
it.effect("returns full oversized checkpoint diffs without truncation", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const checkpointStore = yield* CheckpointStore;
const threadId = ThreadId.makeUnsafe("thread-checkpoint-store");
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
yield* checkpointStore.captureCheckpoint({
cwd: tmp,
checkpointRef: fromCheckpointRef,
});
yield* writeTextFile(path.join(tmp, "README.md"), buildLargeText());
yield* checkpointStore.captureCheckpoint({
cwd: tmp,
checkpointRef: toCheckpointRef,
});
const diff = yield* checkpointStore.diffCheckpoints({
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
});
expect(diff).toContain("diff --git");
expect(diff).not.toContain("[truncated]");
expect(diff).toContain("+line 19999");
}),
);
});
});
+67 -14
View File
@@ -207,6 +207,42 @@ describe("classifyCodexStderrLine", () => {
});
});
describe("process stderr events", () => {
it("emits classified stderr lines as notifications", () => {
const manager = new CodexAppServerManager();
const emitEvent = vi
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
.mockImplementation(() => {});
(
manager as unknown as {
emitNotificationEvent: (
context: { session: { threadId: ThreadId } },
method: string,
message: string,
) => void;
}
).emitNotificationEvent(
{
session: {
threadId: asThreadId("thread-1"),
},
},
"process/stderr",
"fatal: permission denied",
);
expect(emitEvent).toHaveBeenCalledWith(
expect.objectContaining({
kind: "notification",
method: "process/stderr",
threadId: "thread-1",
message: "fatal: permission denied",
}),
);
});
});
describe("normalizeCodexModelSlug", () => {
it("maps 5.3 aliases to gpt-5.3-codex", () => {
expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
@@ -274,7 +310,7 @@ describe("readCodexAccountSnapshot", () => {
});
});
it("keeps spark enabled for api key accounts", () => {
it("disables spark for api key accounts", () => {
expect(
readCodexAccountSnapshot({
type: "apiKey",
@@ -282,7 +318,20 @@ describe("readCodexAccountSnapshot", () => {
).toEqual({
type: "apiKey",
planType: null,
sparkEnabled: true,
sparkEnabled: false,
});
});
it("disables spark for unknown chatgpt plans", () => {
expect(
readCodexAccountSnapshot({
type: "chatgpt",
email: "[email protected]",
}),
).toEqual({
type: "chatgpt",
planType: "unknown",
sparkEnabled: false,
});
});
});
@@ -307,6 +356,16 @@ describe("resolveCodexModelForAccount", () => {
}),
).toBe("gpt-5.3-codex-spark");
});
it("falls back from spark to default for api key auth", () => {
expect(
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
type: "apiKey",
planType: null,
sparkEnabled: false,
}),
).toBe("gpt-5.3-codex");
});
});
describe("startSession", () => {
@@ -342,6 +401,7 @@ describe("startSession", () => {
manager.startSession({
threadId: asThreadId("thread-1"),
provider: "codex",
binaryPath: "codex",
runtimeMode: "full-access",
}),
).rejects.toThrow("cwd missing");
@@ -390,6 +450,7 @@ describe("startSession", () => {
manager.startSession({
threadId: asThreadId("thread-1"),
provider: "codex",
binaryPath: "codex",
runtimeMode: "full-access",
}),
).rejects.toThrow(
@@ -948,12 +1009,8 @@ describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume"
provider: "codex",
cwd: workspaceDir,
runtimeMode: "full-access",
providerOptions: {
codex: {
...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
},
},
binaryPath: process.env.CODEX_BINARY_PATH!,
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
});
const firstTurn = await manager.sendTurn({
@@ -983,12 +1040,8 @@ describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume"
cwd: workspaceDir,
runtimeMode: "approval-required",
resumeCursor: firstSession.resumeCursor,
providerOptions: {
codex: {
...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
},
},
binaryPath: process.env.CODEX_BINARY_PATH!,
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
});
expect(resumedSession.threadId).toBe(originalThreadId);
+37 -124
View File
@@ -14,7 +14,6 @@ import {
type ProviderApprovalDecision,
type ProviderEvent,
type ProviderSession,
type ProviderSessionStartInput,
type ProviderTurnStartResult,
RuntimeMode,
ProviderInteractionMode,
@@ -27,6 +26,16 @@ import {
isCodexCliVersionSupported,
parseCodexCliVersion,
} from "./provider/codexCliVersion";
import {
readCodexAccountSnapshot,
resolveCodexModelForAccount,
type CodexAccountSnapshot,
} from "./provider/codexAccount";
import { buildCodexInitializeParams } from "./provider/codexAppServer";
import { killChildProcessTree } from "./process/killTree";
export { buildCodexInitializeParams } from "./provider/codexAppServer";
export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount";
type PendingRequestKey = string;
@@ -97,23 +106,6 @@ interface JsonRpcNotification {
params?: unknown;
}
type CodexPlanType =
| "free"
| "go"
| "plus"
| "pro"
| "team"
| "business"
| "enterprise"
| "edu"
| "unknown";
interface CodexAccountSnapshot {
readonly type: "apiKey" | "chatgpt" | "unknown";
readonly planType: CodexPlanType | null;
readonly sparkEnabled: boolean;
}
export interface CodexAppServerSendTurnInput {
readonly threadId: ThreadId;
readonly input?: string;
@@ -131,7 +123,8 @@ export interface CodexAppServerStartSessionInput {
readonly model?: string;
readonly serviceTier?: string;
readonly resumeCursor?: unknown;
readonly providerOptions?: ProviderSessionStartInput["providerOptions"];
readonly binaryPath: string;
readonly homePath?: string;
readonly runtimeMode: RuntimeMode;
}
@@ -162,50 +155,6 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
"unknown thread",
"does not exist",
];
const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
const CODEX_SPARK_DISABLED_PLAN_TYPES = new Set<CodexPlanType>(["free", "go", "plus"]);
function asObject(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
return value as Record<string, unknown>;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
const record = asObject(response);
const account = asObject(record?.account) ?? record;
const accountType = asString(account?.type);
if (accountType === "apiKey") {
return {
type: "apiKey",
planType: null,
sparkEnabled: true,
};
}
if (accountType === "chatgpt") {
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
return {
type: "chatgpt",
planType,
sparkEnabled: !CODEX_SPARK_DISABLED_PLAN_TYPES.has(planType),
};
}
return {
type: "unknown",
planType: null,
sparkEnabled: true,
};
}
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
@@ -358,34 +307,6 @@ 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();
}
export function normalizeCodexModelSlug(
model: string | undefined | null,
preferredId?: string,
@@ -402,19 +323,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;
@@ -541,9 +449,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
updatedAt: now,
};
const codexOptions = readCodexProviderOptions(input);
const codexBinaryPath = codexOptions.binaryPath || "codex";
const codexHomePath = codexOptions.homePath;
const codexBinaryPath = input.binaryPath;
const codexHomePath = input.homePath;
this.assertSupportedCodexCliVersion({
binaryPath: codexBinaryPath,
cwd: resolvedCwd,
@@ -993,7 +900,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
context.output.close();
if (!context.child.killed) {
killChildTree(context.child);
killChildProcessTree(context.child);
}
this.updateSession(context, {
@@ -1047,7 +954,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
continue;
}
this.emitErrorEvent(context, "process/stderr", classified.message);
this.emitNotificationEvent(context, "process/stderr", classified.message);
}
});
@@ -1355,6 +1262,22 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
});
}
private emitNotificationEvent(
context: CodexSessionContext,
method: string,
message: string,
): void {
this.emitEvent({
id: EventId.makeUnsafe(randomUUID()),
kind: "notification",
provider: "codex",
threadId: context.session.threadId,
createdAt: new Date().toISOString(),
method,
message,
});
}
private emitEvent(event: ProviderEvent): void {
this.emit("event", event);
}
@@ -1591,20 +1514,6 @@ function normalizeProviderThreadId(value: string | undefined): string | undefine
return brandIfNonEmpty(value, (normalized) => normalized);
}
function readCodexProviderOptions(input: CodexAppServerStartSessionInput): {
readonly binaryPath?: string;
readonly homePath?: string;
} {
const options = input.providerOptions?.codex;
if (!options) {
return {};
}
return {
...(options.binaryPath ? { binaryPath: options.binaryPath } : {}),
...(options.homePath ? { homePath: options.homePath } : {}),
};
}
function assertSupportedCodexCliVersion(input: {
readonly binaryPath: string;
readonly cwd: string;
@@ -1658,7 +1567,11 @@ function readResumeCursorThreadId(resumeCursor: unknown): string | undefined {
return typeof rawThreadId === "string" ? normalizeProviderThreadId(rawThreadId) : undefined;
}
function readResumeThreadId(input: CodexAppServerStartSessionInput): string | undefined {
function readResumeThreadId(input: {
readonly resumeCursor?: unknown;
readonly threadId?: ThreadId;
readonly runtimeMode?: RuntimeMode;
}): string | undefined {
return readResumeCursorThreadId(input.resumeCursor);
}
@@ -5,6 +5,7 @@ import { expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { sanitizeThreadTitle } from "../Utils.ts";
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
@@ -247,4 +248,62 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
}),
),
);
it.effect("generates thread titles through the Claude provider", () =>
withFakeClaudeEnv(
{
output: JSON.stringify({
structured_output: {
title:
' "Reconnect failures after restart because the session state does not recover" ',
},
}),
stdinMustContain: "You write concise thread titles for coding conversations.",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Please investigate reconnect failures after restarting the session.",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
expect(generated.title).toBe(
sanitizeThreadTitle(
'"Reconnect failures after restart because the session state does not recover"',
),
);
}),
),
);
it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>
withFakeClaudeEnv(
{
output: JSON.stringify({
structured_output: {
title: ' """ """ ',
},
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Name this thread.",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
expect(generated.title).toBe("New thread");
}),
),
);
});
@@ -11,7 +11,7 @@ import { Effect, Layer, Option, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { ClaudeModelSelection } from "@t3tools/contracts";
import { normalizeClaudeModelOptions } from "@t3tools/shared/model";
import { resolveApiModelId } from "@t3tools/shared/model";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { TextGenerationError } from "../Errors.ts";
@@ -20,14 +20,18 @@ import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "../Prompts.ts";
import {
normalizeCliError,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
import { ServerSettingsService } from "../../serverSettings.ts";
import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts";
const CLAUDE_TIMEOUT_MS = 180_000;
@@ -69,7 +73,11 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
outputSchemaJson,
modelSelection,
}: {
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
cwd: string;
prompt: string;
outputSchemaJson: S;
@@ -77,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 = {
@@ -103,7 +111,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
"--json-schema",
jsonSchemaStr,
"--model",
modelSelection.model,
resolveApiModelId(modelSelection),
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
"--dangerously-skip-permissions",
@@ -298,10 +306,39 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
};
});
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
"ClaudeTextGeneration.generateThreadTitle",
)(function* (input) {
const { prompt, outputSchema } = buildThreadTitlePrompt({
message: input.message,
attachments: input.attachments,
});
if (input.modelSelection.provider !== "claudeAgent") {
return yield* new TextGenerationError({
operation: "generateThreadTitle",
detail: "Invalid model selection.",
});
}
const generated = yield* runClaudeJson({
operation: "generateThreadTitle",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
title: sanitizeThreadTitle(generated.title),
};
});
return {
generateCommitMessage,
generatePrContent,
generateBranchName,
generateThreadTitle,
} satisfies TextGenerationShape;
});
@@ -24,7 +24,20 @@ const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
Layer.provideMerge(NodeServices.layer),
);
function makeFakeCodexBinary(dir: string) {
function makeFakeCodexBinary(
dir: string,
input: {
output: string;
exitCode?: number;
stderr?: string;
requireImage?: boolean;
requireFastServiceTier?: boolean;
requireReasoningEffort?: string;
forbidReasoningEffort?: boolean;
stdinMustContain?: string;
stdinMustNotContain?: string;
},
) {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -37,12 +50,16 @@ function makeFakeCodexBinary(dir: string) {
[
"#!/bin/sh",
'output_path=""',
'seen_image="0"',
'seen_fast_service_tier="0"',
'seen_reasoning_effort=""',
"while [ $# -gt 0 ]; do",
' if [ "$1" = "--image" ]; then',
" shift",
' if [ -n "$1" ]; then',
' seen_image="1"',
" fi",
" shift",
" continue",
" fi",
' if [ "$1" = "--config" ]; then',
@@ -55,55 +72,80 @@ function makeFakeCodexBinary(dir: string) {
' seen_reasoning_effort="$1"',
" ;;",
" esac",
" shift",
" continue",
" fi",
' if [ "$1" = "--output-last-message" ]; then',
" shift",
' output_path="$1"',
" shift",
" continue",
" fi",
" shift",
"done",
'stdin_content="$(cat)"',
'if [ "$T3_FAKE_CODEX_REQUIRE_IMAGE" = "1" ] && [ "$seen_image" != "1" ]; then',
' printf "%s\\n" "missing --image input" >&2',
" exit 2",
"fi",
'if [ "$T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER" = "1" ] && [ "$seen_fast_service_tier" != "1" ]; then',
' printf "%s\\n" "missing fast service tier config" >&2',
" exit 5",
"fi",
'if [ -n "$T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT" ] && [ "$seen_reasoning_effort" != "model_reasoning_effort=\\"$T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT\\"" ]; then',
' printf "%s\\n" "unexpected reasoning effort config: $seen_reasoning_effort" >&2',
" exit 6",
"fi",
'if [ "$T3_FAKE_CODEX_FORBID_REASONING_EFFORT" = "1" ] && [ -n "$seen_reasoning_effort" ]; then',
' printf "%s\\n" "reasoning effort config should be omitted: $seen_reasoning_effort" >&2',
" exit 7",
"fi",
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" ]; then',
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" >/dev/null || {',
' printf "%s\\n" "stdin missing expected content" >&2',
" exit 3",
" }",
"fi",
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" ]; then',
' if printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" >/dev/null; then',
' printf "%s\\n" "stdin contained forbidden content" >&2',
" exit 4",
" fi",
"fi",
'if [ -n "$T3_FAKE_CODEX_STDERR" ]; then',
' printf "%s\\n" "$T3_FAKE_CODEX_STDERR" >&2',
"fi",
...(input.requireImage
? [
'if [ "$seen_image" != "1" ]; then',
' printf "%s\\n" "missing --image input" >&2',
` exit 2`,
"fi",
]
: []),
...(input.requireFastServiceTier
? [
'if [ "$seen_fast_service_tier" != "1" ]; then',
' printf "%s\\n" "missing fast service tier config" >&2',
` exit 5`,
"fi",
]
: []),
...(input.requireReasoningEffort !== undefined
? [
`if [ "$seen_reasoning_effort" != "model_reasoning_effort=\\"${input.requireReasoningEffort}\\"" ]; then`,
' printf "%s\\n" "unexpected reasoning effort config: $seen_reasoning_effort" >&2',
` exit 6`,
"fi",
]
: []),
...(input.forbidReasoningEffort
? [
'if [ -n "$seen_reasoning_effort" ]; then',
' printf "%s\\n" "reasoning effort config should be omitted: $seen_reasoning_effort" >&2',
` exit 7`,
"fi",
]
: []),
...(input.stdinMustContain !== undefined
? [
`if ! printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustContain)} >/dev/null; then`,
' printf "%s\\n" "stdin missing expected content" >&2',
` exit 3`,
"fi",
]
: []),
...(input.stdinMustNotContain !== undefined
? [
`if printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustNotContain)} >/dev/null; then`,
' printf "%s\\n" "stdin contained forbidden content" >&2',
` exit 4`,
"fi",
]
: []),
...(input.stderr !== undefined
? [`printf "%s\\n" ${JSON.stringify(input.stderr)} >&2`]
: []),
'if [ -n "$output_path" ]; then',
' node -e \'const fs=require("node:fs"); const value=process.argv[2] ?? ""; fs.writeFileSync(process.argv[1], Buffer.from(value, "base64"));\' "$output_path" "${T3_FAKE_CODEX_OUTPUT_B64:-e30=}"',
" cat > \"$output_path\" <<'__T3CODE_FAKE_CODEX_OUTPUT__'",
input.output,
"__T3CODE_FAKE_CODEX_OUTPUT__",
"fi",
'exit "${T3_FAKE_CODEX_EXIT_CODE:-0}"',
`exit ${input.exitCode ?? 0}`,
"",
].join("\n"),
);
yield* fs.chmod(codexPath, 0o755);
return binDir;
return codexPath;
});
}
@@ -125,146 +167,29 @@ function withFakeCodexEnv<A, E, R>(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
const binDir = yield* makeFakeCodexBinary(tempDir);
const previousPath = process.env.PATH;
const previousOutput = process.env.T3_FAKE_CODEX_OUTPUT_B64;
const previousExitCode = process.env.T3_FAKE_CODEX_EXIT_CODE;
const previousStderr = process.env.T3_FAKE_CODEX_STDERR;
const previousRequireImage = process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
const previousRequireFastServiceTier = process.env.T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER;
const previousRequireReasoningEffort = process.env.T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT;
const previousForbidReasoningEffort = process.env.T3_FAKE_CODEX_FORBID_REASONING_EFFORT;
const previousStdinMustContain = process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
const previousStdinMustNotContain = process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
yield* Effect.sync(() => {
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
process.env.T3_FAKE_CODEX_OUTPUT_B64 = Buffer.from(input.output, "utf8").toString("base64");
if (input.exitCode !== undefined) {
process.env.T3_FAKE_CODEX_EXIT_CODE = String(input.exitCode);
} else {
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
}
if (input.stderr !== undefined) {
process.env.T3_FAKE_CODEX_STDERR = input.stderr;
} else {
delete process.env.T3_FAKE_CODEX_STDERR;
}
if (input.requireImage) {
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = "1";
} else {
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
}
if (input.requireFastServiceTier) {
process.env.T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER = "1";
} else {
delete process.env.T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER;
}
if (input.requireReasoningEffort !== undefined) {
process.env.T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT = input.requireReasoningEffort;
} else {
delete process.env.T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT;
}
if (input.forbidReasoningEffort) {
process.env.T3_FAKE_CODEX_FORBID_REASONING_EFFORT = "1";
} else {
delete process.env.T3_FAKE_CODEX_FORBID_REASONING_EFFORT;
}
if (input.stdinMustContain !== undefined) {
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = input.stdinMustContain;
} else {
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
}
if (input.stdinMustNotContain !== undefined) {
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = input.stdinMustNotContain;
} else {
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
}
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
const serverSettings = yield* ServerSettingsService;
const previousSettings = yield* serverSettings.getSettings;
yield* serverSettings.updateSettings({
providers: {
codex: {
binaryPath: codexPath,
},
},
});
return {
previousPath,
previousOutput,
previousExitCode,
previousStderr,
previousRequireImage,
previousRequireFastServiceTier,
previousRequireReasoningEffort,
previousForbidReasoningEffort,
previousStdinMustContain,
previousStdinMustNotContain,
};
return { serverSettings, previousBinaryPath: previousSettings.providers.codex.binaryPath };
}),
() => effect,
(previous) =>
Effect.sync(() => {
process.env.PATH = previous.previousPath;
if (previous.previousOutput === undefined) {
delete process.env.T3_FAKE_CODEX_OUTPUT_B64;
} else {
process.env.T3_FAKE_CODEX_OUTPUT_B64 = previous.previousOutput;
}
if (previous.previousExitCode === undefined) {
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
} else {
process.env.T3_FAKE_CODEX_EXIT_CODE = previous.previousExitCode;
}
if (previous.previousStderr === undefined) {
delete process.env.T3_FAKE_CODEX_STDERR;
} else {
process.env.T3_FAKE_CODEX_STDERR = previous.previousStderr;
}
if (previous.previousRequireImage === undefined) {
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
} else {
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = previous.previousRequireImage;
}
if (previous.previousRequireFastServiceTier === undefined) {
delete process.env.T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER;
} else {
process.env.T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER =
previous.previousRequireFastServiceTier;
}
if (previous.previousRequireReasoningEffort === undefined) {
delete process.env.T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT;
} else {
process.env.T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT =
previous.previousRequireReasoningEffort;
}
if (previous.previousForbidReasoningEffort === undefined) {
delete process.env.T3_FAKE_CODEX_FORBID_REASONING_EFFORT;
} else {
process.env.T3_FAKE_CODEX_FORBID_REASONING_EFFORT =
previous.previousForbidReasoningEffort;
}
if (previous.previousStdinMustContain === undefined) {
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
} else {
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
}
if (previous.previousStdinMustNotContain === undefined) {
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
} else {
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = previous.previousStdinMustNotContain;
}
}),
({ serverSettings, previousBinaryPath }) =>
serverSettings
.updateSettings({
providers: {
codex: {
binaryPath: previousBinaryPath,
},
},
})
.pipe(Effect.asVoid),
);
}
@@ -433,6 +358,70 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
),
);
it.effect("generates thread titles and trims them for sidebar use", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
title:
' "Investigate websocket reconnect regressions after worktree restore" \nignored line',
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Please investigate websocket reconnect regressions after a worktree restore.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.title).toBe("Investigate websocket reconnect regressions aft...");
}),
),
);
it.effect("falls back when thread title normalization becomes whitespace-only", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
title: ' """ """ ',
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Name this thread.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.title).toBe("New thread");
}),
),
);
it.effect("trims whitespace exposed after quote removal in thread titles", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
title: ` "' hello world '" `,
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Name this thread.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.title).toBe("hello world");
}),
),
);
it.effect("omits attachment metadata section when no attachments are provided", () =>
withFakeCodexEnv(
{
@@ -4,7 +4,6 @@ import { Effect, FileSystem, Layer, Option, Path, Schema, Scope, Stream } from "
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { CodexModelSelection } from "@t3tools/contracts";
import { normalizeCodexModelOptions } from "@t3tools/shared/model";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
@@ -12,6 +11,7 @@ import { ServerConfig } from "../../config.ts";
import { TextGenerationError } from "../Errors.ts";
import {
type BranchNameGenerationInput,
type ThreadTitleGenerationResult,
type TextGenerationShape,
TextGeneration,
} from "../Services/TextGeneration.ts";
@@ -19,18 +19,21 @@ import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "../Prompts.ts";
import {
normalizeCliError,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { normalizeCodexModelOptionsWithCapabilities } from "@t3tools/shared/model";
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
const makeCodexTextGeneration = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -83,7 +86,11 @@ const makeCodexTextGeneration = Effect.gen(function* () {
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
const materializeImageAttachments = (
_operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName",
_operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle",
attachments: BranchNameGenerationInput["attachments"],
): Effect.Effect<MaterializedImageAttachments, TextGenerationError> =>
Effect.gen(function* () {
@@ -124,7 +131,11 @@ const makeCodexTextGeneration = Effect.gen(function* () {
cleanupPaths = [],
modelSelection,
}: {
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
cwd: string;
prompt: string;
outputSchemaJson: S;
@@ -146,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 =
@@ -172,7 +183,10 @@ const makeCodexTextGeneration = Effect.gen(function* () {
"-",
],
{
env: codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {},
env: {
...process.env,
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
},
cwd,
shell: process.platform === "win32",
stdin: {
@@ -360,10 +374,44 @@ const makeCodexTextGeneration = Effect.gen(function* () {
};
});
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
"CodexTextGeneration.generateThreadTitle",
)(function* (input) {
const { imagePaths } = yield* materializeImageAttachments(
"generateThreadTitle",
input.attachments,
);
const { prompt, outputSchema } = buildThreadTitlePrompt({
message: input.message,
attachments: input.attachments,
});
if (input.modelSelection.provider !== "codex") {
return yield* new TextGenerationError({
operation: "generateThreadTitle",
detail: "Invalid model selection.",
});
}
const generated = yield* runCodexJson({
operation: "generateThreadTitle",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
imagePaths,
modelSelection: input.modelSelection,
});
return {
title: sanitizeThreadTitle(generated.title),
} satisfies ThreadTitleGenerationResult;
});
return {
generateCommitMessage,
generatePrContent,
generateBranchName,
generateThreadTitle,
} satisfies TextGenerationShape;
});
+125 -8
View File
@@ -132,6 +132,19 @@ function commitWithDate(
});
}
function buildLargeText(lineCount = 20_000): string {
return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`)
.join("\n")
.concat("\n");
}
function splitNullSeparatedPaths(input: string): string[] {
return input
.split("\0")
.map((value) => value.trim())
.filter((value) => value.length > 0);
}
// ── Tests ──
it.layer(TestLayer)("git integration", (it) => {
@@ -175,6 +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", () => {
@@ -415,6 +477,9 @@ it.layer(TestLayer)("git integration", (it) => {
it.effect("refreshes upstream behind count after checkout when remote branch advanced", () =>
Effect.gen(function* () {
const services = yield* Effect.services();
const runPromise = Effect.runPromiseWith(services);
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
const clone = yield* makeTmpDir();
@@ -448,12 +513,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 Effect.runPromise(core.statusDetails(source));
expect(details.branch).toBe(featureBranch);
expect(details.aheadCount).toBe(0);
expect(details.behindCount).toBe(1);
}),
vi.waitFor(
async () => {
const details = await runPromise(core.statusDetails(source));
expect(details.branch).toBe(featureBranch);
expect(details.aheadCount).toBe(0);
expect(details.behindCount).toBe(1);
},
{
timeout: 10_000,
interval: 100,
},
),
);
}),
);
@@ -532,7 +603,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);
});
@@ -585,7 +662,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);
@@ -1667,6 +1750,40 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("prepareCommitContext truncates oversized staged patches instead of failing", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const core = yield* GitCore;
yield* writeTextFile(path.join(tmp, "README.md"), buildLargeText());
const context = yield* core.prepareCommitContext(tmp);
expect(context).not.toBeNull();
expect(context!.stagedSummary).toContain("README.md");
expect(context!.stagedPatch).toContain("[truncated]");
}),
);
it.effect("readRangeContext truncates oversized diff patches instead of failing", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const { initialBranch } = yield* initRepoWithCommit(tmp);
const core = yield* GitCore;
yield* core.createBranch({ cwd: tmp, branch: "feature/large-range-context" });
yield* core.checkoutBranch({ cwd: tmp, branch: "feature/large-range-context" });
yield* writeTextFile(path.join(tmp, "large.txt"), buildLargeText());
yield* git(tmp, ["add", "large.txt"]);
yield* git(tmp, ["commit", "-m", "Add large range context"]);
const rangeContext = yield* core.readRangeContext(tmp, initialBranch);
expect(rangeContext.commitSummary).toContain("Add large range context");
expect(rangeContext.diffSummary).toContain("large.txt");
expect(rangeContext.diffPatch).toContain("[truncated]");
}),
);
it.effect("pushes with upstream setup and then skips when up to date", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
File diff suppressed because it is too large. Load diff
+25 -2
View File
@@ -6,7 +6,7 @@ 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 type { GitActionProgressEvent } from "@t3tools/contracts";
import type { GitActionProgressEvent, ModelSelection } from "@t3tools/contracts";
import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts";
import { type GitManagerShape } from "../Services/GitManager.ts";
@@ -49,6 +49,7 @@ interface FakeGitTextGeneration {
stagedSummary: string;
stagedPatch: string;
includeBranch?: boolean;
modelSelection: ModelSelection;
}) => Effect.Effect<
{ subject: string; body: string; branch?: string | undefined },
TextGenerationError
@@ -60,11 +61,18 @@ interface FakeGitTextGeneration {
commitSummary: string;
diffSummary: string;
diffPatch: string;
modelSelection: ModelSelection;
}) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;
generateBranchName: (input: {
cwd: string;
message: string;
modelSelection: ModelSelection;
}) => Effect.Effect<{ branch: string }, TextGenerationError>;
generateThreadTitle: (input: {
cwd: string;
message: string;
modelSelection: ModelSelection;
}) => Effect.Effect<{ title: string }, TextGenerationError>;
}
type FakePullRequest = NonNullable<FakeGhScenario["pullRequest"]>;
@@ -168,6 +176,10 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): T
Effect.succeed({
branch: "update-workflow",
}),
generateThreadTitle: () =>
Effect.succeed({
title: "Update workflow",
}),
...overrides,
};
@@ -205,6 +217,17 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): T
}),
),
),
generateThreadTitle: (input) =>
implementation.generateThreadTitle(input).pipe(
Effect.mapError(
(cause) =>
new TextGenerationError({
operation: "generateThreadTitle",
detail: "fake text generation failed",
...(cause !== undefined ? { cause } : {}),
}),
),
),
};
}
@@ -502,7 +525,7 @@ function makeManager(input?: {
serverSettingsLayer,
).pipe(Layer.provideMerge(NodeServices.layer));
return makeGitManager.pipe(
return makeGitManager().pipe(
Effect.provide(managerLayer),
Effect.map((manager) => ({ manager, ghCalls })),
);
File diff suppressed because it is too large. Load diff
@@ -47,6 +47,7 @@ const makeRoutingTextGeneration = Effect.gen(function* () {
route(input.modelSelection.provider).generateCommitMessage(input),
generatePrContent: (input) => route(input.modelSelection.provider).generatePrContent(input),
generateBranchName: (input) => route(input.modelSelection.provider).generateBranchName(input),
generateThreadTitle: (input) => route(input.modelSelection.provider).generateThreadTitle(input),
} satisfies TextGenerationShape;
});
+44 -1
View File
@@ -4,8 +4,9 @@ import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "./Prompts.ts";
import { normalizeCliError } from "./Utils.ts";
import { normalizeCliError, sanitizeThreadTitle } from "./Utils.ts";
import { TextGenerationError } from "./Errors.ts";
describe("buildCommitMessagePrompt", () => {
@@ -103,6 +104,48 @@ describe("buildBranchNamePrompt", () => {
});
});
describe("buildThreadTitlePrompt", () => {
it("includes the user message in the prompt", () => {
const result = buildThreadTitlePrompt({
message: "Investigate reconnect regressions after session restore",
});
expect(result.prompt).toContain("User message:");
expect(result.prompt).toContain("Investigate reconnect regressions after session restore");
expect(result.prompt).not.toContain("Attachment metadata:");
});
it("includes attachment metadata when attachments are provided", () => {
const result = buildThreadTitlePrompt({
message: "Name this thread from the screenshot",
attachments: [
{
type: "image" as const,
id: "att-456",
name: "thread.png",
mimeType: "image/png",
sizeBytes: 67890,
},
],
});
expect(result.prompt).toContain("Attachment metadata:");
expect(result.prompt).toContain("thread.png");
expect(result.prompt).toContain("image/png");
expect(result.prompt).toContain("67890 bytes");
});
});
describe("sanitizeThreadTitle", () => {
it("truncates long titles with the shared sidebar-safe limit", () => {
expect(
sanitizeThreadTitle(
' "Reconnect failures after restart because the session state does not recover" ',
),
).toBe("Reconnect failures after restart because the se...");
});
});
describe("normalizeCliError", () => {
it("detects 'Command not found' and includes CLI name in the message", () => {
const error = normalizeCliError(
+57 -8
View File
@@ -119,19 +119,24 @@ export interface BranchNamePromptInput {
attachments?: ReadonlyArray<ChatAttachment> | undefined;
}
export function buildBranchNamePrompt(input: BranchNamePromptInput) {
interface PromptFromMessageInput {
instruction: string;
responseShape: string;
rules: ReadonlyArray<string>;
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
}
function buildPromptFromMessage(input: PromptFromMessageInput): string {
const attachmentLines = (input.attachments ?? []).map(
(attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
);
const promptSections = [
"You generate concise git branch names.",
"Return a JSON object with key: branch.",
input.instruction,
input.responseShape,
"Rules:",
"- Branch should describe the requested work from the user message.",
"- Keep it short and specific (2-6 words).",
"- Use plain words only, no issue prefixes and no punctuation-heavy text.",
"- If images are attached, use them as primary context for visual/UI issues.",
...input.rules.map((rule) => `- ${rule}`),
"",
"User message:",
limitSection(input.message, 8_000),
@@ -144,10 +149,54 @@ export function buildBranchNamePrompt(input: BranchNamePromptInput) {
);
}
const prompt = promptSections.join("\n");
return promptSections.join("\n");
}
export function buildBranchNamePrompt(input: BranchNamePromptInput) {
const prompt = buildPromptFromMessage({
instruction: "You generate concise git branch names.",
responseShape: "Return a JSON object with key: branch.",
rules: [
"Branch should describe the requested work from the user message.",
"Keep it short and specific (2-6 words).",
"Use plain words only, no issue prefixes and no punctuation-heavy text.",
"If images are attached, use them as primary context for visual/UI issues.",
],
message: input.message,
attachments: input.attachments,
});
const outputSchema = Schema.Struct({
branch: Schema.String,
});
return { prompt, outputSchema };
}
// ---------------------------------------------------------------------------
// Thread title
// ---------------------------------------------------------------------------
export interface ThreadTitlePromptInput {
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
}
export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
const prompt = buildPromptFromMessage({
instruction: "You write concise thread titles for coding conversations.",
responseShape: "Return a JSON object with key: title.",
rules: [
"Title should summarize the user's request, not restate it verbatim.",
"Keep it short and specific (3-8 words).",
"Avoid quotes, filler, prefixes, and trailing punctuation.",
"If images are attached, use them as primary context for visual/UI issues.",
],
message: input.message,
attachments: input.attachments,
});
const outputSchema = Schema.Struct({
title: Schema.String,
});
return { prompt, outputSchema };
}
+29
View File
@@ -28,10 +28,12 @@ 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;
readonly maxOutputBytes?: number;
readonly truncateOutputAtMaxBytes?: boolean;
readonly progress?: ExecuteGitProgress;
}
@@ -39,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"> {
@@ -92,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;
@@ -189,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.
*/
@@ -61,12 +61,25 @@ export interface BranchNameGenerationResult {
branch: string;
}
export interface ThreadTitleGenerationInput {
cwd: string;
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
/** What model and provider to use for generation. */
modelSelection: ModelSelection;
}
export interface ThreadTitleGenerationResult {
title: string;
}
export interface TextGenerationService {
generateCommitMessage(
input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult>;
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
generateBranchName(input: BranchNameGenerationInput): Promise<BranchNameGenerationResult>;
generateThreadTitle(input: ThreadTitleGenerationInput): Promise<ThreadTitleGenerationResult>;
}
/**
@@ -93,6 +106,13 @@ export interface TextGenerationShape {
readonly generateBranchName: (
input: BranchNameGenerationInput,
) => Effect.Effect<BranchNameGenerationResult, TextGenerationError>;
/**
* Generate a concise thread title from a user's first message.
*/
readonly generateThreadTitle: (
input: ThreadTitleGenerationInput,
) => Effect.Effect<ThreadTitleGenerationResult, TextGenerationError>;
}
/**
+21
View File
@@ -53,6 +53,27 @@ export function sanitizePrTitle(raw: string): string {
return "Update project changes";
}
/** Normalise a raw thread title to a compact single-line sidebar-safe label. */
export function sanitizeThreadTitle(raw: string): string {
const normalized = raw
.trim()
.split(/\r?\n/g)[0]
?.trim()
.replace(/^['"`]+|['"`]+$/g, "")
.trim()
.replace(/\s+/g, " ");
if (!normalized || normalized.trim().length === 0) {
return "New thread";
}
if (normalized.length <= 50) {
return normalized;
}
return `${normalized.slice(0, 47).trimEnd()}...`;
}
/** CLI name to human-readable label, e.g. "codex" → "Codex CLI (`codex`)" */
function cliLabel(cliName: string): string {
const capitalized = cliName.charAt(0).toUpperCase() + cliName.slice(1);
+2 -2
View File
@@ -4,7 +4,7 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { CliConfig, t3Cli } from "./main";
import { OpenLive } from "./open";
import * as DesktopLauncher from "./process/Layers/DesktopLauncher";
import { Command } from "effect/unstable/cli";
import { version } from "../package.json" with { type: "json" };
import { ServerLive } from "./wsServer";
@@ -14,7 +14,7 @@ import { FetchHttpClient } from "effect/unstable/http";
const RuntimeLayer = Layer.empty.pipe(
Layer.provideMerge(CliConfig.layer),
Layer.provideMerge(ServerLive),
Layer.provideMerge(OpenLive),
Layer.provideMerge(DesktopLauncher.layer),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(FetchHttpClient.layer),
+13
View File
@@ -165,6 +165,19 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
it.effect("ships configurable thread navigation defaults", () =>
Effect.sync(() => {
const defaultsByCommand = new Map(
DEFAULT_KEYBINDINGS.map((binding) => [binding.command, binding.key] as const),
);
assert.equal(defaultsByCommand.get("thread.previous"), "mod+shift+[");
assert.equal(defaultsByCommand.get("thread.next"), "mod+shift+]");
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
}),
);
it.effect("uses defaults in runtime when config is malformed without overriding file", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
+8
View File
@@ -15,6 +15,7 @@ import {
MAX_WHEN_EXPRESSION_DEPTH,
ResolvedKeybindingRule,
ResolvedKeybindingsConfig,
THREAD_JUMP_KEYBINDING_COMMANDS,
type ServerConfigIssue,
} from "@t3tools/contracts";
import { Mutable } from "effect/Types";
@@ -76,6 +77,12 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
{ key: "mod+o", command: "editor.openFavorite" },
{ key: "mod+shift+[", command: "thread.previous" },
{ key: "mod+shift+]", command: "thread.next" },
...THREAD_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
key: `mod+${index + 1}`,
command,
})),
];
function normalizeKeyToken(token: string): string {
@@ -674,6 +681,7 @@ const makeKeybindings = Effect.gen(function* () {
Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })),
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
Effect.flatMap(() => fs.rename(tempPath, keybindingsConfigPath)),
Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))),
Effect.mapError(
(cause) =>
new KeybindingsConfigError({
+27 -16
View File
@@ -6,7 +6,6 @@ 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 Stream from "effect/Stream";
import * as Command from "effect/unstable/cli/Command";
import { FetchHttpClient } from "effect/unstable/http";
import { beforeEach } from "vitest";
@@ -14,15 +13,15 @@ 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 { DesktopLauncher, type DesktopLauncherShape } from "./process/Services/DesktopLauncher";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
import { Server, type ServerShape } from "./wsServer";
import { ServerSettingsService, type ServerSettingsShape } from "./serverSettings";
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* () {
@@ -38,7 +37,7 @@ const findAvailablePort = vi.fn((preferred: number) => Effect.succeed(preferred)
const testLayer = Layer.mergeAll(
Layer.succeed(CliConfig, {
cwd: "/tmp/t3-test-workspace",
fixPath: Effect.void,
fixPath: Effect.sync(fixPath),
resolveStaticDir: Effect.undefined,
} satisfies CliConfigShape),
Layer.succeed(NetService, {
@@ -51,17 +50,13 @@ const testLayer = Layer.mergeAll(
start: serverStart,
stopSignal: Effect.void,
} satisfies ServerShape),
Layer.succeed(Open, {
Layer.succeed(DesktopLauncher, {
getAvailableEditors: Effect.succeed([]),
openExternal: () => Effect.void,
openBrowser: (_target: string) => Effect.void,
openInEditor: () => Effect.void,
} satisfies OpenShape),
Layer.succeed(ServerSettingsService, {
start: Effect.void,
ready: Effect.void,
getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS),
updateSettings: () => Effect.succeed(DEFAULT_SERVER_SETTINGS),
streamChanges: Stream.empty,
} satisfies ServerSettingsShape),
} satisfies DesktopLauncherShape),
ServerSettingsService.layerTest(),
AnalyticsService.layerTest,
FetchHttpClient.layer,
NodeServices.layer,
@@ -89,6 +84,7 @@ beforeEach(() => {
resolvedConfig = null;
start.mockImplementation(() => undefined);
stop.mockImplementation(() => undefined);
fixPath.mockImplementation(() => undefined);
findAvailablePort.mockImplementation((preferred: number) => Effect.succeed(preferred));
});
@@ -337,6 +333,21 @@ it.layer(testLayer)("server CLI command", (it) => {
}),
);
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(
@@ -376,7 +387,7 @@ it.layer(testLayer)("server CLI command", (it) => {
it.effect("does not start server for invalid --mode values", () =>
Effect.gen(function* () {
yield* runCli(["--mode", "invalid"]);
yield* runCli(["--mode", "invalid"]).pipe(Effect.catch(() => Effect.void));
assert.equal(start.mock.calls.length, 0);
assert.equal(stop.mock.calls.length, 0);
@@ -394,7 +405,7 @@ it.layer(testLayer)("server CLI command", (it) => {
it.effect("does not start server for out-of-range --port values", () =>
Effect.gen(function* () {
yield* runCli(["--port", "70000"]);
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);
+13 -8
View File
@@ -18,11 +18,11 @@ import {
type ServerConfigShape,
} from "./config";
import { fixPath, resolveBaseDir } from "./os-jank";
import { Open } from "./open";
import { DesktopLauncher } from "./process/Services/DesktopLauncher";
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
import { ProviderHealthLive } from "./provider/Layers/ProviderHealth";
import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry";
import { Server } from "./wsServer";
import { ServerLoggerLive } from "./serverLogger";
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
@@ -294,7 +294,7 @@ const LayerLive = (input: CliInput) =>
Layer.empty.pipe(
Layer.provideMerge(makeServerRuntimeServicesLayer()),
Layer.provideMerge(makeServerProviderLayer()),
Layer.provideMerge(ProviderHealthLive),
Layer.provideMerge(ProviderRegistryLive),
Layer.provideMerge(SqlitePersistence.layerConfig),
Layer.provideMerge(ServerLoggerLive),
Layer.provideMerge(AnalyticsServiceLayerLive),
@@ -333,12 +333,10 @@ export const recordStartupHeartbeat = Effect.gen(function* () {
});
});
const makeServerProgram = (input: CliInput) =>
const makeServerRuntimeProgram = (input: CliInput) =>
Effect.gen(function* () {
const cliConfig = yield* CliConfig;
const { start, stopSignal } = yield* Server;
const openDeps = yield* Open;
yield* cliConfig.fixPath;
const desktopLauncher = yield* DesktopLauncher;
const config = yield* ServerConfig;
@@ -368,7 +366,7 @@ const makeServerProgram = (input: CliInput) =>
if (!config.noBrowser) {
const target = config.devUrl?.toString() ?? bindUrl;
yield* openDeps.openBrowser(target).pipe(
yield* desktopLauncher.openBrowser(target).pipe(
Effect.catch(() =>
Effect.logInfo("browser auto-open unavailable", {
hint: `Open ${target} in your browser.`,
@@ -380,6 +378,13 @@ const makeServerProgram = (input: CliInput) =>
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.
*/
-232
View File
@@ -1,232 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { assertSuccess } from "@effect/vitest/utils";
import { FileSystem, Path, Effect } from "effect";
import {
isCommandAvailable,
launchDetached,
resolveAvailableEditors,
resolveEditorLaunch,
} from "./open";
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
it.effect("returns commands for command-based editors", () =>
Effect.gen(function* () {
const antigravityLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "antigravity" },
"darwin",
);
assert.deepEqual(antigravityLaunch, {
command: "agy",
args: ["/tmp/workspace"],
});
const cursorLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "cursor" },
"darwin",
);
assert.deepEqual(cursorLaunch, {
command: "cursor",
args: ["/tmp/workspace"],
});
const vscodeLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "vscode" },
"darwin",
);
assert.deepEqual(vscodeLaunch, {
command: "code",
args: ["/tmp/workspace"],
});
const zedLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "zed" },
"darwin",
);
assert.deepEqual(zedLaunch, {
command: "zed",
args: ["/tmp/workspace"],
});
}),
);
it.effect("uses --goto when editor supports line/column suffixes", () =>
Effect.gen(function* () {
const lineOnly = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
"darwin",
);
assert.deepEqual(lineOnly, {
command: "cursor",
args: ["--goto", "/tmp/workspace/AGENTS.md:48"],
});
const lineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
"darwin",
);
assert.deepEqual(lineAndColumn, {
command: "cursor",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const vscodeLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
"darwin",
);
assert.deepEqual(vscodeLineAndColumn, {
command: "code",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const zedLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
"darwin",
);
assert.deepEqual(zedLineAndColumn, {
command: "zed",
args: ["/tmp/workspace/src/open.ts:71:5"],
});
}),
);
it.effect("maps file-manager editor to OS open commands", () =>
Effect.gen(function* () {
const launch1 = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "file-manager" },
"darwin",
);
assert.deepEqual(launch1, {
command: "open",
args: ["/tmp/workspace"],
});
const launch2 = yield* resolveEditorLaunch(
{ cwd: "C:\\workspace", editor: "file-manager" },
"win32",
);
assert.deepEqual(launch2, {
command: "explorer",
args: ["C:\\workspace"],
});
const launch3 = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "file-manager" },
"linux",
);
assert.deepEqual(launch3, {
command: "xdg-open",
args: ["/tmp/workspace"],
});
}),
);
});
it.layer(NodeServices.layer)("launchDetached", (it) => {
it.effect("resolves when command can be spawned", () =>
Effect.gen(function* () {
const result = yield* launchDetached({
command: process.execPath,
args: ["-e", "process.exit(0)"],
}).pipe(Effect.result);
assertSuccess(result, undefined);
}),
);
it.effect("rejects when command does not exist", () =>
Effect.gen(function* () {
const result = yield* launchDetached({
command: `t3code-no-such-command-${Date.now()}`,
args: [],
}).pipe(Effect.result);
assert.equal(result._tag, "Failure");
}),
);
});
it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
it.effect("resolves win32 commands with PATHEXT", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "code.CMD"), "@echo off\r\n");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
}),
);
it("returns false when a command is not on PATH", () => {
const env = {
PATH: "",
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("definitely-not-installed", { platform: "win32", env }), false);
});
it.effect("does not treat bare files without executable extension as available on win32", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "npm"), "echo nope\r\n");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("npm", { platform: "win32", env }), false);
}),
);
it.effect("appends PATHEXT for commands with non-executable extensions on win32", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "my.tool.CMD"), "@echo off\r\n");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("my.tool", { platform: "win32", env }), true);
}),
);
it.effect("uses platform-specific PATH delimiter for platform overrides", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const firstDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
const secondDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(firstDir, "code.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(secondDir, "code.CMD"), "MZ");
const env = {
PATH: `${firstDir};${secondDir}`,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
}),
);
});
it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
it.effect("returns installed editors for command launches", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
yield* fs.writeFileString(path.join(dir, "cursor.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
const editors = resolveAvailableEditors("win32", {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
});
assert.deepEqual(editors, ["cursor", "file-manager"]);
}),
);
});
-276
View File
@@ -1,276 +0,0 @@
/**
* Open - Browser/editor launch service interface.
*
* Owns process launch helpers for opening URLs in a browser and workspace
* paths in a configured editor.
*
* @module Open
*/
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";
// ==============================
// Definitions
// ==============================
export class OpenError extends Schema.TaggedErrorClass<OpenError>()("OpenError", {
message: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {}
export interface OpenInEditorInput {
readonly cwd: string;
readonly editor: EditorId;
}
interface EditorLaunch {
readonly command: string;
readonly args: ReadonlyArray<string>;
}
interface CommandAvailabilityOptions {
readonly platform?: NodeJS.Platform;
readonly env?: NodeJS.ProcessEnv;
}
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {
return (
(editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target)
);
}
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
switch (platform) {
case "darwin":
return "open";
case "win32":
return "explorer";
default:
return "xdg-open";
}
}
function stripWrappingQuotes(value: string): string {
return value.replace(/^"+|"+$/g, "");
}
function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
return env.PATH ?? env.Path ?? env.path ?? "";
}
function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
const rawValue = env.PATHEXT;
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
if (!rawValue) return fallback;
const parsed = rawValue
.split(";")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
}
function resolveCommandCandidates(
command: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): ReadonlyArray<string> {
if (platform !== "win32") return [command];
const extension = extname(command);
const normalizedExtension = extension.toUpperCase();
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
const commandWithoutExtension = command.slice(0, -extension.length);
return Array.from(
new Set([
command,
`${commandWithoutExtension}${normalizedExtension}`,
`${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
]),
);
}
const candidates: string[] = [];
for (const extension of windowsPathExtensions) {
candidates.push(`${command}${extension}`);
candidates.push(`${command}${extension.toLowerCase()}`);
}
return Array.from(new Set(candidates));
}
function isExecutableFile(
filePath: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): boolean {
try {
const stat = statSync(filePath);
if (!stat.isFile()) return false;
if (platform === "win32") {
const extension = extname(filePath);
if (extension.length === 0) return false;
return windowsPathExtensions.includes(extension.toUpperCase());
}
accessSync(filePath, constants.X_OK);
return true;
} catch {
return false;
}
}
function resolvePathDelimiter(platform: NodeJS.Platform): string {
return platform === "win32" ? ";" : ":";
}
export function isCommandAvailable(
command: string,
options: CommandAvailabilityOptions = {},
): boolean {
const platform = options.platform ?? process.platform;
const env = options.env ?? process.env;
const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
if (command.includes("/") || command.includes("\\")) {
return commandCandidates.some((candidate) =>
isExecutableFile(candidate, platform, windowsPathExtensions),
);
}
const pathValue = resolvePathEnvironmentVariable(env);
if (pathValue.length === 0) return false;
const pathEntries = pathValue
.split(resolvePathDelimiter(platform))
.map((entry) => stripWrappingQuotes(entry.trim()))
.filter((entry) => entry.length > 0);
for (const pathEntry of pathEntries) {
for (const candidate of commandCandidates) {
if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
return true;
}
}
}
return false;
}
export function resolveAvailableEditors(
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): ReadonlyArray<EditorId> {
const available: EditorId[] = [];
for (const editor of EDITORS) {
const command = editor.command ?? fileManagerCommandForPlatform(platform);
if (isCommandAvailable(command, { platform, env })) {
available.push(editor.id);
}
}
return available;
}
/**
* OpenShape - Service API for browser and editor launch actions.
*/
export interface OpenShape {
/**
* Open a URL target in the default browser.
*/
readonly openBrowser: (target: string) => Effect.Effect<void, OpenError>;
/**
* Open a workspace path in a selected editor integration.
*
* Launches the editor as a detached process so server startup is not blocked.
*/
readonly openInEditor: (input: OpenInEditorInput) => Effect.Effect<void, OpenError>;
}
/**
* Open - Service tag for browser/editor launch operations.
*/
export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
// ==============================
// Implementations
// ==============================
export const resolveEditorLaunch = Effect.fnUntraced(function* (
input: OpenInEditorInput,
platform: NodeJS.Platform = process.platform,
): Effect.fn.Return<EditorLaunch, OpenError> {
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
if (!editorDef) {
return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
}
if (editorDef.command) {
return shouldUseGotoFlag(editorDef.id, input.cwd)
? { command: editorDef.command, args: ["--goto", input.cwd] }
: { command: editorDef.command, args: [input.cwd] };
}
if (editorDef.id !== "file-manager") {
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
}
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
});
export const launchDetached = (launch: EditorLaunch) =>
Effect.gen(function* () {
if (!isCommandAvailable(launch.command)) {
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
}
yield* Effect.callback<void, OpenError>((resume) => {
let child;
try {
child = spawn(launch.command, [...launch.args], {
detached: true,
stdio: "ignore",
shell: process.platform === "win32",
});
} catch (error) {
return resume(
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
);
}
const handleSpawn = () => {
child.unref();
resume(Effect.void);
};
child.once("spawn", handleSpawn);
child.once("error", (cause) =>
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
);
});
});
const make = Effect.gen(function* () {
const open = yield* Effect.tryPromise({
try: () => import("open"),
catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
});
return {
openBrowser: (target) =>
Effect.tryPromise({
try: () => open.default(target),
catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
}),
openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
} satisfies OpenShape;
});
export const OpenLive = Layer.effect(Open, make);
@@ -38,6 +38,7 @@ import {
} from "../../provider/Services/ProviderService.ts";
import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
import { ServerConfig } from "../../config.ts";
import { WorkspaceEntriesLive } from "../../workspace/Layers/WorkspaceEntries.ts";
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
@@ -261,7 +262,9 @@ 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),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(NodeServices.layer),
);
@@ -271,7 +274,7 @@ describe("CheckpointReactor", () => {
const reactor = await runtime.runPromise(Effect.service(CheckpointReactor));
const checkpointStore = await runtime.runPromise(Effect.service(CheckpointStore));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reactor.start.pipe(Scope.provide(scope)));
await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
const drain = () => Effect.runPromise(reactor.drain);
const createdAt = new Date().toISOString();
@@ -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) {
@@ -766,7 +767,7 @@ const make = Effect.gen(function* () {
const worker = yield* makeDrainableWorker(processInputSafely);
const start: CheckpointReactorShape["start"] = Effect.gen(function* () {
const start: CheckpointReactorShape["start"] = Effect.fn("start")(function* () {
yield* Effect.forkScoped(
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
if (
@@ -120,6 +120,73 @@ describe("OrchestrationEngine", () => {
await system.dispose();
});
it("archives and unarchives threads through orchestration commands", async () => {
const system = await createOrchestrationSystem();
const { engine } = system;
const createdAt = now();
await system.run(
engine.dispatch({
type: "project.create",
commandId: CommandId.makeUnsafe("cmd-project-archive-create"),
projectId: asProjectId("project-archive"),
title: "Project Archive",
workspaceRoot: "/tmp/project-archive",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
}),
);
await system.run(
engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-archive-create"),
threadId: ThreadId.makeUnsafe("thread-archive"),
projectId: asProjectId("project-archive"),
title: "Archive me",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt,
}),
);
await system.run(
engine.dispatch({
type: "thread.archive",
commandId: CommandId.makeUnsafe("cmd-thread-archive"),
threadId: ThreadId.makeUnsafe("thread-archive"),
}),
);
expect(
(await system.run(engine.getReadModel())).threads.find(
(thread) => thread.id === "thread-archive",
)?.archivedAt,
).not.toBeNull();
await system.run(
engine.dispatch({
type: "thread.unarchive",
commandId: CommandId.makeUnsafe("cmd-thread-unarchive"),
threadId: ThreadId.makeUnsafe("thread-archive"),
}),
);
expect(
(await system.run(engine.getReadModel())).threads.find(
(thread) => thread.id === "thread-archive",
)?.archivedAt,
).toBeNull();
await system.dispose();
});
it("replays append-only events from sequence", async () => {
const system = await createOrchestrationSystem();
const { engine } = system;
@@ -24,25 +24,28 @@ describe("OrchestrationReactor", () => {
Layer.effect(OrchestrationReactor, makeOrchestrationReactor).pipe(
Layer.provideMerge(
Layer.succeed(ProviderRuntimeIngestionService, {
start: Effect.sync(() => {
start: () => {
started.push("provider-runtime-ingestion");
}),
return Effect.void;
},
drain: Effect.void,
}),
),
Layer.provideMerge(
Layer.succeed(ProviderCommandReactor, {
start: Effect.sync(() => {
start: () => {
started.push("provider-command-reactor");
}),
return Effect.void;
},
drain: Effect.void,
}),
),
Layer.provideMerge(
Layer.succeed(CheckpointReactor, {
start: Effect.sync(() => {
start: () => {
started.push("checkpoint-reactor");
}),
return Effect.void;
},
drain: Effect.void,
}),
),
@@ -51,7 +54,7 @@ describe("OrchestrationReactor", () => {
const reactor = await runtime.runPromise(Effect.service(OrchestrationReactor));
const scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reactor.start.pipe(Scope.provide(scope)));
await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
expect(started).toEqual([
"provider-runtime-ingestion",
@@ -13,10 +13,10 @@ export const makeOrchestrationReactor = Effect.gen(function* () {
const providerCommandReactor = yield* ProviderCommandReactor;
const checkpointReactor = yield* CheckpointReactor;
const start: OrchestrationReactorShape["start"] = Effect.gen(function* () {
yield* providerRuntimeIngestion.start;
yield* providerCommandReactor.start;
yield* checkpointReactor.start;
const start: OrchestrationReactorShape["start"] = Effect.fn("start")(function* () {
yield* providerRuntimeIngestion.start();
yield* providerCommandReactor.start();
yield* checkpointReactor.start();
});
return {
@@ -77,7 +77,7 @@ interface AttachmentSideEffects {
readonly prunedThreadRelativePaths: Map<string, Set<string>>;
}
const materializeAttachmentsForProjection = Effect.fn(
const materializeAttachmentsForProjection = Effect.fn("materializeAttachmentsForProjection")(
(input: { readonly attachments: ReadonlyArray<ChatAttachment> }) =>
Effect.succeed(input.attachments.length === 0 ? [] : input.attachments),
);
@@ -238,124 +238,145 @@ function collectThreadAttachmentRelativePaths(
return relativePaths;
}
const runAttachmentSideEffects = Effect.fn(function* (sideEffects: AttachmentSideEffects) {
const runAttachmentSideEffects = Effect.fn("runAttachmentSideEffects")(function* (
sideEffects: AttachmentSideEffects,
) {
const serverConfig = yield* Effect.service(ServerConfig);
const fileSystem = yield* Effect.service(FileSystem.FileSystem);
const path = yield* Effect.service(Path.Path);
const attachmentsRootDir = serverConfig.attachmentsDir;
const readAttachmentRootEntries = fileSystem
.readDirectory(attachmentsRootDir, { recursive: false })
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
yield* Effect.forEach(
sideEffects.deletedThreadIds,
(threadId) =>
Effect.gen(function* () {
const threadSegment = toSafeThreadAttachmentSegment(threadId);
if (!threadSegment) {
yield* Effect.logWarning("skipping attachment cleanup for unsafe thread id", {
threadId,
});
return;
}
const entries = yield* fileSystem
.readDirectory(attachmentsRootDir, { recursive: false })
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
yield* Effect.forEach(
entries,
(entry) =>
Effect.gen(function* () {
const normalizedEntry = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
if (normalizedEntry.length === 0 || normalizedEntry.includes("/")) {
return;
}
const attachmentId = parseAttachmentIdFromRelativePath(normalizedEntry);
if (!attachmentId) {
return;
}
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
return;
}
yield* fileSystem.remove(path.join(attachmentsRootDir, normalizedEntry), {
force: true,
});
}),
{ concurrency: 1 },
);
}),
{ concurrency: 1 },
const removeDeletedThreadAttachmentEntry = Effect.fn("removeDeletedThreadAttachmentEntry")(
function* (threadSegment: string, entry: string) {
const normalizedEntry = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
if (normalizedEntry.length === 0 || normalizedEntry.includes("/")) {
return;
}
const attachmentId = parseAttachmentIdFromRelativePath(normalizedEntry);
if (!attachmentId) {
return;
}
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
return;
}
yield* fileSystem.remove(path.join(attachmentsRootDir, normalizedEntry), {
force: true,
});
},
);
const deleteThreadAttachments = Effect.fn("deleteThreadAttachments")(function* (
threadId: string,
) {
const threadSegment = toSafeThreadAttachmentSegment(threadId);
if (!threadSegment) {
yield* Effect.logWarning("skipping attachment cleanup for unsafe thread id", {
threadId,
});
return;
}
const entries = yield* readAttachmentRootEntries;
yield* Effect.forEach(
entries,
(entry) => removeDeletedThreadAttachmentEntry(threadSegment, entry),
{
concurrency: 1,
},
);
});
const pruneThreadAttachmentEntry = Effect.fn("pruneThreadAttachmentEntry")(function* (
threadSegment: string,
keptThreadRelativePaths: Set<string>,
entry: string,
) {
const relativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
if (relativePath.length === 0 || relativePath.includes("/")) {
return;
}
const attachmentId = parseAttachmentIdFromRelativePath(relativePath);
if (!attachmentId) {
return;
}
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
return;
}
const absolutePath = path.join(attachmentsRootDir, relativePath);
const fileInfo = yield* fileSystem
.stat(absolutePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
return;
}
if (!keptThreadRelativePaths.has(relativePath)) {
yield* fileSystem.remove(absolutePath, { force: true });
}
});
const pruneThreadAttachments = Effect.fn("pruneThreadAttachments")(function* (
threadId: string,
keptThreadRelativePaths: Set<string>,
) {
if (sideEffects.deletedThreadIds.has(threadId)) {
return;
}
const threadSegment = toSafeThreadAttachmentSegment(threadId);
if (!threadSegment) {
yield* Effect.logWarning("skipping attachment prune for unsafe thread id", { threadId });
return;
}
const entries = yield* readAttachmentRootEntries;
yield* Effect.forEach(
entries,
(entry) => pruneThreadAttachmentEntry(threadSegment, keptThreadRelativePaths, entry),
{ concurrency: 1 },
);
});
yield* Effect.forEach(sideEffects.deletedThreadIds, deleteThreadAttachments, {
concurrency: 1,
});
yield* Effect.forEach(
sideEffects.prunedThreadRelativePaths.entries(),
([threadId, keptThreadRelativePaths]) => {
if (sideEffects.deletedThreadIds.has(threadId)) {
return Effect.void;
}
return Effect.gen(function* () {
const threadSegment = toSafeThreadAttachmentSegment(threadId);
if (!threadSegment) {
yield* Effect.logWarning("skipping attachment prune for unsafe thread id", { threadId });
return;
}
const entries = yield* fileSystem
.readDirectory(attachmentsRootDir, { recursive: false })
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
yield* Effect.forEach(
entries,
(entry) =>
Effect.gen(function* () {
const relativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
if (relativePath.length === 0 || relativePath.includes("/")) {
return;
}
const attachmentId = parseAttachmentIdFromRelativePath(relativePath);
if (!attachmentId) {
return;
}
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
return;
}
const absolutePath = path.join(attachmentsRootDir, relativePath);
const fileInfo = yield* fileSystem
.stat(absolutePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
return;
}
if (!keptThreadRelativePaths.has(relativePath)) {
yield* fileSystem.remove(absolutePath, { force: true });
}
}),
{ concurrency: 1 },
);
});
},
([threadId, keptThreadRelativePaths]) =>
pruneThreadAttachments(threadId, keptThreadRelativePaths),
{ concurrency: 1 },
);
});
const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const eventStore = yield* OrchestrationEventStore;
const projectionStateRepository = yield* ProjectionStateRepository;
const projectionProjectRepository = yield* ProjectionProjectRepository;
const projectionThreadRepository = yield* ProjectionThreadRepository;
const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository;
const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository;
const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository;
const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectionPipeline")(
function* () {
const sql = yield* SqlClient.SqlClient;
const eventStore = yield* OrchestrationEventStore;
const projectionStateRepository = yield* ProjectionStateRepository;
const projectionProjectRepository = yield* ProjectionProjectRepository;
const projectionThreadRepository = yield* ProjectionThreadRepository;
const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository;
const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository;
const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository;
const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const applyProjectsProjection: ProjectorDefinition["apply"] = (event, _attachmentSideEffects) =>
Effect.gen(function* () {
const applyProjectsProjection: ProjectorDefinition["apply"] = Effect.fn(
"applyProjectsProjection",
)(function* (event, _attachmentSideEffects) {
switch (event.type) {
case "project.created":
yield* projectionProjectRepository.upsert({
@@ -412,8 +433,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
}
});
const applyThreadsProjection: ProjectorDefinition["apply"] = (event, attachmentSideEffects) =>
Effect.gen(function* () {
const applyThreadsProjection: ProjectorDefinition["apply"] = Effect.fn(
"applyThreadsProjection",
)(function* (event, attachmentSideEffects) {
switch (event.type) {
case "thread.created":
yield* projectionThreadRepository.upsert({
@@ -428,10 +450,41 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
latestTurnId: null,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
archivedAt: null,
deletedAt: null,
});
return;
case "thread.archived": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
archivedAt: event.payload.archivedAt,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.unarchived": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
archivedAt: null,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.meta-updated": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
@@ -566,11 +619,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
}
});
const applyThreadMessagesProjection: ProjectorDefinition["apply"] = (
event,
attachmentSideEffects,
) =>
Effect.gen(function* () {
const applyThreadMessagesProjection: ProjectorDefinition["apply"] = Effect.fn(
"applyThreadMessagesProjection",
)(function* (event, attachmentSideEffects) {
switch (event.type) {
case "thread.message-sent": {
const existingRows = yield* projectionThreadMessageRepository.listByThreadId({
@@ -643,11 +694,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
}
});
const applyThreadProposedPlansProjection: ProjectorDefinition["apply"] = (
event,
_attachmentSideEffects,
) =>
Effect.gen(function* () {
const applyThreadProposedPlansProjection: ProjectorDefinition["apply"] = Effect.fn(
"applyThreadProposedPlansProjection",
)(function* (event, _attachmentSideEffects) {
switch (event.type) {
case "thread.proposed-plan-upserted":
yield* projectionThreadProposedPlanRepository.upsert({
@@ -696,11 +745,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
}
});
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = (
event,
_attachmentSideEffects,
) =>
Effect.gen(function* () {
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = Effect.fn(
"applyThreadActivitiesProjection",
)(function* (event, _attachmentSideEffects) {
switch (event.type) {
case "thread.activity-appended":
yield* projectionThreadActivityRepository.upsert({
@@ -750,11 +797,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
}
});
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (
event,
_attachmentSideEffects,
) =>
Effect.gen(function* () {
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = Effect.fn(
"applyThreadSessionsProjection",
)(function* (event, _attachmentSideEffects) {
if (event.type !== "thread.session-set") {
return;
}
@@ -769,11 +814,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
});
});
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = (
event,
_attachmentSideEffects,
) =>
Effect.gen(function* () {
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = Effect.fn(
"applyThreadTurnsProjection",
)(function* (event, _attachmentSideEffects) {
switch (event.type) {
case "thread.turn-start-requested": {
yield* projectionTurnRepository.replacePendingTurnStart({
@@ -1027,13 +1070,11 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
}
});
const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void;
const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void;
const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = (
event,
_attachmentSideEffects,
) =>
Effect.gen(function* () {
const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = Effect.fn(
"applyPendingApprovalsProjection",
)(function* (event, _attachmentSideEffects) {
switch (event.type) {
case "thread.activity-appended": {
const requestId =
@@ -1119,47 +1160,49 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
}
});
const projectors: ReadonlyArray<ProjectorDefinition> = [
{
name: ORCHESTRATION_PROJECTOR_NAMES.projects,
apply: applyProjectsProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
apply: applyThreadMessagesProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,
apply: applyThreadProposedPlansProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
apply: applyThreadActivitiesProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
apply: applyThreadSessionsProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.threadTurns,
apply: applyThreadTurnsProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.checkpoints,
apply: applyCheckpointsProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.pendingApprovals,
apply: applyPendingApprovalsProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.threads,
apply: applyThreadsProjection,
},
];
const projectors: ReadonlyArray<ProjectorDefinition> = [
{
name: ORCHESTRATION_PROJECTOR_NAMES.projects,
apply: applyProjectsProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
apply: applyThreadMessagesProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,
apply: applyThreadProposedPlansProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
apply: applyThreadActivitiesProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
apply: applyThreadSessionsProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.threadTurns,
apply: applyThreadTurnsProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.checkpoints,
apply: applyCheckpointsProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.pendingApprovals,
apply: applyPendingApprovalsProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.threads,
apply: applyThreadsProjection,
},
];
const runProjectorForEvent = (projector: ProjectorDefinition, event: OrchestrationEvent) =>
Effect.gen(function* () {
const runProjectorForEvent = Effect.fn("runProjectorForEvent")(function* (
projector: ProjectorDefinition,
event: OrchestrationEvent,
) {
const attachmentSideEffects: AttachmentSideEffects = {
deletedThreadIds: new Set<string>(),
prunedThreadRelativePaths: new Map<string, Set<string>>(),
@@ -1189,63 +1232,64 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
);
});
const bootstrapProjector = (projector: ProjectorDefinition) =>
projectionStateRepository
.getByProjector({
projector: projector.name,
})
.pipe(
Effect.flatMap((stateRow) =>
Stream.runForEach(
eventStore.readFromSequence(
Option.isSome(stateRow) ? stateRow.value.lastAppliedSequence : 0,
const bootstrapProjector = (projector: ProjectorDefinition) =>
projectionStateRepository
.getByProjector({
projector: projector.name,
})
.pipe(
Effect.flatMap((stateRow) =>
Stream.runForEach(
eventStore.readFromSequence(
Option.isSome(stateRow) ? stateRow.value.lastAppliedSequence : 0,
),
(event) => runProjectorForEvent(projector, event),
),
(event) => runProjectorForEvent(projector, event),
),
);
const projectEvent: OrchestrationProjectionPipelineShape["projectEvent"] = (event) =>
Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), {
concurrency: 1,
}).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
Effect.provideService(ServerConfig, serverConfig),
Effect.asVoid,
Effect.catchTag("SqlError", (sqlError) =>
Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)),
),
);
const projectEvent: OrchestrationProjectionPipelineShape["projectEvent"] = (event) =>
Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), {
concurrency: 1,
}).pipe(
const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.forEach(
projectors,
bootstrapProjector,
{ concurrency: 1 },
).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
Effect.provideService(ServerConfig, serverConfig),
Effect.asVoid,
Effect.tap(() =>
Effect.log("orchestration projection pipeline bootstrapped").pipe(
Effect.annotateLogs({ projectors: projectors.length }),
),
),
Effect.catchTag("SqlError", (sqlError) =>
Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)),
Effect.fail(toPersistenceSqlError("ProjectionPipeline.bootstrap:query")(sqlError)),
),
);
const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.forEach(
projectors,
bootstrapProjector,
{ concurrency: 1 },
).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
Effect.provideService(ServerConfig, serverConfig),
Effect.asVoid,
Effect.tap(() =>
Effect.log("orchestration projection pipeline bootstrapped").pipe(
Effect.annotateLogs({ projectors: projectors.length }),
),
),
Effect.catchTag("SqlError", (sqlError) =>
Effect.fail(toPersistenceSqlError("ProjectionPipeline.bootstrap:query")(sqlError)),
),
);
return {
bootstrap,
projectEvent,
} satisfies OrchestrationProjectionPipelineShape;
});
return {
bootstrap,
projectEvent,
} satisfies OrchestrationProjectionPipelineShape;
},
);
export const OrchestrationProjectionPipelineLive = Layer.effect(
OrchestrationProjectionPipeline,
makeOrchestrationProjectionPipeline,
makeOrchestrationProjectionPipeline(),
).pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ProjectionProjectRepositoryLive),
@@ -279,6 +279,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
},
createdAt: "2026-02-24T00:00:02.000Z",
updatedAt: "2026-02-24T00:00:03.000Z",
archivedAt: null,
deletedAt: null,
messages: [
{
@@ -174,6 +174,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
latest_turn_id AS "latestTurnId",
created_at AS "createdAt",
updated_at AS "updatedAt",
archived_at AS "archivedAt",
deleted_at AS "deletedAt"
FROM projection_threads
ORDER BY created_at ASC, thread_id ASC
@@ -560,6 +561,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
@@ -176,7 +176,7 @@ describe("ProviderCommandReactor", () => {
: "renamed-branch",
}),
);
const generateBranchName = vi.fn(() =>
const generateBranchName = vi.fn<TextGenerationShape["generateBranchName"]>((_) =>
Effect.fail(
new TextGenerationError({
operation: "generateBranchName",
@@ -184,6 +184,14 @@ describe("ProviderCommandReactor", () => {
}),
),
);
const generateThreadTitle = vi.fn<TextGenerationShape["generateThreadTitle"]>((_) =>
Effect.fail(
new TextGenerationError({
operation: "generateThreadTitle",
detail: "disabled in test harness",
}),
),
);
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
const service: ProviderServiceShape = {
@@ -213,7 +221,10 @@ describe("ProviderCommandReactor", () => {
Layer.provideMerge(Layer.succeed(ProviderService, service)),
Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)),
Layer.provideMerge(
Layer.succeed(TextGeneration, { generateBranchName } as unknown as TextGenerationShape),
Layer.mock(TextGeneration, {
generateBranchName,
generateThreadTitle,
}),
),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
@@ -224,7 +235,7 @@ describe("ProviderCommandReactor", () => {
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reactor.start.pipe(Scope.provide(scope)));
await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
const drain = () => Effect.runPromise(reactor.drain);
await Effect.runPromise(
@@ -264,6 +275,7 @@ describe("ProviderCommandReactor", () => {
stopSession,
renameBranch,
generateBranchName,
generateThreadTitle,
stateDir,
drain,
};
@@ -308,6 +320,199 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
it("generates a thread title on the first turn", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
const seededTitle = "Please investigate reconnect failures after restar...";
harness.generateThreadTitle.mockReturnValue(Effect.succeed({ title: "Generated title" }));
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe("cmd-thread-title-seed"),
threadId: ThreadId.makeUnsafe("thread-1"),
title: seededTitle,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-title"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-title"),
role: "user",
text: "Please investigate reconnect failures after restarting the session.",
attachments: [],
},
titleSeed: seededTitle,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1);
expect(harness.generateThreadTitle.mock.calls[0]?.[0]).toMatchObject({
message: "Please investigate reconnect failures after restarting the session.",
});
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
return (
readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"))?.title ===
"Generated title"
);
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.title).toBe("Generated title");
});
it("does not overwrite an existing custom thread title on the first turn", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
const seededTitle = "Please investigate reconnect failures after restar...";
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe("cmd-thread-title-custom"),
threadId: ThreadId.makeUnsafe("thread-1"),
title: "Keep this custom title",
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-title-preserve"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-title-preserve"),
role: "user",
text: "Please investigate reconnect failures after restarting the session.",
attachments: [],
},
titleSeed: seededTitle,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.generateThreadTitle).not.toHaveBeenCalled();
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.title).toBe("Keep this custom title");
});
it("matches the client-seeded title even when the outgoing prompt is reformatted", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
const seededTitle = "Fix reconnect spinner on resume";
harness.generateThreadTitle.mockReturnValue(
Effect.succeed({
title: "Reconnect spinner resume bug",
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe("cmd-thread-title-formatted-seed"),
threadId: ThreadId.makeUnsafe("thread-1"),
title: seededTitle,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-title-formatted"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-title-formatted"),
role: "user",
text: "[effort:high]\\n\\nFix reconnect spinner on resume",
attachments: [],
},
titleSeed: seededTitle,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
return (
readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"))?.title ===
"Reconnect spinner resume bug"
);
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.title).toBe("Reconnect spinner resume bug");
});
it("generates a worktree branch name for the first turn", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe("cmd-thread-branch"),
threadId: ThreadId.makeUnsafe("thread-1"),
branch: "t3code/1234abcd",
worktreePath: "/tmp/provider-project-worktree",
}),
);
harness.generateBranchName.mockImplementation((input: unknown) =>
Effect.succeed({
branch:
typeof input === "object" &&
input !== null &&
"modelSelection" in input &&
typeof input.modelSelection === "object" &&
input.modelSelection !== null &&
"model" in input.modelSelection &&
typeof input.modelSelection.model === "string"
? `feature/${input.modelSelection.model}`
: "feature/generated",
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-branch-model"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-branch-model"),
role: "user",
text: "Add a safer reconnect backoff.",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
expect(harness.generateBranchName.mock.calls[0]?.[0]).toMatchObject({
message: "Add a safer reconnect backoff.",
});
});
it("forwards codex model options through session start and turn send", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -24,7 +24,7 @@ import {
ProviderCommandReactor,
type ProviderCommandReactorShape,
} from "../Services/ProviderCommandReactor.ts";
import { ServerSettingsService, deriveProviderStartOptions } from "../../serverSettings.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
type ProviderIntentEvent = Extract<
OrchestrationEvent,
@@ -73,6 +73,19 @@ const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
const WORKTREE_BRANCH_PREFIX = "t3code";
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
const DEFAULT_THREAD_TITLE = "New thread";
function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolean {
const trimmedCurrentTitle = currentTitle.trim();
if (trimmedCurrentTitle === DEFAULT_THREAD_TITLE) {
return true;
}
const trimmedTitleSeed = titleSeed?.trim();
return trimmedTitleSeed !== undefined && trimmedTitleSeed.length > 0
? trimmedCurrentTitle === trimmedTitleSeed
: false;
}
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = Cause.squash(cause);
@@ -251,18 +264,13 @@ const make = Effect.gen(function* () {
readonly resumeCursor?: unknown;
readonly provider?: ProviderKind;
}) =>
Effect.gen(function* () {
const serverSettings = yield* serverSettingsService.getSettings;
const providerOptions = deriveProviderStartOptions(serverSettings);
return yield* providerService.startSession(threadId, {
threadId,
...(preferredProvider ? { provider: preferredProvider } : {}),
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
modelSelection: desiredModelSelection,
...(providerOptions !== undefined ? { providerOptions } : {}),
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
runtimeMode: desiredRuntimeMode,
});
providerService.startSession(threadId, {
threadId,
...(preferredProvider ? { provider: preferredProvider } : {}),
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
modelSelection: desiredModelSelection,
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
runtimeMode: desiredRuntimeMode,
});
const bindSessionToThread = (session: ProviderSession) =>
@@ -405,7 +413,6 @@ const make = Effect.gen(function* () {
readonly threadId: ThreadId;
readonly branch: string | null;
readonly worktreePath: string | null;
readonly messageId: string;
readonly messageText: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
}) {
@@ -416,61 +423,85 @@ const make = Effect.gen(function* () {
return;
}
const thread = yield* resolveThread(input.threadId);
if (!thread) {
return;
}
const userMessages = thread.messages.filter((message) => message.role === "user");
if (userMessages.length !== 1 || userMessages[0]?.id !== input.messageId) {
return;
}
const oldBranch = input.branch;
const cwd = input.worktreePath;
const attachments = input.attachments ?? [];
yield* textGeneration
.generateBranchName({
yield* Effect.gen(function* () {
const { textGenerationModelSelection: modelSelection } =
yield* serverSettingsService.getSettings;
const generated = yield* textGeneration.generateBranchName({
cwd,
message: input.messageText,
...(attachments.length > 0 ? { attachments } : {}),
modelSelection: yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.textGenerationModelSelection,
),
})
.pipe(
Effect.catch((error) =>
Effect.logWarning(
"provider command reactor failed to generate worktree branch name; skipping rename",
{ threadId: input.threadId, cwd, oldBranch, reason: error.message },
),
),
Effect.flatMap((generated) => {
if (!generated) return Effect.void;
modelSelection,
});
if (!generated) return;
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
if (targetBranch === oldBranch) return Effect.void;
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
if (targetBranch === oldBranch) return;
return Effect.flatMap(
git.renameBranch({ cwd, oldBranch, newBranch: targetBranch }),
(renamed) =>
orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: serverCommandId("worktree-branch-rename"),
threadId: input.threadId,
branch: renamed.branch,
worktreePath: cwd,
}),
);
const renamed = yield* git.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: serverCommandId("worktree-branch-rename"),
threadId: input.threadId,
branch: renamed.branch,
worktreePath: cwd,
});
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("provider command reactor failed to generate or rename worktree branch", {
threadId: input.threadId,
cwd,
oldBranch,
cause: Cause.pretty(cause),
}),
Effect.catchCause((cause) =>
Effect.logWarning(
"provider command reactor failed to generate or rename worktree branch",
{ threadId: input.threadId, cwd, oldBranch, cause: Cause.pretty(cause) },
),
),
);
),
);
});
const maybeGenerateThreadTitleForFirstTurn = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly cwd: string;
readonly messageText: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly titleSeed?: string;
}) {
const attachments = input.attachments ?? [];
yield* Effect.gen(function* () {
const { textGenerationModelSelection: modelSelection } =
yield* serverSettingsService.getSettings;
const generated = yield* textGeneration.generateThreadTitle({
cwd: input.cwd,
message: input.messageText,
...(attachments.length > 0 ? { attachments } : {}),
modelSelection,
});
if (!generated) return;
const thread = yield* resolveThread(input.threadId);
if (!thread) return;
if (!canReplaceThreadTitle(thread.title, input.titleSeed)) {
return;
}
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: serverCommandId("thread-title-rename"),
threadId: input.threadId,
title: generated.title,
});
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("provider command reactor failed to generate or rename thread title", {
threadId: input.threadId,
cwd: input.cwd,
cause: Cause.pretty(cause),
}),
),
);
});
const processTurnStartRequested = Effect.fnUntraced(function* (
@@ -499,14 +530,35 @@ const make = Effect.gen(function* () {
return;
}
yield* maybeGenerateAndRenameWorktreeBranchForFirstTurn({
threadId: event.payload.threadId,
branch: thread.branch,
worktreePath: thread.worktreePath,
messageId: message.id,
messageText: message.text,
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
}).pipe(Effect.forkScoped);
const isFirstUserMessageTurn =
thread.messages.filter((entry) => entry.role === "user").length === 1;
if (isFirstUserMessageTurn) {
const generationCwd =
resolveThreadWorkspaceCwd({
thread,
projects: (yield* orchestrationEngine.getReadModel()).projects,
}) ?? process.cwd();
const generationInput = {
messageText: message.text,
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
...(event.payload.titleSeed !== undefined ? { titleSeed: event.payload.titleSeed } : {}),
};
yield* maybeGenerateAndRenameWorktreeBranchForFirstTurn({
threadId: event.payload.threadId,
branch: thread.branch,
worktreePath: thread.worktreePath,
...generationInput,
}).pipe(Effect.forkScoped);
if (canReplaceThreadTitle(thread.title, event.payload.titleSeed)) {
yield* maybeGenerateThreadTitleForFirstTurn({
threadId: event.payload.threadId,
cwd: generationCwd,
...generationInput,
}).pipe(Effect.forkScoped);
}
}
yield* sendTurnForThread({
threadId: event.payload.threadId,
@@ -721,22 +773,24 @@ const make = Effect.gen(function* () {
const worker = yield* makeDrainableWorker(processDomainEventSafely);
const start: ProviderCommandReactorShape["start"] = Effect.forkScoped(
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
const start: ProviderCommandReactorShape["start"] = Effect.fn("start")(function* () {
const processEvent = Effect.fn("processEvent")(function* (event: OrchestrationEvent) {
if (
event.type !== "thread.runtime-mode-set" &&
event.type !== "thread.turn-start-requested" &&
event.type !== "thread.turn-interrupt-requested" &&
event.type !== "thread.approval-response-requested" &&
event.type !== "thread.user-input-response-requested" &&
event.type !== "thread.session-stop-requested"
event.type === "thread.runtime-mode-set" ||
event.type === "thread.turn-start-requested" ||
event.type === "thread.turn-interrupt-requested" ||
event.type === "thread.approval-response-requested" ||
event.type === "thread.user-input-response-requested" ||
event.type === "thread.session-stop-requested"
) {
return Effect.void;
return yield* worker.enqueue(event);
}
});
return worker.enqueue(event);
}),
).pipe(Effect.asVoid);
yield* Effect.forkScoped(
Stream.runForEach(orchestrationEngine.streamDomainEvents, processEvent),
);
});
return {
start,
@@ -4,7 +4,6 @@ import path from "node:path";
import type {
OrchestrationReadModel,
ProviderKind,
ProviderRuntimeEvent,
ProviderSession,
} from "@t3tools/contracts";
@@ -12,7 +11,6 @@ import {
ApprovalRequestId,
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_SERVER_SETTINGS,
EventId,
MessageId,
ProjectId,
@@ -40,18 +38,11 @@ import {
} from "../Services/OrchestrationEngine.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
function makeTestServerSettingsLayer(overrides: Partial<ServerSettings> = {}) {
const settings: ServerSettings = { ...DEFAULT_SERVER_SETTINGS, ...overrides };
return Layer.succeed(ServerSettingsService, {
start: Effect.void,
ready: Effect.void,
getSettings: Effect.succeed(settings),
updateSettings: () => Effect.succeed(settings),
streamChanges: Stream.empty,
} satisfies ServerSettingsShape);
return ServerSettingsService.layerTest(overrides);
}
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
@@ -64,7 +55,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: ProviderKind;
readonly provider: ProviderRuntimeEvent["provider"];
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -74,6 +65,23 @@ type LegacyProviderRuntimeEvent = {
readonly [key: string]: unknown;
};
type LegacyTurnCompletedEvent = LegacyProviderRuntimeEvent & {
readonly type: "turn.completed";
readonly payload?: undefined;
readonly status: "completed" | "failed" | "interrupted" | "cancelled";
readonly errorMessage?: string | undefined;
};
function isLegacyTurnCompletedEvent(
event: LegacyProviderRuntimeEvent,
): event is LegacyTurnCompletedEvent {
return (
event.type === "turn.completed" &&
event.payload === undefined &&
typeof event.status === "string"
);
}
function createProviderServiceHarness() {
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
const runtimeSessions: ProviderSession[] = [];
@@ -101,8 +109,23 @@ function createProviderServiceHarness() {
runtimeSessions.push(session);
};
const normalizeLegacyEvent = (event: LegacyProviderRuntimeEvent): ProviderRuntimeEvent => {
if (isLegacyTurnCompletedEvent(event)) {
const normalized: Extract<ProviderRuntimeEvent, { type: "turn.completed" }> = {
...(event as Omit<Extract<ProviderRuntimeEvent, { type: "turn.completed" }>, "payload">),
payload: {
state: event.status,
...(typeof event.errorMessage === "string" ? { errorMessage: event.errorMessage } : {}),
},
};
return normalized;
}
return event as ProviderRuntimeEvent;
};
const emit = (event: LegacyProviderRuntimeEvent): void => {
Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent));
Effect.runSync(PubSub.publish(runtimeEventPubSub, normalizeLegacyEvent(event)));
};
return {
@@ -191,7 +214,7 @@ describe("ProviderRuntimeIngestion", () => {
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
const ingestion = await runtime.runPromise(Effect.service(ProviderRuntimeIngestionService));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(ingestion.start.pipe(Scope.provide(scope)));
await Effect.runPromise(ingestion.start().pipe(Scope.provide(scope)));
const drain = () => Effect.runPromise(ingestion.drain);
const createdAt = new Date().toISOString();
@@ -1703,6 +1726,37 @@ describe("ProviderRuntimeIngestion", () => {
expect(thread.session?.lastError).toBe("runtime exploded");
});
it("records runtime.error activities from the typed payload message", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "runtime.error",
eventId: asEventId("evt-runtime-error-activity"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-runtime-error-activity"),
payload: {
message: "runtime activity exploded",
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.activities.some((activity) => activity.id === "evt-runtime-error-activity"),
);
const activity = thread.activities.find(
(entry: ProviderRuntimeTestActivity) => entry.id === "evt-runtime-error-activity",
);
const activityPayload =
activity?.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: undefined;
expect(activity?.kind).toBe("runtime.error");
expect(activityPayload?.message).toBe("runtime activity exploded");
});
it("keeps the session running when a runtime.warning arrives during an active turn", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -98,10 +98,6 @@ function proposedPlanIdFromEvent(event: ProviderRuntimeEvent, threadId: ThreadId
return `plan:${threadId}:event:${event.eventId}`;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function buildContextWindowActivityPayload(
event: ProviderRuntimeEvent,
): ThreadTokenUsageSnapshot | undefined {
@@ -111,14 +107,6 @@ function buildContextWindowActivityPayload(
return event.payload.usage;
}
function runtimePayloadRecord(event: ProviderRuntimeEvent): Record<string, unknown> | undefined {
const payload = (event as { payload?: unknown }).payload;
if (!payload || typeof payload !== "object") {
return undefined;
}
return payload as Record<string, unknown>;
}
function normalizeRuntimeTurnState(
value: string | undefined,
): "completed" | "failed" | "interrupted" | "cancelled" {
@@ -133,23 +121,6 @@ function normalizeRuntimeTurnState(
}
}
function runtimeTurnState(
event: ProviderRuntimeEvent,
): "completed" | "failed" | "interrupted" | "cancelled" {
const payloadState = asString(runtimePayloadRecord(event)?.state);
return normalizeRuntimeTurnState(payloadState);
}
function runtimeTurnErrorMessage(event: ProviderRuntimeEvent): string | undefined {
const payloadErrorMessage = asString(runtimePayloadRecord(event)?.errorMessage);
return payloadErrorMessage;
}
function runtimeErrorMessageFromEvent(event: ProviderRuntimeEvent): string | undefined {
const payloadMessage = asString(runtimePayloadRecord(event)?.message);
return payloadMessage;
}
function orchestrationSessionStatusFromRuntimeState(
state: "starting" | "running" | "waiting" | "ready" | "interrupted" | "stopped" | "error",
): "starting" | "running" | "ready" | "interrupted" | "stopped" | "error" {
@@ -253,10 +224,6 @@ function runtimeEventToActivities(
}
case "runtime.error": {
const message = runtimeErrorMessageFromEvent(event);
if (!message) {
return [];
}
return [
{
id: event.eventId,
@@ -265,7 +232,7 @@ function runtimeEventToActivities(
kind: "runtime.error",
summary: "Runtime error",
payload: {
message: truncateDetail(message),
message: truncateDetail(event.payload.message),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -533,7 +500,7 @@ function runtimeEventToActivities(
return [];
}
const make = Effect.gen(function* () {
const make = Effect.fn("make")(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const providerService = yield* ProviderService;
const projectionTurnRepository = yield* ProjectionTurnRepository;
@@ -620,8 +587,8 @@ const make = Effect.gen(function* () {
const appendBufferedAssistantText = (messageId: MessageId, delta: string) =>
Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe(
Effect.flatMap((existingText) =>
Effect.gen(function* () {
Effect.flatMap(
Effect.fn("appendBufferedAssistantText")(function* (existingText) {
const nextText = Option.match(existingText, {
onNone: () => delta,
onSome: (text) => `${text}${delta}`,
@@ -677,7 +644,7 @@ const make = Effect.gen(function* () {
const clearAssistantMessageState = (messageId: MessageId) =>
clearBufferedAssistantText(messageId);
const finalizeAssistantMessage = (input: {
const finalizeAssistantMessage = Effect.fn("finalizeAssistantMessage")(function* (input: {
event: ProviderRuntimeEvent;
threadId: ThreadId;
messageId: MessageId;
@@ -686,40 +653,39 @@ const make = Effect.gen(function* () {
commandTag: string;
finalDeltaCommandTag: string;
fallbackText?: string;
}) =>
Effect.gen(function* () {
const bufferedText = yield* takeBufferedAssistantText(input.messageId);
const text =
bufferedText.length > 0
? bufferedText
: (input.fallbackText?.trim().length ?? 0) > 0
? input.fallbackText!
: "";
if (text.length > 0) {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.delta",
commandId: providerCommandId(input.event, input.finalDeltaCommandTag),
threadId: input.threadId,
messageId: input.messageId,
delta: text,
...(input.turnId ? { turnId: input.turnId } : {}),
createdAt: input.createdAt,
});
}
}) {
const bufferedText = yield* takeBufferedAssistantText(input.messageId);
const text =
bufferedText.length > 0
? bufferedText
: (input.fallbackText?.trim().length ?? 0) > 0
? input.fallbackText!
: "";
if (text.length > 0) {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.complete",
commandId: providerCommandId(input.event, input.commandTag),
type: "thread.message.assistant.delta",
commandId: providerCommandId(input.event, input.finalDeltaCommandTag),
threadId: input.threadId,
messageId: input.messageId,
delta: text,
...(input.turnId ? { turnId: input.turnId } : {}),
createdAt: input.createdAt,
});
yield* clearAssistantMessageState(input.messageId);
});
}
const upsertProposedPlan = (input: {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.complete",
commandId: providerCommandId(input.event, input.commandTag),
threadId: input.threadId,
messageId: input.messageId,
...(input.turnId ? { turnId: input.turnId } : {}),
createdAt: input.createdAt,
});
yield* clearAssistantMessageState(input.messageId);
});
const upsertProposedPlan = Effect.fn("upsertProposedPlan")(function* (input: {
event: ProviderRuntimeEvent;
threadId: ThreadId;
threadProposedPlans: ReadonlyArray<{
@@ -733,32 +699,31 @@ const make = Effect.gen(function* () {
planMarkdown: string | undefined;
createdAt: string;
updatedAt: string;
}) =>
Effect.gen(function* () {
const planMarkdown = normalizeProposedPlanMarkdown(input.planMarkdown);
if (!planMarkdown) {
return;
}
}) {
const planMarkdown = normalizeProposedPlanMarkdown(input.planMarkdown);
if (!planMarkdown) {
return;
}
const existingPlan = input.threadProposedPlans.find((entry) => entry.id === input.planId);
yield* orchestrationEngine.dispatch({
type: "thread.proposed-plan.upsert",
commandId: providerCommandId(input.event, "proposed-plan-upsert"),
threadId: input.threadId,
proposedPlan: {
id: input.planId,
turnId: input.turnId ?? null,
planMarkdown,
implementedAt: existingPlan?.implementedAt ?? null,
implementationThreadId: existingPlan?.implementationThreadId ?? null,
createdAt: existingPlan?.createdAt ?? input.createdAt,
updatedAt: input.updatedAt,
},
createdAt: input.updatedAt,
});
const existingPlan = input.threadProposedPlans.find((entry) => entry.id === input.planId);
yield* orchestrationEngine.dispatch({
type: "thread.proposed-plan.upsert",
commandId: providerCommandId(input.event, "proposed-plan-upsert"),
threadId: input.threadId,
proposedPlan: {
id: input.planId,
turnId: input.turnId ?? null,
planMarkdown,
implementedAt: existingPlan?.implementedAt ?? null,
implementationThreadId: existingPlan?.implementationThreadId ?? null,
createdAt: existingPlan?.createdAt ?? input.createdAt,
updatedAt: input.updatedAt,
},
createdAt: input.updatedAt,
});
});
const finalizeBufferedProposedPlan = (input: {
const finalizeBufferedProposedPlan = Effect.fn("finalizeBufferedProposedPlan")(function* (input: {
event: ProviderRuntimeEvent;
threadId: ThreadId;
threadProposedPlans: ReadonlyArray<{
@@ -771,66 +736,65 @@ const make = Effect.gen(function* () {
turnId?: TurnId;
fallbackMarkdown?: string;
updatedAt: string;
}) =>
Effect.gen(function* () {
const bufferedPlan = yield* takeBufferedProposedPlan(input.planId);
const bufferedMarkdown = normalizeProposedPlanMarkdown(bufferedPlan?.text);
const fallbackMarkdown = normalizeProposedPlanMarkdown(input.fallbackMarkdown);
const planMarkdown = bufferedMarkdown ?? fallbackMarkdown;
if (!planMarkdown) {
return;
}
}) {
const bufferedPlan = yield* takeBufferedProposedPlan(input.planId);
const bufferedMarkdown = normalizeProposedPlanMarkdown(bufferedPlan?.text);
const fallbackMarkdown = normalizeProposedPlanMarkdown(input.fallbackMarkdown);
const planMarkdown = bufferedMarkdown ?? fallbackMarkdown;
if (!planMarkdown) {
return;
}
yield* upsertProposedPlan({
event: input.event,
threadId: input.threadId,
threadProposedPlans: input.threadProposedPlans,
planId: input.planId,
...(input.turnId ? { turnId: input.turnId } : {}),
planMarkdown,
createdAt:
bufferedPlan?.createdAt && bufferedPlan.createdAt.length > 0
? bufferedPlan.createdAt
: input.updatedAt,
updatedAt: input.updatedAt,
});
yield* clearBufferedProposedPlan(input.planId);
yield* upsertProposedPlan({
event: input.event,
threadId: input.threadId,
threadProposedPlans: input.threadProposedPlans,
planId: input.planId,
...(input.turnId ? { turnId: input.turnId } : {}),
planMarkdown,
createdAt:
bufferedPlan?.createdAt && bufferedPlan.createdAt.length > 0
? bufferedPlan.createdAt
: input.updatedAt,
updatedAt: input.updatedAt,
});
yield* clearBufferedProposedPlan(input.planId);
});
const clearTurnStateForSession = (threadId: ThreadId) =>
Effect.gen(function* () {
const prefix = `${threadId}:`;
const proposedPlanPrefix = `plan:${threadId}:`;
const turnKeys = Array.from(yield* Cache.keys(turnMessageIdsByTurnKey));
const proposedPlanKeys = Array.from(yield* Cache.keys(bufferedProposedPlanById));
yield* Effect.forEach(
turnKeys,
(key) =>
Effect.gen(function* () {
if (!key.startsWith(prefix)) {
return;
}
const clearTurnStateForSession = Effect.fn("clearTurnStateForSession")(function* (
threadId: ThreadId,
) {
const prefix = `${threadId}:`;
const proposedPlanPrefix = `plan:${threadId}:`;
const turnKeys = Array.from(yield* Cache.keys(turnMessageIdsByTurnKey));
const proposedPlanKeys = Array.from(yield* Cache.keys(bufferedProposedPlanById));
yield* Effect.forEach(
turnKeys,
Effect.fn(function* (key) {
if (!key.startsWith(prefix)) {
return;
}
const messageIds = yield* Cache.getOption(turnMessageIdsByTurnKey, key);
if (Option.isSome(messageIds)) {
yield* Effect.forEach(messageIds.value, clearAssistantMessageState, {
concurrency: 1,
}).pipe(Effect.asVoid);
}
const messageIds = yield* Cache.getOption(turnMessageIdsByTurnKey, key);
if (Option.isSome(messageIds)) {
yield* Effect.forEach(messageIds.value, clearAssistantMessageState, {
concurrency: 1,
}).pipe(Effect.asVoid);
}
yield* Cache.invalidate(turnMessageIdsByTurnKey, key);
}),
{ concurrency: 1 },
).pipe(Effect.asVoid);
yield* Effect.forEach(
proposedPlanKeys,
(key) =>
key.startsWith(proposedPlanPrefix)
? Cache.invalidate(bufferedProposedPlanById, key)
: Effect.void,
{ concurrency: 1 },
).pipe(Effect.asVoid);
});
yield* Cache.invalidate(turnMessageIdsByTurnKey, key);
}),
{ concurrency: 1 },
).pipe(Effect.asVoid);
yield* Effect.forEach(
proposedPlanKeys,
(key) =>
key.startsWith(proposedPlanPrefix)
? Cache.invalidate(bufferedProposedPlanById, key)
: Effect.void,
{ concurrency: 1 },
).pipe(Effect.asVoid);
});
const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fnUntraced(function* (
threadId: ThreadId,
@@ -905,356 +869,355 @@ const make = Effect.gen(function* () {
});
});
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
Effect.gen(function* () {
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
if (!thread) return;
const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* (
event: ProviderRuntimeEvent,
) {
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
if (!thread) return;
const now = event.createdAt;
const eventTurnId = toTurnId(event.turnId);
const activeTurnId = thread.session?.activeTurnId ?? null;
const now = event.createdAt;
const eventTurnId = toTurnId(event.turnId);
const activeTurnId = thread.session?.activeTurnId ?? null;
const conflictsWithActiveTurn =
activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined;
const conflictsWithActiveTurn =
activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined;
const shouldApplyThreadLifecycle = (() => {
if (!STRICT_PROVIDER_LIFECYCLE_GUARD) {
const shouldApplyThreadLifecycle = (() => {
if (!STRICT_PROVIDER_LIFECYCLE_GUARD) {
return true;
}
switch (event.type) {
case "session.exited":
return true;
}
case "session.started":
case "thread.started":
return true;
case "turn.started":
return !conflictsWithActiveTurn;
case "turn.completed":
if (conflictsWithActiveTurn || missingTurnForActiveTurn) {
return false;
}
// Only the active turn may close the lifecycle state.
if (activeTurnId !== null && eventTurnId !== undefined) {
return sameId(activeTurnId, eventTurnId);
}
// If no active turn is tracked, accept completion scoped to this thread.
return true;
default:
return true;
}
})();
const acceptedTurnStartedSourcePlan =
event.type === "turn.started" && shouldApplyThreadLifecycle
? yield* getSourceProposedPlanReferenceForAcceptedTurnStart(thread.id, eventTurnId)
: null;
if (
event.type === "session.started" ||
event.type === "session.state.changed" ||
event.type === "session.exited" ||
event.type === "thread.started" ||
event.type === "turn.started" ||
event.type === "turn.completed"
) {
const nextActiveTurnId =
event.type === "turn.started"
? (eventTurnId ?? null)
: event.type === "turn.completed" || event.type === "session.exited"
? null
: activeTurnId;
const status = (() => {
switch (event.type) {
case "session.state.changed":
return orchestrationSessionStatusFromRuntimeState(event.payload.state);
case "turn.started":
return "running";
case "session.exited":
return true;
return "stopped";
case "turn.completed":
return normalizeRuntimeTurnState(event.payload.state) === "failed" ? "error" : "ready";
case "session.started":
case "thread.started":
return true;
case "turn.started":
return !conflictsWithActiveTurn;
case "turn.completed":
if (conflictsWithActiveTurn || missingTurnForActiveTurn) {
return false;
}
// Only the active turn may close the lifecycle state.
if (activeTurnId !== null && eventTurnId !== undefined) {
return sameId(activeTurnId, eventTurnId);
}
// If no active turn is tracked, accept completion scoped to this thread.
return true;
default:
return true;
// Provider thread/session start notifications can arrive during an
// active turn; preserve turn-running state in that case.
return activeTurnId !== null ? "running" : "ready";
}
})();
const acceptedTurnStartedSourcePlan =
event.type === "turn.started" && shouldApplyThreadLifecycle
? yield* getSourceProposedPlanReferenceForAcceptedTurnStart(thread.id, eventTurnId)
: null;
if (
event.type === "session.started" ||
event.type === "session.state.changed" ||
event.type === "session.exited" ||
event.type === "thread.started" ||
event.type === "turn.started" ||
event.type === "turn.completed"
) {
const nextActiveTurnId =
event.type === "turn.started"
? (eventTurnId ?? null)
: event.type === "turn.completed" || event.type === "session.exited"
const lastError =
event.type === "session.state.changed" && event.payload.state === "error"
? (event.payload.reason ?? thread.session?.lastError ?? "Provider session error")
: event.type === "turn.completed" &&
normalizeRuntimeTurnState(event.payload.state) === "failed"
? (event.payload.errorMessage ?? thread.session?.lastError ?? "Turn failed")
: status === "ready"
? null
: activeTurnId;
const status = (() => {
switch (event.type) {
case "session.state.changed":
return orchestrationSessionStatusFromRuntimeState(event.payload.state);
case "turn.started":
return "running";
case "session.exited":
return "stopped";
case "turn.completed":
return runtimeTurnState(event) === "failed" ? "error" : "ready";
case "session.started":
case "thread.started":
// Provider thread/session start notifications can arrive during an
// active turn; preserve turn-running state in that case.
return activeTurnId !== null ? "running" : "ready";
}
})();
const lastError =
event.type === "session.state.changed" && event.payload.state === "error"
? (event.payload.reason ?? thread.session?.lastError ?? "Provider session error")
: event.type === "turn.completed" && runtimeTurnState(event) === "failed"
? (runtimeTurnErrorMessage(event) ?? thread.session?.lastError ?? "Turn failed")
: status === "ready"
? null
: (thread.session?.lastError ?? null);
: (thread.session?.lastError ?? null);
if (shouldApplyThreadLifecycle) {
if (event.type === "turn.started" && acceptedTurnStartedSourcePlan !== null) {
yield* markSourceProposedPlanImplemented(
acceptedTurnStartedSourcePlan.sourceThreadId,
acceptedTurnStartedSourcePlan.sourcePlanId,
thread.id,
now,
).pipe(
Effect.catchCause((cause) =>
Effect.logWarning(
"provider runtime ingestion failed to mark source proposed plan",
{
eventId: event.eventId,
eventType: event.type,
cause: Cause.pretty(cause),
},
),
),
);
}
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: providerCommandId(event, "thread-session-set"),
threadId: thread.id,
session: {
threadId: thread.id,
status,
providerName: event.provider,
runtimeMode: thread.session?.runtimeMode ?? "full-access",
activeTurnId: nextActiveTurnId,
lastError,
updatedAt: now,
},
createdAt: now,
});
if (shouldApplyThreadLifecycle) {
if (event.type === "turn.started" && acceptedTurnStartedSourcePlan !== null) {
yield* markSourceProposedPlanImplemented(
acceptedTurnStartedSourcePlan.sourceThreadId,
acceptedTurnStartedSourcePlan.sourcePlanId,
thread.id,
now,
).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("provider runtime ingestion failed to mark source proposed plan", {
eventId: event.eventId,
eventType: event.type,
cause: Cause.pretty(cause),
}),
),
);
}
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: providerCommandId(event, "thread-session-set"),
threadId: thread.id,
session: {
threadId: thread.id,
status,
providerName: event.provider,
runtimeMode: thread.session?.runtimeMode ?? "full-access",
activeTurnId: nextActiveTurnId,
lastError,
updatedAt: now,
},
createdAt: now,
});
}
}
const assistantDelta =
event.type === "content.delta" && event.payload.streamKind === "assistant_text"
? event.payload.delta
: undefined;
const proposedPlanDelta =
event.type === "turn.proposed.delta" ? event.payload.delta : undefined;
if (assistantDelta && assistantDelta.length > 0) {
const assistantMessageId = MessageId.makeUnsafe(
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
);
const turnId = toTurnId(event.turnId);
if (turnId) {
yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);
}
const assistantDelta =
event.type === "content.delta" && event.payload.streamKind === "assistant_text"
? event.payload.delta
: undefined;
const proposedPlanDelta =
event.type === "turn.proposed.delta" ? event.payload.delta : undefined;
if (assistantDelta && assistantDelta.length > 0) {
const assistantMessageId = MessageId.makeUnsafe(
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
);
const turnId = toTurnId(event.turnId);
if (turnId) {
yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);
}
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
);
if (assistantDeliveryMode === "buffered") {
const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta);
if (spillChunk.length > 0) {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.delta",
commandId: providerCommandId(event, "assistant-delta-buffer-spill"),
threadId: thread.id,
messageId: assistantMessageId,
delta: spillChunk,
...(turnId ? { turnId } : {}),
createdAt: now,
});
}
} else {
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
);
if (assistantDeliveryMode === "buffered") {
const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta);
if (spillChunk.length > 0) {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.delta",
commandId: providerCommandId(event, "assistant-delta"),
commandId: providerCommandId(event, "assistant-delta-buffer-spill"),
threadId: thread.id,
messageId: assistantMessageId,
delta: assistantDelta,
delta: spillChunk,
...(turnId ? { turnId } : {}),
createdAt: now,
});
}
}
if (proposedPlanDelta && proposedPlanDelta.length > 0) {
const planId = proposedPlanIdFromEvent(event, thread.id);
yield* appendBufferedProposedPlan(planId, proposedPlanDelta, now);
}
const assistantCompletion =
event.type === "item.completed" && event.payload.itemType === "assistant_message"
? {
messageId: MessageId.makeUnsafe(
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
),
fallbackText: event.payload.detail,
}
: undefined;
const proposedPlanCompletion =
event.type === "turn.proposed.completed"
? {
planId: proposedPlanIdFromEvent(event, thread.id),
turnId: toTurnId(event.turnId),
planMarkdown: event.payload.planMarkdown,
}
: undefined;
if (assistantCompletion) {
const assistantMessageId = assistantCompletion.messageId;
const turnId = toTurnId(event.turnId);
const existingAssistantMessage = thread.messages.find(
(entry) => entry.id === assistantMessageId,
);
const shouldApplyFallbackCompletionText =
!existingAssistantMessage || existingAssistantMessage.text.length === 0;
if (turnId) {
yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);
}
yield* finalizeAssistantMessage({
event,
} else {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.delta",
commandId: providerCommandId(event, "assistant-delta"),
threadId: thread.id,
messageId: assistantMessageId,
delta: assistantDelta,
...(turnId ? { turnId } : {}),
createdAt: now,
commandTag: "assistant-complete",
finalDeltaCommandTag: "assistant-delta-finalize",
...(assistantCompletion.fallbackText !== undefined && shouldApplyFallbackCompletionText
? { fallbackText: assistantCompletion.fallbackText }
: {}),
});
}
}
if (turnId) {
yield* forgetAssistantMessageId(thread.id, turnId, assistantMessageId);
}
if (proposedPlanDelta && proposedPlanDelta.length > 0) {
const planId = proposedPlanIdFromEvent(event, thread.id);
yield* appendBufferedProposedPlan(planId, proposedPlanDelta, now);
}
const assistantCompletion =
event.type === "item.completed" && event.payload.itemType === "assistant_message"
? {
messageId: MessageId.makeUnsafe(
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
),
fallbackText: event.payload.detail,
}
: undefined;
const proposedPlanCompletion =
event.type === "turn.proposed.completed"
? {
planId: proposedPlanIdFromEvent(event, thread.id),
turnId: toTurnId(event.turnId),
planMarkdown: event.payload.planMarkdown,
}
: undefined;
if (assistantCompletion) {
const assistantMessageId = assistantCompletion.messageId;
const turnId = toTurnId(event.turnId);
const existingAssistantMessage = thread.messages.find(
(entry) => entry.id === assistantMessageId,
);
const shouldApplyFallbackCompletionText =
!existingAssistantMessage || existingAssistantMessage.text.length === 0;
if (turnId) {
yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);
}
if (proposedPlanCompletion) {
yield* finalizeAssistantMessage({
event,
threadId: thread.id,
messageId: assistantMessageId,
...(turnId ? { turnId } : {}),
createdAt: now,
commandTag: "assistant-complete",
finalDeltaCommandTag: "assistant-delta-finalize",
...(assistantCompletion.fallbackText !== undefined && shouldApplyFallbackCompletionText
? { fallbackText: assistantCompletion.fallbackText }
: {}),
});
if (turnId) {
yield* forgetAssistantMessageId(thread.id, turnId, assistantMessageId);
}
}
if (proposedPlanCompletion) {
yield* finalizeBufferedProposedPlan({
event,
threadId: thread.id,
threadProposedPlans: thread.proposedPlans,
planId: proposedPlanCompletion.planId,
...(proposedPlanCompletion.turnId ? { turnId: proposedPlanCompletion.turnId } : {}),
fallbackMarkdown: proposedPlanCompletion.planMarkdown,
updatedAt: now,
});
}
if (event.type === "turn.completed") {
const turnId = toTurnId(event.turnId);
if (turnId) {
const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId);
yield* Effect.forEach(
assistantMessageIds,
(assistantMessageId) =>
finalizeAssistantMessage({
event,
threadId: thread.id,
messageId: assistantMessageId,
turnId,
createdAt: now,
commandTag: "assistant-complete-finalize",
finalDeltaCommandTag: "assistant-delta-finalize-fallback",
}),
{ concurrency: 1 },
).pipe(Effect.asVoid);
yield* clearAssistantMessageIdsForTurn(thread.id, turnId);
yield* finalizeBufferedProposedPlan({
event,
threadId: thread.id,
threadProposedPlans: thread.proposedPlans,
planId: proposedPlanCompletion.planId,
...(proposedPlanCompletion.turnId ? { turnId: proposedPlanCompletion.turnId } : {}),
fallbackMarkdown: proposedPlanCompletion.planMarkdown,
planId: proposedPlanIdForTurn(thread.id, turnId),
turnId,
updatedAt: now,
});
}
}
if (event.type === "turn.completed") {
const turnId = toTurnId(event.turnId);
if (turnId) {
const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId);
yield* Effect.forEach(
assistantMessageIds,
(assistantMessageId) =>
finalizeAssistantMessage({
event,
threadId: thread.id,
messageId: assistantMessageId,
turnId,
createdAt: now,
commandTag: "assistant-complete-finalize",
finalDeltaCommandTag: "assistant-delta-finalize-fallback",
}),
{ concurrency: 1 },
).pipe(Effect.asVoid);
yield* clearAssistantMessageIdsForTurn(thread.id, turnId);
if (event.type === "session.exited") {
yield* clearTurnStateForSession(thread.id);
}
yield* finalizeBufferedProposedPlan({
event,
if (event.type === "runtime.error") {
const runtimeErrorMessage = event.payload.message;
const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD
? true
: activeTurnId === null || eventTurnId === undefined || sameId(activeTurnId, eventTurnId);
if (shouldApplyRuntimeError) {
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: providerCommandId(event, "runtime-error-session-set"),
threadId: thread.id,
session: {
threadId: thread.id,
threadProposedPlans: thread.proposedPlans,
planId: proposedPlanIdForTurn(thread.id, turnId),
turnId,
status: "error",
providerName: event.provider,
runtimeMode: thread.session?.runtimeMode ?? "full-access",
activeTurnId: eventTurnId ?? null,
lastError: runtimeErrorMessage,
updatedAt: now,
});
}
},
createdAt: now,
});
}
}
if (event.type === "session.exited") {
yield* clearTurnStateForSession(thread.id);
}
if (event.type === "thread.metadata.updated" && event.payload.name) {
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: providerCommandId(event, "thread-meta-update"),
threadId: thread.id,
title: event.payload.name,
});
}
if (event.type === "runtime.error") {
const runtimeErrorMessage = runtimeErrorMessageFromEvent(event) ?? "Provider runtime error";
const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD
? true
: activeTurnId === null || eventTurnId === undefined || sameId(activeTurnId, eventTurnId);
if (shouldApplyRuntimeError) {
if (event.type === "turn.diff.updated") {
const turnId = toTurnId(event.turnId);
if (turnId && (yield* isGitRepoForThread(thread.id))) {
// Skip if a checkpoint already exists for this turn. A real
// (non-placeholder) capture from CheckpointReactor should not
// be clobbered, and dispatching a duplicate placeholder for the
// same turnId would produce an unstable checkpointTurnCount.
if (thread.checkpoints.some((c) => c.turnId === turnId)) {
// Already tracked; no-op.
} else {
const assistantMessageId = MessageId.makeUnsafe(
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
);
const maxTurnCount = thread.checkpoints.reduce(
(max, c) => Math.max(max, c.checkpointTurnCount),
0,
);
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: providerCommandId(event, "runtime-error-session-set"),
type: "thread.turn.diff.complete",
commandId: providerCommandId(event, "thread-turn-diff-complete"),
threadId: thread.id,
session: {
threadId: thread.id,
status: "error",
providerName: event.provider,
runtimeMode: thread.session?.runtimeMode ?? "full-access",
activeTurnId: eventTurnId ?? null,
lastError: runtimeErrorMessage,
updatedAt: now,
},
turnId,
completedAt: now,
checkpointRef: CheckpointRef.makeUnsafe(`provider-diff:${event.eventId}`),
status: "missing",
files: [],
assistantMessageId,
checkpointTurnCount: maxTurnCount + 1,
createdAt: now,
});
}
}
}
if (event.type === "thread.metadata.updated" && event.payload.name) {
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: providerCommandId(event, "thread-meta-update"),
threadId: thread.id,
title: event.payload.name,
});
}
if (event.type === "turn.diff.updated") {
const turnId = toTurnId(event.turnId);
if (turnId && (yield* isGitRepoForThread(thread.id))) {
// Skip if a checkpoint already exists for this turn. A real
// (non-placeholder) capture from CheckpointReactor should not
// be clobbered, and dispatching a duplicate placeholder for the
// same turnId would produce an unstable checkpointTurnCount.
if (thread.checkpoints.some((c) => c.turnId === turnId)) {
// Already tracked; no-op.
} else {
const assistantMessageId = MessageId.makeUnsafe(
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
);
const maxTurnCount = thread.checkpoints.reduce(
(max, c) => Math.max(max, c.checkpointTurnCount),
0,
);
yield* orchestrationEngine.dispatch({
type: "thread.turn.diff.complete",
commandId: providerCommandId(event, "thread-turn-diff-complete"),
threadId: thread.id,
turnId,
completedAt: now,
checkpointRef: CheckpointRef.makeUnsafe(`provider-diff:${event.eventId}`),
status: "missing",
files: [],
assistantMessageId,
checkpointTurnCount: maxTurnCount + 1,
createdAt: now,
});
}
}
}
const activities = runtimeEventToActivities(event);
yield* Effect.forEach(activities, (activity) =>
orchestrationEngine.dispatch({
type: "thread.activity.append",
commandId: providerCommandId(event, "thread-activity-append"),
threadId: thread.id,
activity,
createdAt: activity.createdAt,
}),
).pipe(Effect.asVoid);
});
const activities = runtimeEventToActivities(event);
yield* Effect.forEach(activities, (activity) =>
orchestrationEngine.dispatch({
type: "thread.activity.append",
commandId: providerCommandId(event, "thread-activity-append"),
threadId: thread.id,
activity,
createdAt: activity.createdAt,
}),
).pipe(Effect.asVoid);
});
const processDomainEvent = (_event: TurnStartRequestedDomainEvent) => Effect.void;
@@ -1278,7 +1241,7 @@ const make = Effect.gen(function* () {
const worker = yield* makeDrainableWorker(processInputSafely);
const start: ProviderRuntimeIngestionShape["start"] = Effect.gen(function* () {
const start: ProviderRuntimeIngestionShape["start"] = Effect.fn("start")(function* () {
yield* Effect.forkScoped(
Stream.runForEach(providerService.streamEvents, (event) =>
worker.enqueue({ source: "runtime", event }),
@@ -1302,5 +1265,5 @@ const make = Effect.gen(function* () {
export const ProviderRuntimeIngestionLive = Layer.effect(
ProviderRuntimeIngestionService,
make,
make(),
).pipe(Layer.provide(ProjectionTurnRepositoryLive));
+4
View File
@@ -3,10 +3,12 @@ import {
ProjectMetaUpdatedPayload as ContractsProjectMetaUpdatedPayloadSchema,
ProjectDeletedPayload as ContractsProjectDeletedPayloadSchema,
ThreadCreatedPayload as ContractsThreadCreatedPayloadSchema,
ThreadArchivedPayload as ContractsThreadArchivedPayloadSchema,
ThreadMetaUpdatedPayload as ContractsThreadMetaUpdatedPayloadSchema,
ThreadRuntimeModeSetPayload as ContractsThreadRuntimeModeSetPayloadSchema,
ThreadInteractionModeSetPayload as ContractsThreadInteractionModeSetPayloadSchema,
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema,
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
@@ -26,10 +28,12 @@ export const ProjectMetaUpdatedPayload = ContractsProjectMetaUpdatedPayloadSchem
export const ProjectDeletedPayload = ContractsProjectDeletedPayloadSchema;
export const ThreadCreatedPayload = ContractsThreadCreatedPayloadSchema;
export const ThreadArchivedPayload = ContractsThreadArchivedPayloadSchema;
export const ThreadMetaUpdatedPayload = ContractsThreadMetaUpdatedPayloadSchema;
export const ThreadRuntimeModeSetPayload = ContractsThreadRuntimeModeSetPayloadSchema;
export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSetPayloadSchema;
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
@@ -22,7 +22,7 @@ export interface CheckpointReactorShape {
* Consumes both orchestration-domain and provider-runtime events via an
* internal queue.
*/
readonly start: Effect.Effect<void, never, Scope.Scope>;
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
/**
* Resolves when the internal processing queue is empty and idle.
@@ -19,7 +19,7 @@ export interface OrchestrationReactorShape {
* The returned effect must be run in a scope so all worker fibers can be
* finalized on shutdown.
*/
readonly start: Effect.Effect<void, never, Scope.Scope>;
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
}
/**
@@ -22,7 +22,7 @@ export interface ProviderCommandReactorShape {
* Filters orchestration domain events to provider-intent types before
* processing.
*/
readonly start: Effect.Effect<void, never, Scope.Scope>;
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
/**
* Resolves when the internal processing queue is empty and idle.
@@ -22,7 +22,7 @@ export interface ProviderRuntimeIngestionShape {
* Uses an internal queue and continues after non-interrupt failures by
* logging warnings.
*/
readonly start: Effect.Effect<void, never, Scope.Scope>;
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
/**
* Resolves when the internal processing queue is empty and idle.
@@ -66,6 +66,7 @@ const readModel: OrchestrationReadModel = {
worktreePath: null,
createdAt: now,
updatedAt: now,
archivedAt: null,
latestTurn: null,
messages: [],
session: null,
@@ -88,6 +89,7 @@ const readModel: OrchestrationReadModel = {
worktreePath: null,
createdAt: now,
updatedAt: now,
archivedAt: null,
latestTurn: null,
messages: [],
session: null,
@@ -88,6 +88,44 @@ export function requireThread(input: {
);
}
export function requireThreadArchived(input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
readonly threadId: ThreadId;
}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {
return requireThread(input).pipe(
Effect.flatMap((thread) =>
thread.archivedAt !== null
? Effect.succeed(thread)
: Effect.fail(
invariantError(
input.command.type,
`Thread '${input.threadId}' is not archived for command '${input.command.type}'.`,
),
),
),
);
}
export function requireThreadNotArchived(input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
readonly threadId: ThreadId;
}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {
return requireThread(input).pipe(
Effect.flatMap((thread) =>
thread.archivedAt === null
? Effect.succeed(thread)
: Effect.fail(
invariantError(
input.command.type,
`Thread '${input.threadId}' is already archived and cannot handle command '${input.command.type}'.`,
),
),
),
);
}
export function requireThreadAbsent(input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
+48 -1
View File
@@ -10,11 +10,12 @@ import {
requireProject,
requireProjectAbsent,
requireThread,
requireThreadArchived,
requireThreadAbsent,
requireThreadNotArchived,
} from "./commandInvariants.ts";
const nowIso = () => new Date().toISOString();
const defaultMetadata: Omit<OrchestrationEvent, "sequence" | "type" | "payload"> = {
eventId: crypto.randomUUID() as OrchestrationEvent["eventId"],
aggregateKind: "thread",
@@ -190,6 +191,51 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.archive": {
yield* requireThreadNotArchived({
readModel,
command,
threadId: command.threadId,
});
const occurredAt = nowIso();
return {
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
}),
type: "thread.archived",
payload: {
threadId: command.threadId,
archivedAt: occurredAt,
updatedAt: occurredAt,
},
};
}
case "thread.unarchive": {
yield* requireThreadArchived({
readModel,
command,
threadId: command.threadId,
});
const occurredAt = nowIso();
return {
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
}),
type: "thread.unarchived",
payload: {
threadId: command.threadId,
updatedAt: occurredAt,
},
};
}
case "thread.meta.update": {
yield* requireThread({
readModel,
@@ -329,6 +375,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
...(command.modelSelection !== undefined
? { modelSelection: command.modelSelection }
: {}),
...(command.titleSeed !== undefined ? { titleSeed: command.titleSeed } : {}),
runtimeMode: targetThread.runtimeMode,
interactionMode: targetThread.interactionMode,
...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
@@ -87,6 +87,7 @@ describe("orchestration projector", () => {
latestTurn: null,
createdAt: now,
updatedAt: now,
archivedAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
@@ -131,6 +132,78 @@ describe("orchestration projector", () => {
).rejects.toBeDefined();
});
it("applies thread.archived and thread.unarchived events", async () => {
const now = new Date().toISOString();
const later = new Date(Date.parse(now) + 1_000).toISOString();
const created = await Effect.runPromise(
projectEvent(
createEmptyReadModel(now),
makeEvent({
sequence: 1,
type: "thread.created",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: now,
commandId: "cmd-thread-create",
payload: {
threadId: "thread-1",
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
}),
),
);
const archived = await Effect.runPromise(
projectEvent(
created,
makeEvent({
sequence: 2,
type: "thread.archived",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: later,
commandId: "cmd-thread-archive",
payload: {
threadId: "thread-1",
archivedAt: later,
updatedAt: later,
},
}),
),
);
expect(archived.threads[0]?.archivedAt).toBe(later);
const unarchived = await Effect.runPromise(
projectEvent(
archived,
makeEvent({
sequence: 3,
type: "thread.unarchived",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: later,
commandId: "cmd-thread-unarchive",
payload: {
threadId: "thread-1",
updatedAt: later,
},
}),
),
);
expect(unarchived.threads[0]?.archivedAt).toBeNull();
});
it("keeps projector forward-compatible for unhandled event types", async () => {
const now = new Date().toISOString();
const model = createEmptyReadModel(now);
@@ -14,12 +14,14 @@ import {
ProjectDeletedPayload,
ProjectMetaUpdatedPayload,
ThreadActivityAppendedPayload,
ThreadArchivedPayload,
ThreadCreatedPayload,
ThreadDeletedPayload,
ThreadInteractionModeSetPayload,
ThreadMetaUpdatedPayload,
ThreadProposedPlanUpsertedPayload,
ThreadRuntimeModeSetPayload,
ThreadUnarchivedPayload,
ThreadRevertedPayload,
ThreadSessionSetPayload,
ThreadTurnDiffCompletedPayload,
@@ -260,6 +262,7 @@ export function projectEvent(
latestTurn: null,
createdAt: payload.createdAt,
updatedAt: payload.updatedAt,
archivedAt: null,
deletedAt: null,
messages: [],
activities: [],
@@ -289,6 +292,28 @@ export function projectEvent(
})),
);
case "thread.archived":
return decodeForEvent(ThreadArchivedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
archivedAt: payload.archivedAt,
updatedAt: payload.updatedAt,
}),
})),
);
case "thread.unarchived":
return decodeForEvent(ThreadUnarchivedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
archivedAt: null,
updatedAt: payload.updatedAt,
}),
})),
);
case "thread.meta-updated":
return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
+39
View File
@@ -0,0 +1,39 @@
import { describe, expect, it, vi } from "vitest";
import { fixPath } from "./os-jank";
describe("fixPath", () => {
it("hydrates PATH on linux using the resolved login shell", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
};
const readPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin");
fixPath({
env,
platform: "linux",
readPath,
});
expect(readPath).toHaveBeenCalledWith("/bin/zsh");
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
});
it("does nothing outside macOS and linux even when SHELL is set", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "C:/Program Files/Git/bin/bash.exe",
PATH: "C:\\Windows\\System32",
};
const readPath = vi.fn(() => "/usr/local/bin:/usr/bin");
fixPath({
env,
platform: "win32",
readPath,
});
expect(readPath).not.toHaveBeenCalled();
expect(env.PATH).toBe("C:\\Windows\\System32");
});
});
+16 -6
View File
@@ -1,15 +1,25 @@
import * as OS from "node:os";
import { Effect, Path } from "effect";
import { readPathFromLoginShell } from "@t3tools/shared/shell";
import { readPathFromLoginShell, resolveLoginShell } from "@t3tools/shared/shell";
export function fixPath(): void {
if (process.platform !== "darwin") return;
export function fixPath(
options: {
env?: NodeJS.ProcessEnv;
platform?: NodeJS.Platform;
readPath?: typeof readPathFromLoginShell;
} = {},
): void {
const platform = options.platform ?? process.platform;
if (platform !== "darwin" && platform !== "linux") return;
const env = options.env ?? process.env;
try {
const shell = process.env.SHELL ?? "/bin/zsh";
const result = readPathFromLoginShell(shell);
const shell = resolveLoginShell(platform, env.SHELL);
if (!shell) return;
const result = (options.readPath ?? readPathFromLoginShell)(shell);
if (result) {
process.env.PATH = result;
env.PATH = result;
}
} catch {
// Silently ignore — keep default PATH
@@ -87,6 +87,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
latestTurnId: null,
createdAt: "2026-03-24T00:00:00.000Z",
updatedAt: "2026-03-24T00:00:00.000Z",
archivedAt: null,
deletedAt: null,
});
@@ -39,6 +39,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
latest_turn_id,
created_at,
updated_at,
archived_at,
deleted_at
)
VALUES (
@@ -53,6 +54,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.latestTurnId},
${row.createdAt},
${row.updatedAt},
${row.archivedAt},
${row.deletedAt}
)
ON CONFLICT (thread_id)
@@ -67,6 +69,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
latest_turn_id = excluded.latest_turn_id,
created_at = excluded.created_at,
updated_at = excluded.updated_at,
archived_at = excluded.archived_at,
deleted_at = excluded.deleted_at
`,
});
@@ -88,6 +91,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
latest_turn_id AS "latestTurnId",
created_at AS "createdAt",
updated_at AS "updatedAt",
archived_at AS "archivedAt",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE thread_id = ${threadId}
@@ -111,6 +115,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
latest_turn_id AS "latestTurnId",
created_at AS "createdAt",
updated_at AS "updatedAt",
archived_at AS "archivedAt",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE project_id = ${projectId}
@@ -29,6 +29,8 @@ import Migration0013 from "./Migrations/013_ProjectionThreadProposedPlans.ts";
import Migration0014 from "./Migrations/014_ProjectionThreadProposedPlanImplementation.ts";
import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts";
import Migration0016 from "./Migrations/016_CanonicalizeModelSelections.ts";
import Migration0017 from "./Migrations/017_ProjectionThreadsArchivedAt.ts";
import Migration0018 from "./Migrations/018_ProjectionThreadsArchivedAtIndex.ts";
/**
* Migration loader with all migrations defined inline.
@@ -57,6 +59,8 @@ export const migrationEntries = [
[14, "ProjectionThreadProposedPlanImplementation", Migration0014],
[15, "ProjectionTurnsSourceProposedPlan", Migration0015],
[16, "CanonicalizeModelSelections", Migration0016],
[17, "ProjectionThreadsArchivedAt", Migration0017],
[18, "ProjectionThreadsArchivedAtIndex", Migration0018],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -128,6 +128,20 @@ layer("016_CanonicalizeModelSelections", (it) => {
'{"projectId":"project-2","title":"Fallback Project","workspaceRoot":"/tmp/project-2","defaultModel":"claude-opus-4-6","defaultModelOptions":{"codex":{"reasoningEffort":"low"}},"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-project-created-null-model',
'project',
'project-3',
1,
'project.created',
'2026-01-01T00:00:00.000Z',
'command-project-created-null-model',
NULL,
'correlation-project-created-null-model',
'user',
'{"projectId":"project-3","title":"Null Model Project","workspaceRoot":"/tmp/project-3","defaultModel":null,"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-thread-created',
'thread',
@@ -284,6 +298,16 @@ layer("016_CanonicalizeModelSelections", (it) => {
});
assert.deepStrictEqual(JSON.parse(eventRows[2]!.payloadJson), {
projectId: "project-3",
title: "Null Model Project",
workspaceRoot: "/tmp/project-3",
defaultModelSelection: null,
scripts: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
});
assert.deepStrictEqual(JSON.parse(eventRows[3]!.payloadJson), {
threadId: "thread-1",
projectId: "project-1",
title: "Thread",
@@ -303,7 +327,7 @@ layer("016_CanonicalizeModelSelections", (it) => {
updatedAt: "2026-01-01T00:00:00.000Z",
});
assert.deepStrictEqual(JSON.parse(eventRows[3]!.payloadJson), {
assert.deepStrictEqual(JSON.parse(eventRows[4]!.payloadJson), {
threadId: "thread-2",
projectId: "project-1",
title: "Fallback Thread",
@@ -322,7 +346,7 @@ layer("016_CanonicalizeModelSelections", (it) => {
updatedAt: "2026-01-01T00:00:00.000Z",
});
assert.deepStrictEqual(JSON.parse(eventRows[4]!.payloadJson), {
assert.deepStrictEqual(JSON.parse(eventRows[5]!.payloadJson), {
threadId: "thread-1",
turnId: "turn-1",
input: "hi",
@@ -336,7 +360,7 @@ layer("016_CanonicalizeModelSelections", (it) => {
deliveryMode: "buffered",
});
assert.deepStrictEqual(JSON.parse(eventRows[5]!.payloadJson), {
assert.deepStrictEqual(JSON.parse(eventRows[6]!.payloadJson), {
threadId: "thread-3",
projectId: "project-1",
title: "Ancient Thread",
@@ -0,0 +1,18 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
if (columns.some((column) => column.name === "archived_at")) {
return;
}
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN archived_at TEXT
`;
});
@@ -0,0 +1,11 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_threads_project_archived_at
ON projection_threads(project_id, archived_at)
`;
});
@@ -20,7 +20,7 @@ import * as Stream from "effect/Stream";
import * as Reactivity from "effect/unstable/reactivity/Reactivity";
import * as Client from "effect/unstable/sql/SqlClient";
import type { Connection } from "effect/unstable/sql/SqlConnection";
import { SqlError } from "effect/unstable/sql/SqlError";
import { SqlError, classifySqliteError } from "effect/unstable/sql/SqlError";
import * as Statement from "effect/unstable/sql/Statement";
const ATTR_DB_SYSTEM_NAME = "db.system.name";
@@ -109,7 +109,13 @@ const makeWithDatabase = (
lookup: (sql: string) =>
Effect.try({
try: () => db.prepare(sql),
catch: (cause) => new SqlError({ cause, message: "Failed to prepare statement" }),
catch: (cause) =>
new SqlError({
reason: classifySqliteError(cause, {
message: "Failed to prepare statement",
operation: "prepare",
}),
}),
}),
});
@@ -127,7 +133,14 @@ const makeWithDatabase = (
const result = statement.run(...(params as any));
return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
} catch (cause) {
return Effect.fail(new SqlError({ cause, message: "Failed to execute statement" }));
return Effect.fail(
new SqlError({
reason: classifySqliteError(cause, {
message: "Failed to execute statement",
operation: "execute",
}),
}),
);
}
});
@@ -150,7 +163,13 @@ const makeWithDatabase = (
statement.run(...(params as any));
return [];
},
catch: (cause) => new SqlError({ cause, message: "Failed to execute statement" }),
catch: (cause) =>
new SqlError({
reason: classifySqliteError(cause, {
message: "Failed to execute statement",
operation: "execute",
}),
}),
}),
(statement) =>
Effect.sync(() => {
@@ -32,6 +32,7 @@ export const ProjectionThread = Schema.Struct({
latestTurnId: Schema.NullOr(TurnId),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
archivedAt: Schema.NullOr(IsoDateTime),
deletedAt: Schema.NullOr(IsoDateTime),
});
export type ProjectionThread = typeof ProjectionThread.Type;
@@ -0,0 +1,835 @@
import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
import * as NodePath from "@effect/platform-node/NodePath";
import { assert, it } from "@effect/vitest";
import {
Deferred,
Effect,
Exit,
FileSystem,
Layer,
PlatformError,
Scope,
Sink,
Stream,
} from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
make as makeDesktopLauncher,
type DetachedSpawnInput,
type LaunchRuntimeOptions,
} from "./DesktopLauncher";
import { DesktopLauncher, DesktopLauncherSpawnError } from "../Services/DesktopLauncher";
const encoder = new TextEncoder();
interface SpawnCall {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly detached?: boolean | undefined;
readonly shell?: boolean | string | undefined;
readonly windowsVerbatimArguments?: boolean | undefined;
readonly windowsHide?: boolean | undefined;
readonly stdin?: unknown;
readonly stdout?: unknown;
readonly stderr?: unknown;
}
function decodePowerShellCommand(encoded: string): string {
return Buffer.from(encoded, "base64").toString("utf16le");
}
function platformSpawnError(message: string) {
return PlatformError.systemError({
_tag: "Unknown",
module: "ChildProcess",
method: "spawn",
description: message,
});
}
function spawnerLayer(
calls: Array<SpawnCall>,
handler: (call: SpawnCall) => {
readonly code?: number;
readonly fail?: string;
readonly awaitExit?: Deferred.Deferred<void>;
readonly onKill?: () => void;
} = () => ({
code: 0,
}),
) {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const standardCommand = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly options: {
readonly detached?: boolean;
readonly shell?: boolean | string;
readonly stdin?: unknown;
readonly stdout?: unknown;
readonly stderr?: unknown;
};
};
const call: SpawnCall = {
command: standardCommand.command,
args: [...standardCommand.args],
detached: standardCommand.options.detached,
shell: standardCommand.options.shell,
stdin: standardCommand.options.stdin,
stdout: standardCommand.options.stdout,
stderr: standardCommand.options.stderr,
};
calls.push(call);
const result = handler(call);
if (result.fail) {
return Effect.fail(platformSpawnError(result.fail));
}
let exited = false;
const exitCode = result.awaitExit
? Deferred.await(result.awaitExit).pipe(
Effect.tap(() =>
Effect.sync(() => {
exited = true;
}),
),
Effect.andThen(Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0))),
)
: Effect.sync(() => {
exited = true;
return ChildProcessSpawner.ExitCode(result.code ?? 0);
});
return Effect.succeed(
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(calls.length),
exitCode,
isRunning: Effect.succeed(false),
kill: () =>
Effect.sync(() => {
if (!exited) {
result.onKill?.();
}
}),
stdin: Sink.drain,
stdout: Stream.make(encoder.encode("")),
stderr: Stream.make(encoder.encode("")),
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
}),
);
}),
);
}
function spawnHarness(
calls: Array<SpawnCall>,
handler: (call: SpawnCall) => {
readonly code?: number;
readonly fail?: string;
readonly awaitExit?: Deferred.Deferred<void>;
readonly onKill?: () => void;
} = () => ({
code: 0,
}),
) {
return {
layer: spawnerLayer(calls, handler),
spawnDetached: (
input: DetachedSpawnInput,
context: {
readonly operation: string;
readonly target?: string;
readonly editor?: string;
},
) => {
const call: SpawnCall = {
command: input.command,
args: [...input.args],
detached: input.detached,
shell: input.shell,
windowsVerbatimArguments: input.windowsVerbatimArguments,
windowsHide: input.windowsHide,
stdin: input.stdin,
stdout: input.stdout,
stderr: input.stderr,
};
calls.push(call);
const result = handler(call);
return result.fail
? Effect.fail(
new DesktopLauncherSpawnError({
operation: context.operation,
command: input.command,
args: [...input.args],
...(context.target !== undefined ? { target: context.target } : {}),
...(context.editor !== undefined ? { editor: context.editor } : {}),
}),
)
: Effect.void;
},
} as const;
}
const provideOpen = (
options: LaunchRuntimeOptions,
harness: {
readonly layer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
readonly spawnDetached: (
input: DetachedSpawnInput,
context: {
readonly operation: string;
readonly target?: string;
readonly editor?: string;
},
) => Effect.Effect<void, DesktopLauncherSpawnError>;
},
) =>
Layer.effect(
DesktopLauncher,
makeDesktopLauncher({ ...options, spawnDetached: harness.spawnDetached }),
).pipe(Layer.provide(Layer.mergeAll(NodeFileSystem.layer, NodePath.layer, harness.layer)));
const runOpen = <A>(
options: LaunchRuntimeOptions,
harness: {
readonly layer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
readonly spawnDetached: (
input: DetachedSpawnInput,
context: {
readonly operation: string;
readonly target?: string;
readonly editor?: string;
},
) => Effect.Effect<void, DesktopLauncherSpawnError>;
},
effect: Effect.Effect<A, never, DesktopLauncher>,
) => effect.pipe(Effect.provide(provideOpen(options, harness)));
const readOpen = Effect.service(DesktopLauncher);
const writeExecutable = (filePath: string) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* fs.writeFileString(filePath, "#!/bin/sh\nexit 0\n");
yield* fs.chmod(filePath, 0o755);
});
it.effect("getAvailableEditors detects installed editors through the service", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-editors-" });
yield* fs.writeFileString(`${dir}/code-insiders.CMD`, "@echo off\r\n");
yield* fs.writeFileString(`${dir}/codium.CMD`, "@echo off\r\n");
yield* fs.writeFileString(`${dir}/explorer.CMD`, "@echo off\r\n");
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "win32",
env: {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
},
spawnHarness(calls),
readOpen,
);
const editors = yield* open.getAvailableEditors;
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
assert.deepEqual(calls, []);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("getAvailableEditors does not advertise WSL file-manager from PowerShell alone", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-wsl-editors-" });
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
recursive: true,
});
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "linux",
env: {
PATH: `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`,
WSL_DISTRO_NAME: "Ubuntu",
},
isWsl: true,
isInsideContainer: false,
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
},
spawnHarness(calls),
readOpen,
);
const editors = yield* open.getAvailableEditors;
assert.equal(editors.includes("file-manager"), false);
assert.deepEqual(calls, []);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor uses --goto for editors that support it", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-cursor-" });
yield* writeExecutable(`${dir}/cursor`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "darwin",
env: { PATH: dir },
},
spawnHarness(calls),
readOpen,
);
yield* open.openInEditor({
cwd: "/tmp/workspace/src/open.ts:71:5",
editor: "cursor",
});
assert.deepEqual(calls, [
{
command: `${dir}/cursor`,
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
detached: true,
shell: false,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor uses explorer with a VS Code protocol target on Windows", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-vscode-win32-" });
yield* fs.writeFileString(`${dir}/explorer.exe`, "MZ");
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "win32",
env: {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
},
spawnHarness(calls),
readOpen,
);
yield* open.openInEditor({
cwd: "C:\\work\\100% real\\file.ts:12:4",
editor: "vscode",
});
assert.deepEqual(calls, [
{
command: `${dir}/explorer.exe`,
args: ["vscode://file/C:/work/100%25%20real/file.ts:12:4"],
detached: true,
shell: false,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor detached launches bypass the scoped child-process spawner", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-zed-detached-" });
yield* writeExecutable(`${dir}/zed`);
const calls: Array<SpawnCall> = [];
const harness = spawnHarness(calls);
yield* Effect.acquireUseRelease(
Scope.make("sequential"),
(scope) =>
Effect.gen(function* () {
const runtimeServices = yield* Layer.build(
provideOpen(
{
platform: "darwin",
env: { PATH: dir },
},
harness,
),
).pipe(Scope.provide(scope));
const open = yield* readOpen.pipe(Effect.provide(runtimeServices), Scope.provide(scope));
yield* open.openInEditor({
cwd: "/tmp/workspace",
editor: "zed",
});
}),
(scope) => Scope.close(scope, Exit.void),
);
assert.deepEqual(calls, [
{
command: `${dir}/zed`,
args: ["/tmp/workspace"],
detached: true,
shell: false,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor uses the default opener for file-manager on macOS", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-macos-" });
yield* writeExecutable(`${dir}/open`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "darwin",
env: { PATH: dir },
},
spawnHarness(calls),
readOpen,
);
yield* open.openInEditor({
cwd: "/tmp/workspace",
editor: "file-manager",
});
assert.deepEqual(calls, [
{
command: `${dir}/open`,
args: ["/tmp/workspace"],
detached: undefined,
shell: false,
stdin: undefined,
stdout: undefined,
stderr: undefined,
},
]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openBrowser uses macOS open flags and app arguments", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-macos-" });
yield* writeExecutable(`${dir}/open`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "darwin",
env: { PATH: dir },
},
spawnHarness(calls),
readOpen,
);
yield* open.openBrowser("https://example.com", {
wait: true,
background: true,
newInstance: true,
app: {
name: "google chrome",
arguments: ["--profile-directory=Work"],
},
});
assert.deepEqual(calls, [
{
command: `${dir}/open`,
args: [
"--wait-apps",
"--background",
"--new",
"-a",
"google chrome",
"https://example.com",
"--args",
"--profile-directory=Work",
],
detached: undefined,
shell: false,
stdin: undefined,
stdout: undefined,
stderr: undefined,
},
]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openBrowser uses PowerShell on win32", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-win32-" });
yield* fs.writeFileString(`${dir}/powershell.exe`, "MZ");
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "win32",
env: {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
},
spawnHarness(calls),
readOpen,
);
yield* open.openBrowser("https://example.com");
assert.equal(calls.length, 1);
assert.equal(calls[0]?.command, `${dir}/powershell.exe`);
assert.equal(calls[0]?.args.at(-2), "-EncodedCommand");
assert.equal(
decodePowerShellCommand(calls[0]?.args.at(-1) ?? ""),
"Start 'https://example.com'",
);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openBrowser detaches direct app launches on win32 when not waiting", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-win32-app-" });
yield* fs.writeFileString(`${dir}/chrome.exe`, "MZ");
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "win32",
env: {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
},
spawnHarness(calls),
readOpen,
);
yield* open.openBrowser("https://example.com", {
app: {
name: "chrome",
arguments: ["--profile-directory=Work"],
},
});
assert.equal(calls.length, 1);
assert.equal(calls[0]?.command.toLowerCase(), `${dir}/chrome.exe`.toLowerCase());
assert.deepEqual(calls[0]?.args, ["--profile-directory=Work", "https://example.com"]);
assert.equal(calls[0]?.detached, true);
assert.equal(calls[0]?.shell, false);
assert.equal(calls[0]?.stdin, "ignore");
assert.equal(calls[0]?.stdout, "ignore");
assert.equal(calls[0]?.stderr, "ignore");
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openBrowser preserves non-zero exit errors for waited direct app launches", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-linux-app-wait-" });
yield* writeExecutable(`${dir}/firefox`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "linux",
env: { PATH: dir },
},
spawnHarness(calls, () => ({ code: 23 })),
readOpen,
);
const error = yield* open
.openBrowser("https://example.com", {
wait: true,
app: { name: "firefox" },
})
.pipe(Effect.flip);
assert.equal(error._tag, "DesktopLauncherNonZeroExitError");
if (error._tag !== "DesktopLauncherNonZeroExitError") {
throw new Error(`Unexpected error tag: ${error._tag}`);
}
assert.equal(error.exitCode, 23);
assert.equal(error.command, `${dir}/firefox`);
assert.deepEqual(error.args, ["https://example.com"]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openBrowser falls back from WSL PowerShell to xdg-open", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-wsl-" });
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
recursive: true,
});
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
yield* writeExecutable(`${dir}/xdg-open`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "linux",
env: {
PATH: `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`,
WSL_DISTRO_NAME: "Ubuntu",
},
isWsl: true,
isInsideContainer: false,
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
},
spawnHarness(calls, (call) =>
call.command.includes("powershell")
? { fail: "powershell unavailable" }
: {
code: 0,
},
),
readOpen,
);
yield* open.openBrowser("https://example.com");
assert.equal(calls[0]?.command.includes("powershell"), true);
assert.equal(calls[1]?.command, `${dir}/xdg-open`);
assert.deepEqual(calls[1]?.args, ["https://example.com"]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openBrowser skips WSL PowerShell when process env marks a container", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-wsl-container-" });
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
recursive: true,
});
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
yield* writeExecutable(`${dir}/xdg-open`);
const calls: Array<SpawnCall> = [];
const originalValues = new Map<string, string | undefined>();
const setEnv = (key: string, value: string | undefined) => {
if (!originalValues.has(key)) {
originalValues.set(key, process.env[key]);
}
if (value === undefined) {
delete process.env[key];
return;
}
process.env[key] = value;
};
const restoreEnv = () => {
for (const [key, value] of originalValues) {
if (value === undefined) {
delete process.env[key];
} else {
process.env[key] = value;
}
}
};
try {
setEnv("PATH", `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`);
setEnv("WSL_DISTRO_NAME", "Ubuntu");
setEnv("CONTAINER", "docker");
const open = yield* runOpen(
{
platform: "linux",
isWsl: true,
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
},
spawnHarness(calls),
readOpen,
);
yield* open.openBrowser("https://example.com");
} finally {
restoreEnv();
}
assert.deepEqual(calls, [
{
command: `${dir}/xdg-open`,
args: ["https://example.com"],
detached: true,
shell: false,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor uses xdg-open first for WSL file-manager paths", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-wsl-file-manager-" });
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
recursive: true,
});
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
yield* writeExecutable(`${dir}/xdg-open`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "linux",
env: {
PATH: `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`,
WSL_DISTRO_NAME: "Ubuntu",
},
isWsl: true,
isInsideContainer: false,
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
},
spawnHarness(calls),
readOpen,
);
yield* open.openInEditor({
cwd: "/home/julius/workspace",
editor: "file-manager",
});
assert.deepEqual(calls, [
{
command: `${dir}/xdg-open`,
args: ["/home/julius/workspace"],
detached: true,
shell: false,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor fails when the editor command is unavailable", () =>
Effect.gen(function* () {
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "darwin",
env: { PATH: "" },
},
spawnHarness(calls),
readOpen,
);
const error = yield* open
.openInEditor({
cwd: "/tmp/workspace",
editor: "cursor",
})
.pipe(Effect.flip);
assert.equal(error._tag, "DesktopLauncherCommandNotFoundError");
assert.equal(
error.message,
"Desktop launcher command not found in openInEditor: cursor for editor cursor",
);
assert.deepEqual(calls, []);
}),
);
it.effect("openBrowser rejects an empty target with a validation error", () =>
Effect.gen(function* () {
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "darwin",
env: { PATH: "" },
},
spawnHarness(calls),
readOpen,
);
const error = yield* open.openBrowser(" ").pipe(Effect.flip);
assert.equal(error._tag, "DesktopLauncherValidationError");
assert.equal(
error.message,
"Desktop launcher validation failed in openBrowser: target must not be empty",
);
assert.deepEqual(calls, []);
}),
);
it.effect("openBrowser reports exhausted fallback attempts when multiple launchers fail", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-fallback-errors-" });
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
recursive: true,
});
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
yield* writeExecutable(`${dir}/xdg-open`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "linux",
env: {
PATH: `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`,
WSL_DISTRO_NAME: "Ubuntu",
},
isWsl: true,
isInsideContainer: false,
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
},
spawnHarness(calls, () => ({ fail: "launcher unavailable" })),
readOpen,
);
const error = yield* open.openBrowser("https://example.com").pipe(Effect.flip);
assert.equal(error._tag, "DesktopLauncherLaunchAttemptsExhaustedError");
if (error._tag !== "DesktopLauncherLaunchAttemptsExhaustedError") {
throw new Error(`Unexpected error tag: ${error._tag}`);
}
assert.deepEqual(
error.attempts.map((attempt) => attempt.reason),
["spawnFailed", "spawnFailed"],
);
assert.deepEqual(
error.attempts.map((attempt) => attempt.command.includes("powershell")),
[true, false],
);
assert.deepEqual(
calls.map((call) => call.command.includes("powershell")),
[true, false],
);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
@@ -0,0 +1,998 @@
/**
* Open - Browser/editor launch service interface.
*
* Owns process launch helpers for opening URLs in a browser, workspace paths in
* a configured editor, and generic external targets through the platform's
* default opener.
*
* @module Open
*/
import OS from "node:os";
import { spawn as spawnNodeChildProcess } from "node:child_process";
import { pathToFileURL } from "node:url";
import { EDITORS, type EditorId } from "@t3tools/contracts";
import { Array, Effect, FileSystem, Layer, Option, Path, Scope } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
isWindowsBatchShim,
makeWindowsCmdSpawnArguments,
resolveWindowsCommandShell,
} from "../windowsCommand";
import {
DesktopLauncherCommandNotFoundError,
DesktopLauncherDiscoveryError,
DesktopLauncherLaunchAttemptsExhaustedError,
DesktopLauncherNonZeroExitError,
DesktopLauncherSpawnError,
DesktopLauncherUnknownEditorError,
DesktopLauncherValidationError,
DesktopLauncher,
type DesktopLauncherShape,
type OpenApplicationInput,
type OpenExternalInput,
} from "../Services/DesktopLauncher";
export interface DetachedSpawnInput {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly detached?: boolean;
readonly shell?: boolean;
readonly windowsVerbatimArguments?: boolean;
readonly windowsHide?: boolean;
readonly stdin?: "ignore";
readonly stdout?: "ignore";
readonly stderr?: "ignore";
}
type DesktopLauncherOperation =
| "getAvailableEditors"
| "openBrowser"
| "openExternal"
| "openInEditor";
interface LaunchContext {
readonly operation: DesktopLauncherOperation;
readonly target?: string;
readonly editor?: EditorId;
}
export interface LaunchRuntimeOptions {
readonly platform?: NodeJS.Platform;
readonly env?: NodeJS.ProcessEnv;
readonly isWsl?: boolean;
readonly isInsideContainer?: boolean;
readonly powerShellCommand?: string;
readonly spawnDetached?: (
input: DetachedSpawnInput,
context: LaunchContext,
) => Effect.Effect<void, DesktopLauncherSpawnError>;
}
interface LaunchRuntime {
readonly platform: NodeJS.Platform;
readonly env: NodeJS.ProcessEnv;
readonly isWsl: boolean;
readonly isInsideContainer: boolean;
readonly powerShellCandidates: ReadonlyArray<string>;
readonly windowsPathExtensions: ReadonlyArray<string>;
}
interface LaunchPlan {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly wait: boolean;
readonly allowNonzeroExitCode: boolean;
readonly detached?: boolean;
readonly shell?: boolean;
readonly stdio?: "ignore";
}
interface ResolvedCommand {
readonly path: string;
readonly usesCmdWrapper: boolean;
}
interface OpenApplicationCandidate {
readonly name: string;
readonly arguments: ReadonlyArray<string>;
}
interface LaunchAttemptFailure {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly reason: "commandNotFound" | "spawnFailed" | "nonZeroExit";
readonly detail: string;
readonly exitCode?: number;
}
type LaunchAttemptError =
| DesktopLauncherCommandNotFoundError
| DesktopLauncherNonZeroExitError
| DesktopLauncherSpawnError;
type LaunchPlanError = LaunchAttemptError | DesktopLauncherLaunchAttemptsExhaustedError;
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
const WINDOWS_POWERSHELL_CANDIDATES = ["powershell.exe", "powershell", "pwsh.exe", "pwsh"] as const;
const WSL_POWERSHELL_CANDIDATES = [
"/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe",
"/mnt/c/Program Files/PowerShell/7/pwsh.exe",
"powershell.exe",
"pwsh.exe",
] as const;
const WINDOWS_EDITOR_URI_SCHEMES: Partial<Record<EditorId, string>> = {
vscode: "vscode",
"vscode-insiders": "vscode-insiders",
vscodium: "vscodium",
};
function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean {
return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target);
}
function stripWrappingQuotes(value: string): string {
return value.replace(/^"+|"+$/g, "");
}
function splitLineColumnSuffix(target: string): {
readonly filePath: string;
readonly suffix: string;
} {
const match = target.match(LINE_COLUMN_SUFFIX_PATTERN);
if (!match) {
return {
filePath: target,
suffix: "",
};
}
return {
filePath: target.slice(0, -match[0].length),
suffix: match[0],
};
}
function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
return env.PATH ?? env.Path ?? env.path ?? "";
}
function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
const rawValue = env.PATHEXT;
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
if (!rawValue) return fallback;
const parsed = rawValue
.split(";")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
return parsed.length > 0 ? Array.dedupe(parsed) : fallback;
}
function resolveCommandCandidates(
command: string,
runtime: LaunchRuntime,
pathService: Path.Path,
): ReadonlyArray<string> {
if (runtime.platform !== "win32") return [command];
const extension = pathService.extname(command);
const normalizedExtension = extension.toUpperCase();
if (extension.length > 0 && runtime.windowsPathExtensions.includes(normalizedExtension)) {
const commandWithoutExtension = command.slice(0, -extension.length);
return Array.dedupe([
command,
`${commandWithoutExtension}${normalizedExtension}`,
`${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
]);
}
const candidates: string[] = [];
for (const extensionName of runtime.windowsPathExtensions) {
candidates.push(`${command}${extensionName}`);
candidates.push(`${command}${extensionName.toLowerCase()}`);
}
return Array.dedupe(candidates);
}
function resolvePathDelimiter(platform: NodeJS.Platform): string {
return platform === "win32" ? ";" : ":";
}
function detectWsl(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): boolean {
if (platform !== "linux") return false;
if (typeof env.WSL_DISTRO_NAME === "string" || typeof env.WSL_INTEROP === "string") {
return true;
}
return OS.release().toLowerCase().includes("microsoft");
}
function quotePowerShellValue(value: string): string {
return `'${value.replaceAll("'", "''")}'`;
}
function quotePowerShellArgument(value: string): string {
return `"\`"${value.replaceAll("`", "``").replaceAll('"', '`"')}\`""`;
}
function encodePowerShellCommand(command: string): string {
return Buffer.from(command, "utf16le").toString("base64");
}
function normalizeAppCandidates(
app: OpenApplicationInput | ReadonlyArray<OpenApplicationInput> | undefined,
): ReadonlyArray<OpenApplicationCandidate | undefined> {
if (!app) return [undefined];
const apps = Array.ensure(app);
const candidates: Array<OpenApplicationCandidate> = [];
for (const appDef of apps) {
const names = Array.ensure(appDef.name);
for (const name of names) {
candidates.push({ name, arguments: appDef.arguments ?? [] });
}
}
return candidates.length > 0 ? candidates : [undefined];
}
function isUriLikeTarget(target: string): boolean {
return /^[A-Za-z][A-Za-z\d+.-]*:/.test(target);
}
function shouldPreferWindowsOpenerOnWsl(input: OpenExternalInput, runtime: LaunchRuntime): boolean {
return runtime.isWsl && !runtime.isInsideContainer && isUriLikeTarget(input.target);
}
function makeWindowsEditorProtocolTarget(editor: EditorId, target: string): string | undefined {
const scheme = WINDOWS_EDITOR_URI_SCHEMES[editor];
if (!scheme) return undefined;
const { filePath, suffix } = splitLineColumnSuffix(target);
const fileUrl = pathToFileURL(filePath).href;
const fileTarget = fileUrl.startsWith("file:///")
? fileUrl.slice("file:///".length)
: fileUrl.replace(/^file:\/\//, "");
return `${scheme}://file/${fileTarget}${suffix}`;
}
function makeLaunchPlan(
command: string,
args: ReadonlyArray<string>,
options: {
readonly wait: boolean;
readonly allowNonzeroExitCode: boolean;
readonly detached?: boolean;
readonly shell?: boolean;
readonly stdio?: "ignore";
},
): LaunchPlan {
return {
command,
args,
wait: options.wait,
allowNonzeroExitCode: options.allowNonzeroExitCode,
shell: options.shell ?? false,
...(options.detached !== undefined ? { detached: options.detached } : {}),
...(options.stdio !== undefined ? { stdio: options.stdio } : {}),
};
}
function makeDarwinDefaultPlan(input: OpenExternalInput): LaunchPlan {
const args: string[] = [];
const wait = input.wait ?? false;
if (wait) args.push("--wait-apps");
if (input.background) args.push("--background");
if (input.newInstance) args.push("--new");
args.push(input.target);
return makeLaunchPlan("open", args, {
wait,
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
shell: false,
});
}
function makeDarwinApplicationPlan(
input: OpenExternalInput,
app: OpenApplicationCandidate,
): LaunchPlan {
const args: string[] = [];
const wait = input.wait ?? false;
if (wait) args.push("--wait-apps");
if (input.background) args.push("--background");
if (input.newInstance) args.push("--new");
args.push("-a", app.name);
args.push(input.target);
if (app.arguments.length > 0) {
args.push("--args", ...app.arguments);
}
return makeLaunchPlan("open", args, {
wait,
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
shell: false,
});
}
function makePowerShellPlan(input: OpenExternalInput, powerShellCommand: string): LaunchPlan {
const encodedParts = ["Start"];
const wait = input.wait ?? false;
if (wait) encodedParts.push("-Wait");
encodedParts.push(quotePowerShellValue(input.target));
return makeLaunchPlan(
powerShellCommand,
[
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-EncodedCommand",
encodePowerShellCommand(encodedParts.join(" ")),
],
{
wait,
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
shell: false,
},
);
}
function makePowerShellStartProcessArgs(
commandPath: string,
args: ReadonlyArray<string>,
): ReadonlyArray<string> {
const argumentList =
args.length > 0 ? ` -ArgumentList ${args.map(quotePowerShellArgument).join(",")}` : "";
const command = `Start ${quotePowerShellArgument(commandPath)}${argumentList} -WindowStyle Hidden`;
return [
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-EncodedCommand",
encodePowerShellCommand(command),
];
}
function makeLinuxDefaultPlan(input: OpenExternalInput): LaunchPlan {
const wait = input.wait ?? false;
return makeLaunchPlan("xdg-open", [input.target], {
wait,
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
detached: !wait,
...(wait ? {} : { stdio: "ignore" as const }),
shell: false,
});
}
function makeWindowsExplorerPlan(input: OpenExternalInput): LaunchPlan {
return makeLaunchPlan("explorer", [input.target], {
wait: false,
allowNonzeroExitCode: false,
detached: true,
stdio: "ignore",
shell: false,
});
}
function makeDirectApplicationPlan(
input: OpenExternalInput,
app: OpenApplicationCandidate,
): LaunchPlan {
const wait = input.wait ?? false;
return makeLaunchPlan(app.name, [...app.arguments, input.target], {
wait,
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
detached: !wait,
...(wait ? {} : { stdio: "ignore" as const }),
shell: false,
});
}
function resolveExternalPlans(
input: OpenExternalInput,
runtime: LaunchRuntime,
): ReadonlyArray<LaunchPlan> {
const appCandidates = normalizeAppCandidates(input.app);
const plans: LaunchPlan[] = [];
const preferWindowsOpenerOnWsl = shouldPreferWindowsOpenerOnWsl(input, runtime);
for (const app of appCandidates) {
if (app) {
if (runtime.platform === "darwin") {
plans.push(makeDarwinApplicationPlan(input, app));
} else {
plans.push(makeDirectApplicationPlan(input, app));
}
continue;
}
if (runtime.platform === "darwin") {
plans.push(makeDarwinDefaultPlan(input));
continue;
}
if (runtime.platform === "win32" || preferWindowsOpenerOnWsl) {
for (const powerShellCommand of runtime.powerShellCandidates) {
plans.push(makePowerShellPlan(input, powerShellCommand));
}
}
if (runtime.platform === "win32") {
if (!(input.wait ?? false)) {
plans.push(makeWindowsExplorerPlan(input));
}
continue;
}
plans.push(makeLinuxDefaultPlan(input));
}
return plans;
}
function resolveSpawnInput(
runtime: LaunchRuntime,
plan: LaunchPlan,
resolvedCommand: ResolvedCommand,
startProcessLauncher: string | undefined,
): DetachedSpawnInput {
if (plan.detached && resolvedCommand.usesCmdWrapper && startProcessLauncher !== undefined) {
return {
command: startProcessLauncher,
args: makePowerShellStartProcessArgs(resolvedCommand.path, plan.args),
...(plan.detached !== undefined ? { detached: plan.detached } : {}),
...(plan.shell !== undefined ? { shell: plan.shell } : {}),
...(runtime.platform === "win32"
? { windowsVerbatimArguments: true, windowsHide: true }
: {}),
...(plan.stdio === "ignore"
? {
stdin: "ignore" as const,
stdout: "ignore" as const,
stderr: "ignore" as const,
}
: {}),
};
}
const windowsHide = runtime.platform === "win32" && plan.detached ? true : undefined;
return {
command: resolvedCommand.usesCmdWrapper
? resolveWindowsCommandShell(runtime.env)
: resolvedCommand.path,
args: resolvedCommand.usesCmdWrapper
? makeWindowsCmdSpawnArguments(resolvedCommand.path, plan.args)
: [...plan.args],
...(plan.detached !== undefined ? { detached: plan.detached } : {}),
...(plan.shell !== undefined ? { shell: plan.shell } : {}),
...(windowsHide ? { windowsHide } : {}),
...(resolvedCommand.usesCmdWrapper ? { windowsVerbatimArguments: true } : {}),
...(plan.stdio === "ignore"
? {
stdin: "ignore" as const,
stdout: "ignore" as const,
stderr: "ignore" as const,
}
: {}),
};
}
function makeCommandNotFoundError(
context: LaunchContext,
command: string,
): DesktopLauncherCommandNotFoundError {
return new DesktopLauncherCommandNotFoundError({
operation: context.operation,
command,
...(context.target !== undefined ? { target: context.target } : {}),
...(context.editor !== undefined ? { editor: context.editor } : {}),
});
}
function makeSpawnError(
context: LaunchContext,
command: string,
args: ReadonlyArray<string>,
cause?: unknown,
): DesktopLauncherSpawnError {
return new DesktopLauncherSpawnError({
operation: context.operation,
command,
args: [...args],
...(context.target !== undefined ? { target: context.target } : {}),
...(context.editor !== undefined ? { editor: context.editor } : {}),
...(cause !== undefined ? { cause } : {}),
});
}
function makeNonZeroExitError(
context: LaunchContext,
command: string,
args: ReadonlyArray<string>,
exitCode: number,
): DesktopLauncherNonZeroExitError {
return new DesktopLauncherNonZeroExitError({
operation: context.operation,
command,
args: [...args],
exitCode,
...(context.target !== undefined ? { target: context.target } : {}),
...(context.editor !== undefined ? { editor: context.editor } : {}),
});
}
function toLaunchAttemptFailure(error: LaunchAttemptError): LaunchAttemptFailure {
switch (error._tag) {
case "DesktopLauncherCommandNotFoundError":
return {
command: error.command,
args: [],
reason: "commandNotFound",
detail: error.message,
};
case "DesktopLauncherSpawnError":
return {
command: error.command,
args: error.args,
reason: "spawnFailed",
detail: error.message,
};
case "DesktopLauncherNonZeroExitError":
return {
command: error.command,
args: error.args,
reason: "nonZeroExit",
detail: error.message,
exitCode: error.exitCode,
};
}
}
/**
* Detached GUI launches must call `unref()` after spawn. The Effect
* `ChildProcessSpawner` owns spawned handles through scope finalizers and does
* not expose `unref()`, which means it cannot provide true fire-and-forget
* behavior for editor / file-manager launches.
*/
const DETACHED_SPAWN_GRACE_MS = 500;
function defaultSpawnDetached(
input: DetachedSpawnInput,
context: LaunchContext,
): Effect.Effect<void, DesktopLauncherSpawnError> {
return Effect.try({
try: () =>
spawnNodeChildProcess(input.command, [...input.args], {
...(input.detached !== undefined ? { detached: input.detached } : {}),
...(input.shell !== undefined ? { shell: input.shell } : {}),
...(input.windowsHide !== undefined ? { windowsHide: input.windowsHide } : {}),
...(input.windowsVerbatimArguments !== undefined
? { windowsVerbatimArguments: input.windowsVerbatimArguments }
: {}),
...(input.stdin === "ignore" && input.stdout === "ignore" && input.stderr === "ignore"
? { stdio: "ignore" as const }
: {}),
}),
catch: (cause) => makeSpawnError(context, input.command, input.args, cause),
}).pipe(
Effect.flatMap((childProcess) =>
Effect.callback<void, DesktopLauncherSpawnError>((resume) => {
let graceTimer: ReturnType<typeof setTimeout> | undefined;
const onEarlyExit = (code: number | null) => {
if (graceTimer !== undefined) clearTimeout(graceTimer);
if (code !== null && code !== 0) {
resume(
Effect.fail(
makeSpawnError(
context,
input.command,
input.args,
new Error(`Process exited immediately with code ${code}`),
),
),
);
} else {
childProcess.unref();
resume(Effect.void);
}
};
const onError = (error: Error) => {
childProcess.off("spawn", onSpawn);
resume(Effect.fail(makeSpawnError(context, input.command, input.args, error)));
};
const onSpawn = () => {
childProcess.off("error", onError);
childProcess.once("exit", onEarlyExit);
graceTimer = setTimeout(() => {
childProcess.off("exit", onEarlyExit);
childProcess.unref();
resume(Effect.void);
}, DETACHED_SPAWN_GRACE_MS);
};
childProcess.once("error", onError);
childProcess.once("spawn", onSpawn);
return Effect.sync(() => {
if (graceTimer !== undefined) clearTimeout(graceTimer);
childProcess.off("error", onError);
childProcess.off("spawn", onSpawn);
childProcess.off("exit", onEarlyExit);
});
}),
),
);
}
export const make = Effect.fn("makeDesktopLauncher")(function* (
options: LaunchRuntimeOptions = {},
) {
const fileSystem = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const runtimeEnv = options.env ?? process.env;
const runtimePlatform = options.platform ?? process.platform;
const isWsl = options.isWsl ?? detectWsl(runtimePlatform, runtimeEnv);
const isInsideContainer =
options.isInsideContainer ??
(typeof runtimeEnv.CONTAINER === "string" ||
typeof runtimeEnv.container === "string" ||
typeof runtimeEnv.KUBERNETES_SERVICE_HOST === "string"
? true
: yield* fileSystem.exists("/.dockerenv").pipe(Effect.catch(() => Effect.succeed(false))));
const runtime: LaunchRuntime = {
platform: runtimePlatform,
env: runtimeEnv,
isWsl,
isInsideContainer,
powerShellCandidates:
options.powerShellCommand !== undefined
? [options.powerShellCommand]
: isWsl
? WSL_POWERSHELL_CANDIDATES
: WINDOWS_POWERSHELL_CANDIDATES,
windowsPathExtensions: resolveWindowsPathExtensions(runtimeEnv),
};
const resolveCommand = Effect.fn("resolveCommand")(function* (
command: string,
): Effect.fn.Return<Option.Option<ResolvedCommand>> {
const candidates = resolveCommandCandidates(command, runtime, pathService);
const resolveExecutableFile = Effect.fn("resolveExecutableFile")(function* (
filePath: string,
): Effect.fn.Return<Option.Option<ResolvedCommand>> {
const info = yield* fileSystem.stat(filePath).pipe(Effect.option);
if (Option.isNone(info) || info.value.type !== "File") return Option.none();
if (runtime.platform === "win32") {
const extension = pathService.extname(filePath);
if (
extension.length === 0 ||
!runtime.windowsPathExtensions.includes(extension.toUpperCase())
) {
return Option.none();
}
return Option.some({
path: filePath,
usesCmdWrapper: isWindowsBatchShim(filePath),
} satisfies ResolvedCommand);
}
return (info.value.mode & 0o111) !== 0
? Option.some({
path: filePath,
usesCmdWrapper: false,
} satisfies ResolvedCommand)
: Option.none();
});
if (command.includes("/") || command.includes("\\")) {
for (const candidate of candidates) {
const resolved = yield* resolveExecutableFile(candidate);
if (Option.isSome(resolved)) return resolved;
}
return Option.none();
}
const pathValue = resolvePathEnvironmentVariable(runtime.env);
if (pathValue.length === 0) return Option.none();
const pathEntries = pathValue
.split(resolvePathDelimiter(runtime.platform))
.map((entry) => stripWrappingQuotes(entry.trim()))
.filter((entry) => entry.length > 0);
for (const pathEntry of pathEntries) {
for (const candidate of candidates) {
const resolved = yield* resolveExecutableFile(pathService.join(pathEntry, candidate));
if (Option.isSome(resolved)) {
return resolved;
}
}
}
return Option.none();
});
const commandAvailable = (command: string) =>
resolveCommand(command).pipe(Effect.map(Option.isSome));
const startProcessLauncher = yield* Effect.gen(function* () {
for (const candidate of runtime.powerShellCandidates) {
const resolved = yield* resolveCommand(candidate);
if (Option.isSome(resolved)) {
return resolved.value.path;
}
}
return undefined;
});
const fileManagerAvailable = Effect.gen(function* () {
const candidates =
runtime.platform === "darwin"
? ["open"]
: runtime.platform === "win32"
? [...runtime.powerShellCandidates, "explorer"]
: ["xdg-open"];
for (const candidate of candidates) {
if (yield* commandAvailable(candidate)) {
return true;
}
}
return false;
});
const getAvailableEditors: DesktopLauncherShape["getAvailableEditors"] = Effect.gen(function* () {
const available: EditorId[] = [];
for (const editor of EDITORS) {
if (editor.id === "file-manager") {
if (yield* fileManagerAvailable) {
available.push(editor.id);
}
continue;
}
if (editor.command && (yield* commandAvailable(editor.command))) {
available.push(editor.id);
}
}
return available;
}).pipe(
Effect.mapError(
(cause) =>
new DesktopLauncherDiscoveryError({
operation: "getAvailableEditors",
detail: "failed to resolve available editors",
cause,
}),
),
);
const spawnPlan = (
plan: LaunchPlan,
resolvedCommand: ResolvedCommand,
context: LaunchContext,
) => {
const input = resolveSpawnInput(runtime, plan, resolvedCommand, startProcessLauncher);
return spawner
.spawn(
ChildProcess.make(input.command, [...input.args], {
detached: plan.detached,
shell: plan.shell,
...(plan.stdio === "ignore"
? {
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
}
: {}),
}),
)
.pipe(Effect.mapError((cause) => makeSpawnError(context, input.command, input.args, cause)));
};
const spawnDetached = options.spawnDetached ?? defaultSpawnDetached;
const waitForExit = (
plan: LaunchPlan,
context: LaunchContext,
spawnInput: DetachedSpawnInput,
handle: ChildProcessSpawner.ChildProcessHandle,
) =>
handle.exitCode.pipe(
Effect.mapError((cause) =>
makeSpawnError(context, spawnInput.command, spawnInput.args, cause),
),
Effect.flatMap((exitCode) =>
!plan.allowNonzeroExitCode && exitCode !== 0
? Effect.fail(
makeNonZeroExitError(context, spawnInput.command, spawnInput.args, exitCode),
)
: Effect.void,
),
);
const runWaitedPlan = (
plan: LaunchPlan,
resolvedCommand: ResolvedCommand,
context: LaunchContext,
) =>
Effect.acquireUseRelease(
Scope.make("sequential"),
(scope) =>
Effect.gen(function* () {
const spawnInput = resolveSpawnInput(
runtime,
plan,
resolvedCommand,
startProcessLauncher,
);
const handle = yield* spawnPlan(plan, resolvedCommand, context).pipe(
Scope.provide(scope),
);
yield* waitForExit(plan, context, spawnInput, handle);
}),
(scope, exit) => Scope.close(scope, exit),
);
const runDetachedPlan = (
plan: LaunchPlan,
resolvedCommand: ResolvedCommand,
context: LaunchContext,
) =>
spawnDetached(resolveSpawnInput(runtime, plan, resolvedCommand, startProcessLauncher), context);
const runPlan = (plan: LaunchPlan, resolvedCommand: ResolvedCommand, context: LaunchContext) =>
plan.wait
? runWaitedPlan(plan, resolvedCommand, context)
: runDetachedPlan(plan, resolvedCommand, context);
const runFirstAvailablePlan = Effect.fn("runFirstAvailablePlan")(function* (
plans: ReadonlyArray<LaunchPlan>,
context: LaunchContext,
): Effect.fn.Return<void, LaunchPlanError> {
const failures: LaunchAttemptError[] = [];
for (const plan of plans) {
const resolvedCommand = yield* resolveCommand(plan.command);
if (Option.isNone(resolvedCommand)) {
failures.push(makeCommandNotFoundError(context, plan.command));
continue;
}
const attempt = yield* Effect.result(runPlan(plan, resolvedCommand.value, context));
if (attempt._tag === "Success") {
return;
}
failures.push(attempt.failure);
}
const [firstFailure] = failures;
if (failures.length === 1 && firstFailure) {
return yield* firstFailure;
}
return yield* new DesktopLauncherLaunchAttemptsExhaustedError({
operation: context.operation,
...(context.target !== undefined ? { target: context.target } : {}),
...(context.editor !== undefined ? { editor: context.editor } : {}),
attempts: failures.map(toLaunchAttemptFailure),
});
});
const openTarget = Effect.fn("openTarget")(function* (
operation: Extract<DesktopLauncherOperation, "openBrowser" | "openExternal" | "openInEditor">,
input: OpenExternalInput,
context: Omit<LaunchContext, "operation"> = {},
) {
if (input.target.trim().length === 0) {
return yield* new DesktopLauncherValidationError({
operation,
detail: "target must not be empty",
target: input.target,
});
}
return yield* runFirstAvailablePlan(resolveExternalPlans(input, runtime), {
operation,
target: input.target,
...(context.editor !== undefined ? { editor: context.editor } : {}),
});
});
const openExternal: DesktopLauncherShape["openExternal"] = Effect.fn("openExternal")(
function* (input) {
return yield* openTarget("openExternal", input);
},
);
const openBrowser: DesktopLauncherShape["openBrowser"] = Effect.fn("openBrowser")(function* (
target,
openOptions = {},
) {
return yield* openTarget("openBrowser", { ...openOptions, target });
});
const openInEditor: DesktopLauncherShape["openInEditor"] = Effect.fn("openInEditor")(
function* (input) {
const editor = EDITORS.find((candidate) => candidate.id === input.editor);
if (!editor) {
return yield* new DesktopLauncherUnknownEditorError({ editor: input.editor });
}
const windowsEditorProtocolTarget =
runtime.platform === "win32"
? makeWindowsEditorProtocolTarget(input.editor, input.cwd)
: undefined;
if (windowsEditorProtocolTarget) {
return yield* runFirstAvailablePlan(
[makeWindowsExplorerPlan({ target: windowsEditorProtocolTarget })],
{
operation: "openInEditor",
target: input.cwd,
editor: input.editor,
},
);
}
if (editor.command) {
return yield* runFirstAvailablePlan(
[
makeLaunchPlan(
editor.command,
shouldUseGotoFlag(editor, input.cwd) ? ["--goto", input.cwd] : [input.cwd],
{
wait: false,
allowNonzeroExitCode: false,
detached: true,
stdio: "ignore",
shell: false,
},
),
],
{
operation: "openInEditor",
target: input.cwd,
editor: input.editor,
},
);
}
return yield* openTarget(
"openInEditor",
{ target: input.cwd },
{ target: input.cwd, editor: input.editor },
);
},
);
return {
getAvailableEditors,
openExternal,
openBrowser,
openInEditor,
} satisfies DesktopLauncherShape;
});
export const layer = Layer.effect(DesktopLauncher, make());
@@ -0,0 +1,200 @@
/**
* Open - Browser/editor launch service interface.
*
* Owns process launch helpers for opening URLs in a browser, workspace paths in
* a configured editor, and generic external targets through the platform's
* default opener.
*
* @module Open
*/
import { type EditorId } from "@t3tools/contracts";
import { Effect, Schema, ServiceMap } from "effect";
const DesktopLauncherLaunchAttemptSchema = Schema.Struct({
command: Schema.String,
args: Schema.Array(Schema.String),
reason: Schema.Literals(["commandNotFound", "spawnFailed", "nonZeroExit"]),
detail: Schema.String,
exitCode: Schema.optional(Schema.Number),
});
export class DesktopLauncherDiscoveryError extends Schema.TaggedErrorClass<DesktopLauncherDiscoveryError>()(
"DesktopLauncherDiscoveryError",
{
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Desktop launcher discovery failed in ${this.operation}: ${this.detail}`;
}
}
export class DesktopLauncherValidationError extends Schema.TaggedErrorClass<DesktopLauncherValidationError>()(
"DesktopLauncherValidationError",
{
operation: Schema.String,
detail: Schema.String,
target: Schema.optional(Schema.String),
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Desktop launcher validation failed in ${this.operation}: ${this.detail}`;
}
}
export class DesktopLauncherUnknownEditorError extends Schema.TaggedErrorClass<DesktopLauncherUnknownEditorError>()(
"DesktopLauncherUnknownEditorError",
{
editor: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Unknown desktop editor: ${this.editor}`;
}
}
export class DesktopLauncherCommandNotFoundError extends Schema.TaggedErrorClass<DesktopLauncherCommandNotFoundError>()(
"DesktopLauncherCommandNotFoundError",
{
operation: Schema.String,
command: Schema.String,
target: Schema.optional(Schema.String),
editor: Schema.optional(Schema.String),
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
const target = this.editor
? ` for editor ${this.editor}`
: this.target
? ` for ${this.target}`
: "";
return `Desktop launcher command not found in ${this.operation}: ${this.command}${target}`;
}
}
export class DesktopLauncherSpawnError extends Schema.TaggedErrorClass<DesktopLauncherSpawnError>()(
"DesktopLauncherSpawnError",
{
operation: Schema.String,
command: Schema.String,
args: Schema.Array(Schema.String),
target: Schema.optional(Schema.String),
editor: Schema.optional(Schema.String),
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Desktop launcher failed to spawn ${this.command} in ${this.operation}`;
}
}
export class DesktopLauncherNonZeroExitError extends Schema.TaggedErrorClass<DesktopLauncherNonZeroExitError>()(
"DesktopLauncherNonZeroExitError",
{
operation: Schema.String,
command: Schema.String,
args: Schema.Array(Schema.String),
exitCode: Schema.Number,
target: Schema.optional(Schema.String),
editor: Schema.optional(Schema.String),
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Desktop launcher command exited non-zero in ${this.operation}: ${this.command} (code=${this.exitCode})`;
}
}
export class DesktopLauncherLaunchAttemptsExhaustedError extends Schema.TaggedErrorClass<DesktopLauncherLaunchAttemptsExhaustedError>()(
"DesktopLauncherLaunchAttemptsExhaustedError",
{
operation: Schema.String,
target: Schema.optional(Schema.String),
editor: Schema.optional(Schema.String),
attempts: Schema.Array(DesktopLauncherLaunchAttemptSchema),
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
const subject = this.editor ? `editor ${this.editor}` : this.target ? this.target : "target";
return `Desktop launcher exhausted all launch attempts in ${this.operation} for ${subject}`;
}
}
export const DesktopLauncherError = Schema.Union([
DesktopLauncherCommandNotFoundError,
DesktopLauncherDiscoveryError,
DesktopLauncherLaunchAttemptsExhaustedError,
DesktopLauncherNonZeroExitError,
DesktopLauncherSpawnError,
DesktopLauncherUnknownEditorError,
DesktopLauncherValidationError,
]);
export interface OpenInEditorInput {
readonly cwd: string;
readonly editor: EditorId;
}
export interface OpenApplicationInput {
readonly name: string | ReadonlyArray<string>;
readonly arguments?: ReadonlyArray<string>;
}
export interface OpenExternalInput {
readonly target: string;
readonly wait?: boolean;
readonly background?: boolean;
readonly newInstance?: boolean;
readonly allowNonzeroExitCode?: boolean;
readonly app?: OpenApplicationInput | ReadonlyArray<OpenApplicationInput>;
}
export interface DesktopLauncherShape {
readonly getAvailableEditors: Effect.Effect<
ReadonlyArray<EditorId>,
DesktopLauncherDiscoveryError
>;
readonly openExternal: (
input: OpenExternalInput,
) => Effect.Effect<
void,
| DesktopLauncherCommandNotFoundError
| DesktopLauncherLaunchAttemptsExhaustedError
| DesktopLauncherNonZeroExitError
| DesktopLauncherSpawnError
| DesktopLauncherValidationError
>;
readonly openBrowser: (
target: string,
options?: Omit<OpenExternalInput, "target">,
) => Effect.Effect<
void,
| DesktopLauncherCommandNotFoundError
| DesktopLauncherLaunchAttemptsExhaustedError
| DesktopLauncherNonZeroExitError
| DesktopLauncherSpawnError
| DesktopLauncherValidationError
>;
readonly openInEditor: (
input: OpenInEditorInput,
) => Effect.Effect<
void,
| DesktopLauncherCommandNotFoundError
| DesktopLauncherLaunchAttemptsExhaustedError
| DesktopLauncherNonZeroExitError
| DesktopLauncherSpawnError
| DesktopLauncherUnknownEditorError
| DesktopLauncherValidationError
>;
}
export class DesktopLauncher extends ServiceMap.Service<DesktopLauncher, DesktopLauncherShape>()(
"t3/desktop-launcher",
) {}
+57
View File
@@ -0,0 +1,57 @@
import { describe, expect, it, vi } from "vitest";
import { killChildProcessTree } from "./killTree";
describe("killChildProcessTree", () => {
it("uses taskkill on Windows when a pid is available", () => {
const kill = vi.fn();
const spawnSyncImpl = vi.fn(() => ({ status: 0 }));
killChildProcessTree({ pid: 123, kill } as never, "SIGTERM", {
platform: "win32",
spawnSyncImpl,
});
expect(spawnSyncImpl).toHaveBeenCalledWith("taskkill", ["/pid", "123", "/T", "/F"], {
stdio: "ignore",
});
expect(kill).not.toHaveBeenCalled();
});
it("falls back to direct kill when taskkill fails", () => {
const kill = vi.fn();
const spawnSyncImpl = vi.fn(() => ({ status: 1 }));
killChildProcessTree({ pid: 456, kill } as never, "SIGKILL", {
platform: "win32",
spawnSyncImpl,
});
expect(kill).toHaveBeenCalledWith("SIGKILL");
});
it("falls back to direct kill when taskkill cannot be spawned", () => {
const kill = vi.fn();
const spawnSyncImpl = vi.fn(() => ({ status: null, error: new Error("ENOENT") }));
killChildProcessTree({ pid: 654, kill } as never, "SIGTERM", {
platform: "win32",
spawnSyncImpl,
});
expect(kill).toHaveBeenCalledWith("SIGTERM");
});
it("kills directly on non-Windows platforms", () => {
const kill = vi.fn();
const spawnSyncImpl = vi.fn();
killChildProcessTree({ pid: 789, kill } as never, "SIGTERM", {
platform: "darwin",
spawnSyncImpl,
});
expect(spawnSyncImpl).not.toHaveBeenCalled();
expect(kill).toHaveBeenCalledWith("SIGTERM");
});
});
+47
View File
@@ -0,0 +1,47 @@
import { spawnSync, type ChildProcess as NodeChildProcess } from "node:child_process";
type KillableChildProcess = Pick<NodeChildProcess, "kill" | "pid">;
type TaskkillResult = {
readonly status: number | null;
readonly error?: Error;
};
type TaskkillRunner = (
command: string,
args: ReadonlyArray<string>,
options: { readonly stdio: "ignore" },
) => TaskkillResult;
interface KillChildProcessTreeOptions {
readonly platform?: NodeJS.Platform;
readonly spawnSyncImpl?: TaskkillRunner;
}
/**
* On Windows with shell-backed processes, direct kill only terminates the
* wrapper process. Use `taskkill /T` first so the spawned process tree exits.
*/
export function killChildProcessTree(
child: KillableChildProcess,
signal: NodeJS.Signals = "SIGTERM",
options: KillChildProcessTreeOptions = {},
): void {
const platform = options.platform ?? process.platform;
if (platform === "win32" && child.pid !== undefined) {
try {
const result = (options.spawnSyncImpl ?? spawnSync)(
"taskkill",
["/pid", String(child.pid), "/T", "/F"],
{
stdio: "ignore",
},
);
if (!result.error && result.status === 0) {
return;
}
} catch {
// Fall through to direct kill when taskkill is unavailable.
}
}
child.kill(signal);
}
@@ -0,0 +1,34 @@
import { describe, expect, it } from "vitest";
import { appendTextChunkWithinByteLimit, limitChunkToByteLimit } from "./outputBuffer";
describe("outputBuffer", () => {
it("keeps a full chunk when it fits within the byte limit", () => {
const chunk = Buffer.from("hello");
expect(limitChunkToByteLimit(chunk, 2, 10)).toEqual({
chunk,
nextBytes: 7,
truncated: false,
overflow: false,
});
});
it("truncates a chunk to the remaining byte budget", () => {
const chunk = Buffer.from("abcdef");
const limited = limitChunkToByteLimit(chunk, 3, 5);
expect(Buffer.from(limited.chunk).toString()).toBe("ab");
expect(limited.nextBytes).toBe(5);
expect(limited.truncated).toBe(true);
expect(limited.overflow).toBe(true);
});
it("appends only the bytes that fit", () => {
expect(appendTextChunkWithinByteLimit("pre", 3, Buffer.from("abcdef"), 7)).toEqual({
next: "preabcd",
nextBytes: 7,
truncated: true,
});
});
});
+57
View File
@@ -0,0 +1,57 @@
export interface LimitedChunk {
readonly chunk: Uint8Array;
readonly nextBytes: number;
readonly truncated: boolean;
readonly overflow: boolean;
}
export function limitChunkToByteLimit(
chunk: Uint8Array,
currentBytes: number,
maxBytes: number,
): LimitedChunk {
const remaining = maxBytes - currentBytes;
if (remaining <= 0) {
return {
chunk: new Uint8Array(),
nextBytes: currentBytes,
truncated: true,
overflow: true,
};
}
if (chunk.byteLength <= remaining) {
return {
chunk,
nextBytes: currentBytes + chunk.byteLength,
truncated: false,
overflow: false,
};
}
return {
chunk: chunk.subarray(0, remaining),
nextBytes: currentBytes + remaining,
truncated: true,
overflow: true,
};
}
export function appendTextChunkWithinByteLimit(
target: string,
currentBytes: number,
chunk: Uint8Array,
maxBytes: number,
): {
readonly next: string;
readonly nextBytes: number;
readonly truncated: boolean;
} {
const limited = limitChunkToByteLimit(chunk, currentBytes, maxBytes);
return {
next: `${target}${Buffer.from(limited.chunk).toString()}`,
nextBytes: limited.nextBytes,
truncated: limited.truncated,
};
}
@@ -0,0 +1,35 @@
import { describe, expect, it, vi } from "vitest";
import { runProbeProcess } from "./runProbeProcess";
describe("runProbeProcess", () => {
it("forces truncated output mode while preserving other options", async () => {
const runner = vi.fn().mockResolvedValue({
stdout: "",
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
await runProbeProcess(
"ps",
["-eo", "pid=,ppid="],
{
timeoutMs: 500,
allowNonZeroExit: true,
maxBufferBytes: 1024,
cwd: "/tmp",
},
runner,
);
expect(runner).toHaveBeenCalledWith("ps", ["-eo", "pid=,ppid="], {
timeoutMs: 500,
allowNonZeroExit: true,
maxBufferBytes: 1024,
cwd: "/tmp",
outputMode: "truncate",
});
});
});
@@ -0,0 +1,17 @@
import { runProcess, type ProcessRunOptions, type ProcessRunResult } from "../processRunner";
type ProcessRunner = typeof runProcess;
export type ProbeProcessOptions = Omit<ProcessRunOptions, "stdin" | "outputMode">;
export function runProbeProcess(
command: string,
args: readonly string[],
options: ProbeProcessOptions = {},
runner: ProcessRunner = runProcess,
): Promise<ProcessRunResult> {
return runner(command, args, {
...options,
outputMode: "truncate",
});
}
@@ -0,0 +1,65 @@
import { assert, it } from "@effect/vitest";
import {
isWindowsBatchShim,
isWindowsCommandNotFound,
makeWindowsCmdCommandLine,
makeWindowsCmdSpawnArguments,
quoteForWindowsCmd,
resolveWindowsCommandShell,
} from "./windowsCommand";
it("resolves cmd.exe from Windows command shell environment variables", () => {
assert.equal(resolveWindowsCommandShell({}), "cmd.exe");
assert.equal(
resolveWindowsCommandShell({ COMSPEC: "C:\\Windows\\System32\\cmd.exe" }),
"C:\\Windows\\System32\\cmd.exe",
);
assert.equal(
resolveWindowsCommandShell({ ComSpec: "C:\\custom\\cmd.exe" }),
"C:\\custom\\cmd.exe",
);
});
it("detects Windows batch shims case-insensitively", () => {
assert.equal(isWindowsBatchShim("code.cmd"), true);
assert.equal(isWindowsBatchShim("C:\\tools\\launcher.BAT"), true);
assert.equal(isWindowsBatchShim("/tmp/code.exe"), false);
});
it("detects Windows command-not-found exits", () => {
assert.equal(isWindowsCommandNotFound(9009, "", "win32"), true);
assert.equal(
isWindowsCommandNotFound(
1,
"'foo' is not recognized as an internal or external command",
"win32",
),
true,
);
assert.equal(isWindowsCommandNotFound(9009, "", "darwin"), false);
});
it("quotes Windows cmd values safely", () => {
assert.equal(
quoteForWindowsCmd('C:\\work\\100% real\\"quoted".ts:12:4'),
'"C:\\work\\100%% real\\""quoted"".ts:12:4"',
);
});
it("builds Windows cmd command lines safely", () => {
assert.equal(
makeWindowsCmdCommandLine("code.cmd", ["--goto", "file.ts:12:4"]),
'""code.cmd" "--goto" "file.ts:12:4""',
);
});
it("builds Windows cmd spawn arguments with cmd control flags", () => {
assert.deepEqual(makeWindowsCmdSpawnArguments("code.cmd", ["--goto", "file.ts:1:1"]), [
"/d",
"/v:off",
"/s",
"/c",
'""code.cmd" "--goto" "file.ts:1:1""',
]);
});
+35
View File
@@ -0,0 +1,35 @@
export function resolveWindowsCommandShell(env: NodeJS.ProcessEnv): string {
return env.ComSpec ?? env.COMSPEC ?? "cmd.exe";
}
export function isWindowsCommandNotFound(
code: number | null,
stderr: string,
platform: NodeJS.Platform = process.platform,
): boolean {
if (platform !== "win32") return false;
if (code === 9009) return true;
return /is not recognized as an internal or external command/i.test(stderr);
}
export function isWindowsBatchShim(filePath: string): boolean {
return /\.(cmd|bat)$/i.test(filePath);
}
export function quoteForWindowsCmd(value: string): string {
return `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
}
export function makeWindowsCmdCommandLine(
commandPath: string,
args: ReadonlyArray<string>,
): string {
return `"${[commandPath, ...args].map(quoteForWindowsCmd).join(" ")}"`;
}
export function makeWindowsCmdSpawnArguments(
commandPath: string,
args: ReadonlyArray<string>,
): ReadonlyArray<string> {
return ["/d", "/v:off", "/s", "/c", makeWindowsCmdCommandLine(commandPath, args)];
}
+19 -57
View File
@@ -1,4 +1,7 @@
import { type ChildProcess as ChildProcessHandle, spawn, spawnSync } from "node:child_process";
import { spawn } from "node:child_process";
import { killChildProcessTree } from "./process/killTree";
import { appendTextChunkWithinByteLimit } from "./process/outputBuffer";
import { isWindowsCommandNotFound } from "./process/windowsCommand";
export interface ProcessRunOptions {
cwd?: string | undefined;
@@ -37,12 +40,6 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
}
function isWindowsCommandNotFound(code: number | null, stderr: string): boolean {
if (process.platform !== "win32") return false;
if (code === 9009) return true;
return /is not recognized as an internal or external command/i.test(stderr);
}
function normalizeExitError(
command: string,
args: readonly string[],
@@ -80,51 +77,6 @@ function normalizeBufferError(
const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
/**
* 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 killChild(child: ChildProcessHandle, signal: NodeJS.Signals = "SIGTERM"): 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(signal);
}
function appendChunkWithinLimit(
target: string,
currentBytes: number,
chunk: Buffer,
maxBytes: number,
): {
next: string;
nextBytes: number;
truncated: boolean;
} {
const remaining = maxBytes - currentBytes;
if (remaining <= 0) {
return { next: target, nextBytes: currentBytes, truncated: true };
}
if (chunk.length <= remaining) {
return {
next: `${target}${chunk.toString()}`,
nextBytes: currentBytes + chunk.length,
truncated: false,
};
}
return {
next: `${target}${chunk.subarray(0, remaining).toString()}`,
nextBytes: currentBytes + remaining,
truncated: true,
};
}
export async function runProcess(
command: string,
args: readonly string[],
@@ -154,9 +106,9 @@ export async function runProcess(
const timeoutTimer = setTimeout(() => {
timedOut = true;
killChild(child, "SIGTERM");
killChildProcessTree(child, "SIGTERM");
forceKillTimer = setTimeout(() => {
killChild(child, "SIGKILL");
killChildProcessTree(child, "SIGKILL");
}, 1_000);
}, timeoutMs);
@@ -171,7 +123,7 @@ export async function runProcess(
};
const fail = (error: Error): void => {
killChild(child, "SIGTERM");
killChildProcessTree(child, "SIGTERM");
finalize(() => {
reject(error);
});
@@ -183,7 +135,12 @@ export async function runProcess(
const byteLength = chunkBuffer.length;
if (stream === "stdout") {
if (outputMode === "truncate") {
const appended = appendChunkWithinLimit(stdout, stdoutBytes, chunkBuffer, maxBufferBytes);
const appended = appendTextChunkWithinByteLimit(
stdout,
stdoutBytes,
chunkBuffer,
maxBufferBytes,
);
stdout = appended.next;
stdoutBytes = appended.nextBytes;
stdoutTruncated = stdoutTruncated || appended.truncated;
@@ -196,7 +153,12 @@ export async function runProcess(
}
} else {
if (outputMode === "truncate") {
const appended = appendChunkWithinLimit(stderr, stderrBytes, chunkBuffer, maxBufferBytes);
const appended = appendTextChunkWithinByteLimit(
stderr,
stderrBytes,
chunkBuffer,
maxBufferBytes,
);
stderr = appended.next;
stderrBytes = appended.nextBytes;
stderrTruncated = stderrTruncated || appended.truncated;
@@ -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") {}
+23 -5
View File
@@ -3,7 +3,11 @@ import http from "node:http";
import os from "node:os";
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect } from "effect";
import { afterEach, describe, expect, it } from "vitest";
import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts";
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
interface HttpResponse {
@@ -23,11 +27,25 @@ function makeTempDir(prefix: string): string {
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");
void Effect.runPromise(
tryHandleProjectFaviconRequest(url, res).pipe(
Effect.provide(ProjectFaviconResolverLive),
Effect.provide(NodeServices.layer),
Effect.flatMap((handled) =>
handled
? Effect.void
: Effect.sync(() => {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
}),
),
),
).catch(() => {
if (!res.headersSent) {
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("Internal Server Error");
}
});
});
await new Promise<void>((resolve, reject) => {
+58 -153
View File
@@ -1,6 +1,8 @@
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
import { Effect, FileSystem } from "effect";
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver.ts";
const FAVICON_MIME_TYPES: Record<string, string> = {
".png": "image/png",
@@ -11,161 +13,64 @@ const FAVICON_MIME_TYPES: Record<string, string> = {
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",
];
export const tryHandleProjectFaviconRequest = Effect.fn("tryHandleProjectFaviconRequest")(
function* (
url: URL,
res: http.ServerResponse,
): Effect.fn.Return<boolean, never, ProjectFaviconResolver | FileSystem.FileSystem> {
const respond = (
statusCode: number,
headers: Record<string, string>,
body: string | Uint8Array,
) => {
res.writeHead(statusCode, headers);
res.end(body);
};
// 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;
if (url.pathname !== "/api/project-favicon") {
return false;
}
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);
}
const projectCwd = url.searchParams.get("cwd");
if (!projectCwd) {
respond(400, { "Content-Type": "text/plain" }, "Missing cwd parameter");
return true;
}
export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean {
if (url.pathname !== "/api/project-favicon") {
return false;
}
const fileSystem = yield* FileSystem.FileSystem;
const faviconResolver = yield* ProjectFaviconResolver;
const resolvedPath = yield* faviconResolver.resolvePath(projectCwd);
const projectCwd = url.searchParams.get("cwd");
if (!projectCwd) {
res.writeHead(400, { "Content-Type": "text/plain" });
res.end("Missing cwd parameter");
if (!resolvedPath) {
respond(
200,
{
"Content-Type": "image/svg+xml",
"Cache-Control": "public, max-age=3600",
},
FALLBACK_FAVICON_SVG,
);
return true;
}
const data = yield* fileSystem
.readFile(resolvedPath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!data) {
respond(500, { "Content-Type": "text/plain" }, "Read error");
return true;
}
const ext = path.extname(resolvedPath).toLowerCase();
const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream";
respond(
200,
{
"Content-Type": contentType,
"Cache-Control": "public, max-age=3600",
},
data,
);
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;
}
},
);
@@ -21,6 +21,7 @@ import { Effect, Fiber, Layer, Random, Stream } from "effect";
import { attachmentRelativePath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderAdapterValidationError } from "../Errors.ts";
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
import { makeClaudeAdapterLive, type ClaudeAdapterLiveOptions } from "./ClaudeAdapter.ts";
@@ -168,6 +169,7 @@ function makeHarness(config?: {
config?.baseDir ?? "/tmp",
),
),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(NodeServices.layer),
),
query,
@@ -301,7 +303,7 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("keeps explicit claude permission mode over runtime-derived defaults", () => {
it.effect("uses bypass permissions for full-access claude sessions", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
@@ -309,16 +311,11 @@ describe("ClaudeAdapterLive", () => {
threadId: THREAD_ID,
provider: "claudeAgent",
runtimeMode: "full-access",
providerOptions: {
claudeAgent: {
permissionMode: "plan",
},
},
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.permissionMode, "plan");
assert.equal(createInput?.options.allowDangerouslySkipPermissions, undefined);
assert.equal(createInput?.options.permissionMode, "bypassPermissions");
assert.equal(createInput?.options.allowDangerouslySkipPermissions, true);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
@@ -350,7 +347,7 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("ignores unsupported max effort for Sonnet 4.6", () => {
it.effect("falls back to default effort when unsupported max is requested for Sonnet 4.6", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
@@ -368,7 +365,7 @@ describe("ClaudeAdapterLive", () => {
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.effort, undefined);
assert.equal(createInput?.options.effort, "high");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
@@ -535,7 +532,7 @@ describe("ClaudeAdapterLive", () => {
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.effort, undefined);
assert.equal(createInput?.options.effort, "high");
const promptText = yield* Effect.promise(() => readFirstPromptText(createInput));
assert.equal(promptText, "Ultrathink:\nInvestigate the edge cases");
}).pipe(
@@ -1103,10 +1100,13 @@ describe("ClaudeAdapterLive", () => {
it.effect("closes the session when the Claude stream aborts after a turn starts", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const services = yield* Effect.services();
const runFork = Effect.runForkWith(services);
const adapter = yield* ClaudeAdapter;
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
const runtimeEventsFiber = Effect.runFork(
const runtimeEventsFiber = runFork(
Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
@@ -1195,13 +1195,17 @@ describe("ClaudeAdapterLive", () => {
},
}).pipe(
Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(NodeServices.layer),
);
return Effect.gen(function* () {
const services = yield* Effect.services();
const runFork = Effect.runForkWith(services);
const adapter = yield* ClaudeAdapter;
const runtimeEventsFiber = Effect.runFork(
const runtimeEventsFiber = runFork(
Stream.runForEach(adapter.streamEvents, () => Effect.void),
);
@@ -2386,6 +2390,85 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect(
"does not re-set the Claude model when the session already uses the same effective API model",
() => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const modelSelection = {
provider: "claudeAgent" as const,
model: "claude-opus-4-6",
};
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection,
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
modelSelection,
attachments: [],
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello again",
modelSelection,
attachments: [],
});
assert.deepEqual(harness.query.setModelCalls, []);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
},
);
it.effect("re-sets the Claude model when the effective API model changes", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
contextWindow: "1m",
},
},
attachments: [],
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello again",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
},
attachments: [],
});
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6[1m]", "claude-opus-4-6"]);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("sets plan permission mode on sendTurn when interactionMode is plan", () => {
const harness = makeHarness();
return Effect.gen(function* () {
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,650 @@
import type {
ClaudeSettings,
ModelCapabilities,
ServerProvider,
ServerProviderModel,
ServerProviderAuth,
ServerProviderState,
} from "@t3tools/contracts";
import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import { query as claudeQuery } from "@anthropic-ai/claude-agent-sdk";
import {
buildServerProvider,
DEFAULT_TIMEOUT_MS,
detailFromResult,
extractAuthBoolean,
isCommandMissingCause,
parseGenericCliVersion,
providerModelsFromSettings,
spawnAndCollect,
type CommandResult,
} from "../providerSnapshot";
import { makeManagedServerProvider } from "../makeManagedServerProvider";
import { ClaudeProvider } from "../Services/ClaudeProvider";
import { ServerSettingsError, ServerSettingsService } from "../../serverSettings";
const PROVIDER = "claudeAgent" as const;
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "claude-opus-4-6",
name: "Claude Opus 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: ["ultrathink"],
} satisfies ModelCapabilities,
},
{
slug: "claude-sonnet-4-6",
name: "Claude Sonnet 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "ultrathink", label: "Ultrathink" },
],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: ["ultrathink"],
} satisfies ModelCapabilities,
},
{
slug: "claude-haiku-4-5",
name: "Claude Haiku 4.5",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: true,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
} satisfies ModelCapabilities,
},
];
export function getClaudeModelCapabilities(model: string | null | undefined): ModelCapabilities {
const slug = model?.trim();
return (
BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ?? {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
}
);
}
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
readonly status: Exclude<ServerProviderState, "disabled">;
readonly auth: Pick<ServerProviderAuth, "status">;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
if (
lowerOutput.includes("unknown command") ||
lowerOutput.includes("unrecognized command") ||
lowerOutput.includes("unexpected argument")
) {
return {
status: "warning",
auth: { status: "unknown" },
message:
"Claude Agent authentication status command is unavailable in this version of Claude.",
};
}
if (
lowerOutput.includes("not logged in") ||
lowerOutput.includes("login required") ||
lowerOutput.includes("authentication required") ||
lowerOutput.includes("run `claude login`") ||
lowerOutput.includes("run claude login")
) {
return {
status: "error",
auth: { status: "unauthenticated" },
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
const parsedAuth = (() => {
const trimmed = result.stdout.trim();
if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
try {
return {
attemptedJsonParse: true as const,
auth: extractAuthBoolean(JSON.parse(trimmed)),
};
} catch {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
})();
if (parsedAuth.auth === true) {
return { status: "ready", auth: { status: "authenticated" } };
}
if (parsedAuth.auth === false) {
return {
status: "error",
auth: { status: "unauthenticated" },
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
auth: { status: "unknown" },
message:
"Could not verify Claude authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", auth: { status: "authenticated" } };
}
const detail = detailFromResult(result);
return {
status: "warning",
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(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.claudeAgent),
);
const command = ChildProcess.make(claudeSettings.binaryPath, [...args], {
shell: process.platform === "win32",
});
return yield* spawnAndCollect(claudeSettings.binaryPath, command);
});
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",
auth: { status: "unknown" },
message: "Claude is disabled in T3 Code settings.",
},
});
}
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",
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",
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",
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,
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
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),
);
return yield* makeManagedServerProvider<ClaudeSettings>({
getSettings: serverSettings.getSettings.pipe(
Effect.map((settings) => settings.providers.claudeAgent),
Effect.orDie,
),
streamSettings: serverSettings.streamChanges.pipe(
Stream.map((settings) => settings.providers.claudeAgent),
),
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
checkProvider,
});
}),
);
@@ -22,6 +22,7 @@ import {
type CodexAppServerSendTurnInput,
} from "../../codexAppServerManager.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderAdapterValidationError } from "../Errors.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
@@ -151,6 +152,7 @@ const validationManager = new FakeCodexManager();
const validationLayer = it.layer(
makeCodexAdapterLive({ manager: validationManager }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
@@ -201,6 +203,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
assert.deepStrictEqual(validationManager.startSessionImpl.mock.calls[0]?.[0], {
provider: "codex",
threadId: asThreadId("thread-1"),
binaryPath: "codex",
model: "gpt-5.3-codex",
serviceTier: "fast",
runtimeMode: "full-access",
@@ -216,6 +219,7 @@ sessionErrorManager.sendTurnImpl.mockImplementation(async () => {
const sessionErrorLayer = it.layer(
makeCodexAdapterLive({ manager: sessionErrorManager }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
@@ -284,6 +288,7 @@ const lifecycleManager = new FakeCodexManager();
const lifecycleLayer = it.layer(
makeCodexAdapterLive({ manager: lifecycleManager }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
@@ -469,6 +474,40 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
}),
);
it.effect("maps process stderr notifications to runtime.warning", () =>
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"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "process/stderr",
turnId: asTurnId("turn-1"),
message: "The filename or extension is too long. (os error 206)",
} satisfies ProviderEvent);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
if (firstEvent._tag !== "Some") {
return;
}
assert.equal(firstEvent.value.type, "runtime.warning");
if (firstEvent.value.type !== "runtime.warning") {
return;
}
assert.equal(firstEvent.value.turnId, "turn-1");
assert.equal(
firstEvent.value.payload.message,
"The filename or extension is too long. (os error 206)",
);
}),
);
it.effect("preserves request type when mapping serverRequest/resolved", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
+264 -232
View File
@@ -20,6 +20,7 @@ import {
ProviderItemId,
ThreadId,
TurnId,
ProviderSendTurnInput,
} from "@t3tools/contracts";
import { Effect, FileSystem, Layer, Queue, Schema, ServiceMap, Stream } from "effect";
@@ -38,6 +39,7 @@ import {
} from "../../codexAppServerManager.ts";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const PROVIDER = "codex" as const;
@@ -1266,6 +1268,19 @@ function mapToRuntimeEvents(
];
}
if (event.method === "process/stderr") {
return [
{
type: "runtime.warning",
...runtimeEventBase(event, canonicalThreadId),
payload: {
message: event.message ?? "Codex process stderr",
...(event.payload !== undefined ? { detail: event.payload } : {}),
},
},
];
}
if (event.method === "windows/worldWritableWarning") {
return [
{
@@ -1313,54 +1328,70 @@ function mapToRuntimeEvents(
return [];
}
const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const serverConfig = yield* Effect.service(ServerConfig);
const nativeEventLogger =
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
stream: "native",
})
: undefined);
const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
options?: CodexAdapterLiveOptions,
) {
const fileSystem = yield* FileSystem.FileSystem;
const serverConfig = yield* Effect.service(ServerConfig);
const nativeEventLogger =
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
stream: "native",
})
: undefined);
const manager = yield* Effect.acquireRelease(
Effect.gen(function* () {
if (options?.manager) {
return options.manager;
}
const services = yield* Effect.services<never>();
return options?.makeManager?.(services) ?? new CodexAppServerManager(services);
}),
(manager) =>
Effect.sync(() => {
try {
manager.stopAll();
} catch {
// Finalizers should never fail and block shutdown.
}
}),
);
const acquireManager = Effect.fn("acquireManager")(function* () {
if (options?.manager) {
return options.manager;
}
const services = yield* Effect.services<never>();
return options?.makeManager?.(services) ?? new CodexAppServerManager(services);
});
const startSession: CodexAdapterShape["startSession"] = (input) => {
const manager = yield* Effect.acquireRelease(acquireManager(), (manager) =>
Effect.sync(() => {
try {
manager.stopAll();
} catch {
// Finalizers should never fail and block shutdown.
}
}),
);
const serverSettingsService = yield* ServerSettingsService;
const startSession: CodexAdapterShape["startSession"] = Effect.fn("startSession")(
function* (input) {
if (input.provider !== undefined && input.provider !== PROVIDER) {
return Effect.fail(
new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "startSession",
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
}),
);
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "startSession",
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
});
}
const codexSettings = yield* serverSettingsService.getSettings.pipe(
Effect.map((settings) => settings.providers.codex),
Effect.mapError(
(error) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: error.message,
cause: error,
}),
),
);
const binaryPath = codexSettings.binaryPath;
const homePath = codexSettings.homePath;
const managerInput: CodexAppServerStartSessionInput = {
threadId: input.threadId,
provider: "codex",
...(input.cwd !== undefined ? { cwd: input.cwd } : {}),
...(input.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
runtimeMode: input.runtimeMode,
binaryPath,
...(homePath ? { homePath } : {}),
...(input.modelSelection?.provider === "codex"
? { model: input.modelSelection.model }
: {}),
@@ -1369,7 +1400,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
: {}),
};
return Effect.tryPromise({
return yield* Effect.tryPromise({
try: () => manager.startSession(managerInput),
catch: (cause) =>
new ProviderAdapterProcessError({
@@ -1378,212 +1409,213 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
detail: toMessage(cause, "Failed to start Codex adapter session."),
cause,
}),
}).pipe(Effect.map((session) => session));
};
const sendTurn: CodexAdapterShape["sendTurn"] = (input) =>
Effect.gen(function* () {
const codexAttachments = yield* Effect.forEach(
input.attachments ?? [],
(attachment) =>
Effect.gen(function* () {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
if (!attachmentPath) {
return yield* toRequestError(
input.threadId,
"turn/start",
new Error(`Invalid attachment id '${attachment.id}'.`),
);
}
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "turn/start",
detail: toMessage(cause, "Failed to read attachment file."),
cause,
}),
),
);
return {
type: "image" as const,
url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`,
};
}),
{ concurrency: 1 },
);
return yield* Effect.tryPromise({
try: () => {
const managerInput = {
threadId: input.threadId,
...(input.input !== undefined ? { input: input.input } : {}),
...(input.modelSelection?.provider === "codex"
? { model: input.modelSelection.model }
: {}),
...(input.modelSelection?.provider === "codex" &&
input.modelSelection.options?.reasoningEffort !== undefined
? { effort: input.modelSelection.options.reasoningEffort }
: {}),
...(input.modelSelection?.provider === "codex" &&
input.modelSelection.options?.fastMode
? { serviceTier: "fast" }
: {}),
...(input.interactionMode !== undefined
? { interactionMode: input.interactionMode }
: {}),
...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),
};
return manager.sendTurn(managerInput);
},
catch: (cause) => toRequestError(input.threadId, "turn/start", cause),
}).pipe(
Effect.map((result) => ({
...result,
threadId: input.threadId,
})),
);
});
},
);
const interruptTurn: CodexAdapterShape["interruptTurn"] = (threadId, turnId) =>
Effect.tryPromise({
try: () => manager.interruptTurn(threadId, turnId),
catch: (cause) => toRequestError(threadId, "turn/interrupt", cause),
});
const readThread: CodexAdapterShape["readThread"] = (threadId) =>
Effect.tryPromise({
try: () => manager.readThread(threadId),
catch: (cause) => toRequestError(threadId, "thread/read", cause),
}).pipe(
Effect.map((snapshot) => ({
threadId,
turns: snapshot.turns,
})),
const resolveAttachment = Effect.fn("resolveAttachment")(function* (
input: ProviderSendTurnInput,
attachment: NonNullable<ProviderSendTurnInput["attachments"]>[number],
) {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
if (!attachmentPath) {
return yield* toRequestError(
input.threadId,
"turn/start",
new Error(`Invalid attachment id '${attachment.id}'.`),
);
const rollbackThread: CodexAdapterShape["rollbackThread"] = (threadId, numTurns) => {
if (!Number.isInteger(numTurns) || numTurns < 1) {
return Effect.fail(
new ProviderAdapterValidationError({
}
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
operation: "rollbackThread",
issue: "numTurns must be an integer >= 1.",
method: "turn/start",
detail: toMessage(cause, "Failed to read attachment file."),
cause,
}),
);
}
return Effect.tryPromise({
try: () => manager.rollbackThread(threadId, numTurns),
catch: (cause) => toRequestError(threadId, "thread/rollback", cause),
}).pipe(
Effect.map((snapshot) => ({
threadId,
turns: snapshot.turns,
})),
);
),
);
return {
type: "image" as const,
url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`,
};
});
const respondToRequest: CodexAdapterShape["respondToRequest"] = (
threadId,
requestId,
decision,
) =>
Effect.tryPromise({
try: () => manager.respondToRequest(threadId, requestId, decision),
catch: (cause) => toRequestError(threadId, "item/requestApproval/decision", cause),
});
const respondToUserInput: CodexAdapterShape["respondToUserInput"] = (
threadId,
requestId,
answers,
) =>
Effect.tryPromise({
try: () => manager.respondToUserInput(threadId, requestId, answers),
catch: (cause) => toRequestError(threadId, "item/tool/requestUserInput", cause),
});
const stopSession: CodexAdapterShape["stopSession"] = (threadId) =>
Effect.sync(() => {
manager.stopSession(threadId);
});
const listSessions: CodexAdapterShape["listSessions"] = () =>
Effect.sync(() => manager.listSessions());
const hasSession: CodexAdapterShape["hasSession"] = (threadId) =>
Effect.sync(() => manager.hasSession(threadId));
const stopAll: CodexAdapterShape["stopAll"] = () =>
Effect.sync(() => {
manager.stopAll();
});
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
yield* Effect.acquireRelease(
Effect.gen(function* () {
const writeNativeEvent = (event: ProviderEvent) =>
Effect.gen(function* () {
if (!nativeEventLogger) {
return;
}
yield* nativeEventLogger.write(event, event.threadId);
});
const services = yield* Effect.services<never>();
const listener = (event: ProviderEvent) =>
Effect.gen(function* () {
yield* writeNativeEvent(event);
const runtimeEvents = mapToRuntimeEvents(event, event.threadId);
if (runtimeEvents.length === 0) {
yield* Effect.logDebug("ignoring unhandled Codex provider event", {
method: event.method,
threadId: event.threadId,
turnId: event.turnId,
itemId: event.itemId,
});
return;
}
yield* Queue.offerAll(runtimeEventQueue, runtimeEvents);
}).pipe(Effect.runPromiseWith(services));
manager.on("event", listener);
return listener;
}),
(listener) =>
Effect.gen(function* () {
yield* Effect.sync(() => {
manager.off("event", listener);
});
yield* Queue.shutdown(runtimeEventQueue);
}),
const sendTurn: CodexAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {
const codexAttachments = yield* Effect.forEach(
input.attachments ?? [],
(attachment) => resolveAttachment(input, attachment),
{ concurrency: 1 },
);
return {
provider: PROVIDER,
capabilities: {
sessionModelSwitch: "in-session",
return yield* Effect.tryPromise({
try: () => {
const managerInput = {
threadId: input.threadId,
...(input.input !== undefined ? { input: input.input } : {}),
...(input.modelSelection?.provider === "codex"
? { model: input.modelSelection.model }
: {}),
...(input.modelSelection?.provider === "codex" &&
input.modelSelection.options?.reasoningEffort !== undefined
? { effort: input.modelSelection.options.reasoningEffort }
: {}),
...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode
? { serviceTier: "fast" }
: {}),
...(input.interactionMode !== undefined
? { interactionMode: input.interactionMode }
: {}),
...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),
};
return manager.sendTurn(managerInput);
},
startSession,
sendTurn,
interruptTurn,
readThread,
rollbackThread,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
stopAll,
streamEvents: Stream.fromQueue(runtimeEventQueue),
} satisfies CodexAdapterShape;
catch: (cause) => toRequestError(input.threadId, "turn/start", cause),
}).pipe(
Effect.map((result) => ({
...result,
threadId: input.threadId,
})),
);
});
const interruptTurn: CodexAdapterShape["interruptTurn"] = (threadId, turnId) =>
Effect.tryPromise({
try: () => manager.interruptTurn(threadId, turnId),
catch: (cause) => toRequestError(threadId, "turn/interrupt", cause),
});
const readThread: CodexAdapterShape["readThread"] = (threadId) =>
Effect.tryPromise({
try: () => manager.readThread(threadId),
catch: (cause) => toRequestError(threadId, "thread/read", cause),
}).pipe(
Effect.map((snapshot) => ({
threadId,
turns: snapshot.turns,
})),
);
const rollbackThread: CodexAdapterShape["rollbackThread"] = (threadId, numTurns) => {
if (!Number.isInteger(numTurns) || numTurns < 1) {
return Effect.fail(
new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "rollbackThread",
issue: "numTurns must be an integer >= 1.",
}),
);
}
return Effect.tryPromise({
try: () => manager.rollbackThread(threadId, numTurns),
catch: (cause) => toRequestError(threadId, "thread/rollback", cause),
}).pipe(
Effect.map((snapshot) => ({
threadId,
turns: snapshot.turns,
})),
);
};
const respondToRequest: CodexAdapterShape["respondToRequest"] = (threadId, requestId, decision) =>
Effect.tryPromise({
try: () => manager.respondToRequest(threadId, requestId, decision),
catch: (cause) => toRequestError(threadId, "item/requestApproval/decision", cause),
});
const respondToUserInput: CodexAdapterShape["respondToUserInput"] = (
threadId,
requestId,
answers,
) =>
Effect.tryPromise({
try: () => manager.respondToUserInput(threadId, requestId, answers),
catch: (cause) => toRequestError(threadId, "item/tool/requestUserInput", cause),
});
const stopSession: CodexAdapterShape["stopSession"] = (threadId) =>
Effect.sync(() => {
manager.stopSession(threadId);
});
const listSessions: CodexAdapterShape["listSessions"] = () =>
Effect.sync(() => manager.listSessions());
const hasSession: CodexAdapterShape["hasSession"] = (threadId) =>
Effect.sync(() => manager.hasSession(threadId));
const stopAll: CodexAdapterShape["stopAll"] = () =>
Effect.sync(() => {
manager.stopAll();
});
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
const writeNativeEvent = Effect.fn("writeNativeEvent")(function* (event: ProviderEvent) {
if (!nativeEventLogger) {
return;
}
yield* nativeEventLogger.write(event, event.threadId);
});
const registerListener = Effect.fn("registerListener")(function* () {
const services = yield* Effect.services<never>();
const listenerEffect = Effect.fn("listener")(function* (event: ProviderEvent) {
yield* writeNativeEvent(event);
const runtimeEvents = mapToRuntimeEvents(event, event.threadId);
if (runtimeEvents.length === 0) {
yield* Effect.logDebug("ignoring unhandled Codex provider event", {
method: event.method,
threadId: event.threadId,
turnId: event.turnId,
itemId: event.itemId,
});
return;
}
yield* Queue.offerAll(runtimeEventQueue, runtimeEvents);
});
const listener = (event: ProviderEvent) =>
listenerEffect(event).pipe(Effect.runPromiseWith(services));
manager.on("event", listener);
return listener;
});
const unregisterListener = Effect.fn("unregisterListener")(function* (
listener: (event: ProviderEvent) => Promise<void>,
) {
yield* Effect.sync(() => {
manager.off("event", listener);
});
yield* Queue.shutdown(runtimeEventQueue);
});
yield* Effect.acquireRelease(registerListener(), unregisterListener);
return {
provider: PROVIDER,
capabilities: {
sessionModelSwitch: "in-session",
},
startSession,
sendTurn,
interruptTurn,
readThread,
rollbackThread,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
stopAll,
streamEvents: Stream.fromQueue(runtimeEventQueue),
} satisfies CodexAdapterShape;
});
export const CodexAdapterLive = Layer.effect(CodexAdapter, makeCodexAdapter());
export function makeCodexAdapterLive(options?: CodexAdapterLiveOptions) {
@@ -0,0 +1,565 @@
import * as OS from "node:os";
import type {
ModelCapabilities,
CodexSettings,
ServerProvider,
ServerProviderModel,
ServerProviderAuth,
ServerProviderState,
} from "@t3tools/contracts";
import {
Cache,
Duration,
Effect,
Equal,
FileSystem,
Layer,
Option,
Path,
Result,
Stream,
} from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
buildServerProvider,
DEFAULT_TIMEOUT_MS,
detailFromResult,
extractAuthBoolean,
isCommandMissingCause,
parseGenericCliVersion,
providerModelsFromSettings,
spawnAndCollect,
type CommandResult,
} from "../providerSnapshot";
import { makeManagedServerProvider } from "../makeManagedServerProvider";
import {
formatCodexCliUpgradeMessage,
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";
const PROVIDER = "codex" as const;
const OPENAI_AUTH_PROVIDERS = new Set(["openai"]);
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "xhigh", label: "Extra High" },
{ value: "high", label: "High", isDefault: true },
{ value: "medium", label: "Medium" },
{ value: "low", label: "Low" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "gpt-5.4-mini",
name: "GPT-5.4 Mini",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "xhigh", label: "Extra High" },
{ value: "high", label: "High", isDefault: true },
{ value: "medium", label: "Medium" },
{ value: "low", label: "Low" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "gpt-5.3-codex",
name: "GPT-5.3 Codex",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "xhigh", label: "Extra High" },
{ value: "high", label: "High", isDefault: true },
{ value: "medium", label: "Medium" },
{ value: "low", label: "Low" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "gpt-5.3-codex-spark",
name: "GPT-5.3 Codex Spark",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "xhigh", label: "Extra High" },
{ value: "high", label: "High", isDefault: true },
{ value: "medium", label: "Medium" },
{ value: "low", label: "Low" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "gpt-5.2-codex",
name: "GPT-5.2 Codex",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "xhigh", label: "Extra High" },
{ value: "high", label: "High", isDefault: true },
{ value: "medium", label: "Medium" },
{ value: "low", label: "Low" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "gpt-5.2",
name: "GPT-5.2",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "xhigh", label: "Extra High" },
{ value: "high", label: "High", isDefault: true },
{ value: "medium", label: "Medium" },
{ value: "low", label: "Low" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
];
export function getCodexModelCapabilities(model: string | null | undefined): ModelCapabilities {
const slug = model?.trim();
return (
BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ?? {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
}
);
}
export function parseAuthStatusFromOutput(result: CommandResult): {
readonly status: Exclude<ServerProviderState, "disabled">;
readonly auth: Pick<ServerProviderAuth, "status">;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
if (
lowerOutput.includes("unknown command") ||
lowerOutput.includes("unrecognized command") ||
lowerOutput.includes("unexpected argument")
) {
return {
status: "warning",
auth: { status: "unknown" },
message: "Codex CLI authentication status command is unavailable in this Codex version.",
};
}
if (
lowerOutput.includes("not logged in") ||
lowerOutput.includes("login required") ||
lowerOutput.includes("authentication required") ||
lowerOutput.includes("run `codex login`") ||
lowerOutput.includes("run codex login")
) {
return {
status: "error",
auth: { status: "unauthenticated" },
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
const parsedAuth = (() => {
const trimmed = result.stdout.trim();
if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
try {
return {
attemptedJsonParse: true as const,
auth: extractAuthBoolean(JSON.parse(trimmed)),
};
} catch {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
})();
if (parsedAuth.auth === true) {
return { status: "ready", auth: { status: "authenticated" } };
}
if (parsedAuth.auth === false) {
return {
status: "error",
auth: { status: "unauthenticated" },
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
auth: { status: "unknown" },
message:
"Could not verify Codex authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", auth: { status: "authenticated" } };
}
const detail = detailFromResult(result);
return {
status: "warning",
auth: { status: "unknown" },
message: detail
? `Could not verify Codex authentication status. ${detail}`
: "Could not verify Codex authentication status.",
};
}
export const readCodexConfigModelProvider = Effect.fn("readCodexConfigModelProvider")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const settingsService = yield* ServerSettingsService;
const codexHome = yield* settingsService.getSettings.pipe(
Effect.map(
(settings) =>
settings.providers.codex.homePath ||
process.env.CODEX_HOME ||
path.join(OS.homedir(), ".codex"),
),
);
const configPath = path.join(codexHome, "config.toml");
const content = yield* fileSystem
.readFileString(configPath)
.pipe(Effect.orElseSucceed(() => undefined));
if (content === undefined) {
return undefined;
}
let inTopLevel = true;
for (const line of content.split("\n")) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
if (trimmed.startsWith("[")) {
inTopLevel = false;
continue;
}
if (!inTopLevel) continue;
const match = trimmed.match(/^model_provider\s*=\s*["']([^"']+)["']/);
if (match) return match[1];
}
return undefined;
});
export const hasCustomModelProvider = readCodexConfigModelProvider().pipe(
Effect.map((provider) => provider !== undefined && !OPENAI_AUTH_PROVIDERS.has(provider)),
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;
const codexSettings = yield* settingsService.getSettings.pipe(
Effect.map((settings) => settings.providers.codex),
);
const command = ChildProcess.make(codexSettings.binaryPath, [...args], {
shell: process.platform === "win32",
env: {
...process.env,
...(codexSettings.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
},
});
return yield* spawnAndCollect(codexSettings.binaryPath, command);
});
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",
auth: { status: "unknown" },
message: "Codex is disabled in T3 Code settings.",
},
});
}
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",
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",
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",
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,
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
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((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),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
return yield* makeManagedServerProvider<CodexSettings>({
getSettings: serverSettings.getSettings.pipe(
Effect.map((settings) => settings.providers.codex),
Effect.orDie,
),
streamSettings: serverSettings.streamChanges.pipe(
Stream.map((settings) => settings.providers.codex),
),
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
checkProvider,
});
}),
);
@@ -1,640 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, it, assert } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, Sink, Stream } from "effect";
import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
checkClaudeProviderStatus,
checkCodexProviderStatus,
hasCustomModelProvider,
parseAuthStatusFromOutput,
parseClaudeAuthStatusFromOutput,
readCodexConfigModelProvider,
} from "./ProviderHealth";
// ── Test helpers ────────────────────────────────────────────────────
const encoder = new TextEncoder();
function mockHandle(result: { stdout: string; stderr: string; code: number }) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
stdin: Sink.drain,
stdout: Stream.make(encoder.encode(result.stdout)),
stderr: Stream.make(encoder.encode(result.stderr)),
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
}
function mockSpawnerLayer(
handler: (args: ReadonlyArray<string>) => { stdout: string; stderr: string; code: number },
) {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const cmd = command as unknown as { args: ReadonlyArray<string> };
return Effect.succeed(mockHandle(handler(cmd.args)));
}),
);
}
function failingSpawnerLayer(description: string) {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.fail(
PlatformError.systemError({
_tag: "NotFound",
module: "ChildProcess",
method: "spawn",
description,
}),
),
),
);
}
/**
* Create a temporary CODEX_HOME scoped to the current Effect test.
* Cleanup is registered in the test scope rather than via Vitest hooks.
*/
function withTempCodexHome(configContent?: string) {
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tmpDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-test-codex-" });
yield* Effect.acquireRelease(
Effect.sync(() => {
const originalCodexHome = process.env.CODEX_HOME;
process.env.CODEX_HOME = tmpDir;
return originalCodexHome;
}),
(originalCodexHome) =>
Effect.sync(() => {
if (originalCodexHome !== undefined) {
process.env.CODEX_HOME = originalCodexHome;
} else {
delete process.env.CODEX_HOME;
}
}),
);
if (configContent !== undefined) {
yield* fileSystem.writeFileString(path.join(tmpDir, "config.toml"), configContent);
}
return { tmpDir } as const;
});
}
it.layer(NodeServices.layer)("ProviderHealth", (it) => {
// ── checkCodexProviderStatus tests ────────────────────────────────
//
// These tests control CODEX_HOME to ensure the custom-provider detection
// in hasCustomModelProvider() does not interfere with the auth-probe
// path being tested.
describe("checkCodexProviderStatus", () => {
it.effect("returns ready when codex is installed and authenticated", () =>
Effect.gen(function* () {
// Point CODEX_HOME at an empty tmp dir (no config.toml) so the
// default code path (OpenAI provider, auth probe runs) is exercised.
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "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 unavailable when codex is missing", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.message, "Codex CLI (`codex`) is not installed or not on PATH.");
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
);
it.effect("returns unavailable when codex is below the minimum supported version", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
assert.strictEqual(status.authStatus, "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.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 0.36.0\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unauthenticated when auth probe reports login required", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
);
}).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: "", stderr: "Not logged in. Run codex login.", code: 1 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unauthenticated when login status output includes 'not logged in'", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
);
}).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: "Not logged in\n", stderr: "", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns warning when login status command is unsupported", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI authentication status command is unavailable in this Codex version.",
);
}).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: "", stderr: "error: unknown command 'login'", code: 2 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
});
// ── Custom model provider: checkCodexProviderStatus integration ───
describe("checkCodexProviderStatus with custom model provider", () => {
it.effect("skips auth probe and returns ready when a custom model provider is configured", () =>
Effect.gen(function* () {
yield* withTempCodexHome(
[
'model_provider = "portkey"',
"",
"[model_providers.portkey]",
'base_url = "https://api.portkey.ai/v1"',
'env_key = "PORTKEY_API_KEY"',
].join("\n"),
);
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Using a custom Codex model provider; OpenAI login check skipped.",
);
}).pipe(
Effect.provide(
// The spawner only handles --version; if the test attempts
// "login status" the throw proves the auth probe was NOT skipped.
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
throw new Error(`Auth probe should have been skipped but got args: ${joined}`);
}),
),
),
);
it.effect("still reports error when codex CLI is missing even with custom provider", () =>
Effect.gen(function* () {
yield* withTempCodexHome(
[
'model_provider = "portkey"',
"",
"[model_providers.portkey]",
'base_url = "https://api.portkey.ai/v1"',
'env_key = "PORTKEY_API_KEY"',
].join("\n"),
);
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
);
});
describe("checkCodexProviderStatus with openai model provider", () => {
it.effect("still runs auth probe when model_provider is openai", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "openai"\n');
const status = yield* checkCodexProviderStatus;
// The auth probe runs and sees "not logged in" → error
assert.strictEqual(status.status, "error");
assert.strictEqual(status.authStatus, "unauthenticated");
}).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: "Not logged in\n", stderr: "", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
});
// ── parseAuthStatusFromOutput pure tests ──────────────────────────
describe("parseAuthStatusFromOutput", () => {
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");
});
it("JSON with authenticated=false is unauthenticated", () => {
const parsed = parseAuthStatusFromOutput({
stdout: '[{"authenticated":false}]\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.authStatus, "unauthenticated");
});
it("JSON without auth marker is warning", () => {
const parsed = parseAuthStatusFromOutput({
stdout: '[{"ok":true}]\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.authStatus, "unknown");
});
});
// ── readCodexConfigModelProvider tests ─────────────────────────────
describe("readCodexConfigModelProvider", () => {
it.effect("returns undefined when config file does not exist", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
assert.strictEqual(yield* readCodexConfigModelProvider, undefined);
}),
);
it.effect("returns undefined when config has no model_provider key", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model = "gpt-5-codex"\n');
assert.strictEqual(yield* readCodexConfigModelProvider, undefined);
}),
);
it.effect("returns the provider when model_provider is set at top level", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model = "gpt-5-codex"\nmodel_provider = "portkey"\n');
assert.strictEqual(yield* readCodexConfigModelProvider, "portkey");
}),
);
it.effect("returns openai when model_provider is openai", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "openai"\n');
assert.strictEqual(yield* readCodexConfigModelProvider, "openai");
}),
);
it.effect("ignores model_provider inside section headers", () =>
Effect.gen(function* () {
yield* withTempCodexHome(
[
'model = "gpt-5-codex"',
"",
"[model_providers.portkey]",
'base_url = "https://api.portkey.ai/v1"',
'model_provider = "should-be-ignored"',
"",
].join("\n"),
);
assert.strictEqual(yield* readCodexConfigModelProvider, undefined);
}),
);
it.effect("handles comments and whitespace", () =>
Effect.gen(function* () {
yield* withTempCodexHome(
[
"# This is a comment",
"",
' model_provider = "azure" ',
"",
"[profiles.deep-review]",
'model = "gpt-5-pro"',
].join("\n"),
);
assert.strictEqual(yield* readCodexConfigModelProvider, "azure");
}),
);
it.effect("handles single-quoted values in TOML", () =>
Effect.gen(function* () {
yield* withTempCodexHome("model_provider = 'mistral'\n");
assert.strictEqual(yield* readCodexConfigModelProvider, "mistral");
}),
);
});
// ── hasCustomModelProvider tests ───────────────────────────────────
describe("hasCustomModelProvider", () => {
it.effect("returns false when no config file exists", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
assert.strictEqual(yield* hasCustomModelProvider, false);
}),
);
it.effect("returns false when model_provider is not set", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model = "gpt-5-codex"\n');
assert.strictEqual(yield* hasCustomModelProvider, false);
}),
);
it.effect("returns false when model_provider is openai", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "openai"\n');
assert.strictEqual(yield* hasCustomModelProvider, false);
}),
);
it.effect("returns true when model_provider is portkey", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "portkey"\n');
assert.strictEqual(yield* hasCustomModelProvider, true);
}),
);
it.effect("returns true when model_provider is azure", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "azure"\n');
assert.strictEqual(yield* hasCustomModelProvider, true);
}),
);
it.effect("returns true when model_provider is ollama", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "ollama"\n');
assert.strictEqual(yield* hasCustomModelProvider, true);
}),
);
it.effect("returns true when model_provider is a custom proxy", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "my-company-proxy"\n');
assert.strictEqual(yield* hasCustomModelProvider, true);
}),
);
});
// ── checkClaudeProviderStatus tests ──────────────────────────
describe("checkClaudeProviderStatus", () => {
it.effect("returns ready when claude is installed and authenticated", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "authenticated");
}).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 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.available, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Claude Agent CLI (`claude`) is not installed or not on PATH.",
);
}).pipe(Effect.provide(failingSpawnerLayer("spawn claude ENOENT"))),
);
it.effect("returns error when version check fails with non-zero exit code", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version")
return { stdout: "", stderr: "Something went wrong", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unauthenticated when auth status reports not logged in", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Claude is not authenticated. Run `claude auth login` and try again.",
);
}).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":false}\n',
stderr: "",
code: 1,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unauthenticated when output includes 'not logged in'", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
}).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: "Not logged in\n", stderr: "", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns warning when auth status command is unsupported", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Claude Agent authentication status command is unavailable in this version of Claude.",
);
}).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: "", stderr: "error: unknown command 'auth'", code: 2 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
});
// ── parseClaudeAuthStatusFromOutput pure tests ────────────────────
describe("parseClaudeAuthStatusFromOutput", () => {
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");
});
it("JSON with loggedIn=true is authenticated", () => {
const parsed = parseClaudeAuthStatusFromOutput({
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("JSON with loggedIn=false is unauthenticated", () => {
const parsed = parseClaudeAuthStatusFromOutput({
stdout: '{"loggedIn":false}\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.authStatus, "unauthenticated");
});
it("JSON without auth marker is warning", () => {
const parsed = parseClaudeAuthStatusFromOutput({
stdout: '{"ok":true}\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.authStatus, "unknown");
});
});
});
Loaded 100 of 254 files, more files were not shown because too many files have changed in this diff. Show more