Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b8c367df4a | ||
|
|
ea3e9987d7 | ||
|
|
12ecd648ba | ||
|
|
e980a2fd8f |
No files matched your search
@@ -1,2 +0,0 @@
|
||||
# git autocrlf=true converts LF to CRLF on Windows, causing issues with oxfmt
|
||||
* text=auto eol=lf
|
||||
+1
-2
@@ -28,5 +28,4 @@ github:realAhmedRoach
|
||||
github:shiroyasha9
|
||||
github:Yash-Singh1
|
||||
github:eggfriedrice24
|
||||
github:Ymit24
|
||||
github:shivamhwp
|
||||
github:Ymit24
|
||||
@@ -124,49 +124,25 @@ 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 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 testFilePatterns = [
|
||||
/(^|\/)__tests__(\/|$)/,
|
||||
/(^|\/)tests?(\/|$)/,
|
||||
/^apps\/server\/integration\//,
|
||||
/\.(test|spec|browser|integration)\.[^.\/]+$/,
|
||||
];
|
||||
|
||||
const sumNumstat = (text) =>
|
||||
text
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.reduce((total, line) => {
|
||||
const [insertionsRaw = "0", deletionsRaw = "0"] = line.split("\t");
|
||||
const additions =
|
||||
insertionsRaw === "-" ? 0 : Number.parseInt(insertionsRaw, 10) || 0;
|
||||
const deletions =
|
||||
deletionsRaw === "-" ? 0 : Number.parseInt(deletionsRaw, 10) || 0;
|
||||
|
||||
return total + additions + deletions;
|
||||
}, 0);
|
||||
const isTestFile = (filename) =>
|
||||
testFilePatterns.some((pattern) => pattern.test(filename));
|
||||
|
||||
const resolveSizeLabel = (totalChangedLines) => {
|
||||
if (totalChangedLines < 10) {
|
||||
@@ -192,53 +168,40 @@ jobs:
|
||||
return "size:XXL";
|
||||
};
|
||||
|
||||
execFileSync("git", ["fetch", "--no-tags", "origin", baseSha], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
|
||||
execFileSync(
|
||||
"git",
|
||||
["fetch", "--no-tags", "origin", `+refs/pull/${issueNumber}/head:${headTrackingRef}`],
|
||||
const files = await github.paginate(
|
||||
github.rest.pulls.listFiles,
|
||||
{
|
||||
stdio: "inherit",
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
pull_number: issueNumber,
|
||||
per_page: 100,
|
||||
},
|
||||
(response) => response.data,
|
||||
);
|
||||
|
||||
const resolvedHeadSha = execFileSync("git", ["rev-parse", headTrackingRef], {
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
|
||||
if (resolvedHeadSha !== headSha) {
|
||||
if (files.length >= 3000) {
|
||||
core.warning(
|
||||
`Fetched head SHA ${resolvedHeadSha} does not match pull request head SHA ${headSha}; using fetched ref for sizing.`,
|
||||
"The GitHub pull request files API may truncate results at 3,000 files; PR size may be undercounted.",
|
||||
);
|
||||
}
|
||||
|
||||
execFileSync("git", ["cat-file", "-e", `${baseSha}^{commit}`], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
let testChangedLines = 0;
|
||||
let nonTestChangedLines = 0;
|
||||
|
||||
const diffArgs = [
|
||||
"diff",
|
||||
"--numstat",
|
||||
"--ignore-all-space",
|
||||
"--ignore-blank-lines",
|
||||
`${baseSha}...${resolvedHeadSha}`,
|
||||
];
|
||||
for (const file of files) {
|
||||
const changedLinesForFile = (file.additions ?? 0) + (file.deletions ?? 0);
|
||||
|
||||
const totalChangedLines = sumNumstat(
|
||||
execFileSync(
|
||||
"git",
|
||||
diffArgs,
|
||||
{ encoding: "utf8" },
|
||||
),
|
||||
);
|
||||
const nonTestChangedLines = sumNumstat(
|
||||
execFileSync("git", [...diffArgs, "--", ".", ...testExcludePathspecs], {
|
||||
encoding: "utf8",
|
||||
}),
|
||||
);
|
||||
const testChangedLines = Math.max(0, totalChangedLines - nonTestChangedLines);
|
||||
if (changedLinesForFile === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isTestFile(file.filename)) {
|
||||
testChangedLines += changedLinesForFile;
|
||||
continue;
|
||||
}
|
||||
|
||||
nonTestChangedLines += changedLinesForFile;
|
||||
}
|
||||
|
||||
const changedLines = nonTestChangedLines === 0 ? testChangedLines : nonTestChangedLines;
|
||||
const nextLabelName = resolveSizeLabel(changedLines);
|
||||
|
||||
@@ -126,7 +126,7 @@ jobs:
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: bun scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Build desktop artifact
|
||||
shell: bash
|
||||
@@ -248,7 +248,7 @@ jobs:
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: bun scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Build CLI package
|
||||
run: bun run build --filter=@t3tools/web --filter=t3
|
||||
@@ -348,7 +348,7 @@ jobs:
|
||||
name: Update version strings
|
||||
env:
|
||||
RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
|
||||
run: bun scripts/update-release-package-versions.ts "$RELEASE_VERSION" --github-output
|
||||
run: node scripts/update-release-package-versions.ts "$RELEASE_VERSION" --github-output
|
||||
|
||||
- name: Format package.json files
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
@@ -364,7 +364,7 @@ jobs:
|
||||
env:
|
||||
RELEASE_TAG: ${{ needs.preflight.outputs.tag }}
|
||||
run: |
|
||||
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json apps/marketing/public/schemas bun.lock; then
|
||||
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
|
||||
echo "No version changes to commit."
|
||||
exit 0
|
||||
fi
|
||||
@@ -372,6 +372,6 @@ jobs:
|
||||
git config user.name "${{ steps.app_bot.outputs.name }}"
|
||||
git config user.email "${{ steps.app_bot.outputs.email }}"
|
||||
|
||||
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json apps/marketing/public/schemas bun.lock
|
||||
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
|
||||
git commit -m "chore(release): prepare $RELEASE_TAG"
|
||||
git push origin HEAD:main
|
||||
@@ -12,7 +12,6 @@ packages/*/dist
|
||||
build/
|
||||
.logs/
|
||||
release/
|
||||
release-mock/
|
||||
.t3
|
||||
.idea/
|
||||
apps/web/.playwright
|
||||
|
||||
@@ -15,29 +15,6 @@ The file must be a JSON array of rules:
|
||||
|
||||
See the full schema for more details: [`packages/contracts/src/keybindings.ts`](packages/contracts/src/keybindings.ts)
|
||||
|
||||
## Editor Schema Support
|
||||
|
||||
`keybindings.json` is intentionally a top-level JSON array, so it cannot carry an inline `$schema` property the way `settings.json` can.
|
||||
|
||||
To get autocomplete and hover docs in editors like VS Code, associate the file externally with the published schema:
|
||||
|
||||
```json
|
||||
{
|
||||
"json.schemas": [
|
||||
{
|
||||
"fileMatch": ["**/.t3/keybindings.json", "**/keybindings.json"],
|
||||
"url": "https://t3.codes/schemas/keybindings.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
If you want a pinned schema instead of the latest stable one, use a versioned URL such as:
|
||||
|
||||
```text
|
||||
https://t3.codes/schemas/keybindings/0.0.15.json
|
||||
```
|
||||
|
||||
## Defaults
|
||||
|
||||
```json
|
||||
|
||||
@@ -2,42 +2,18 @@
|
||||
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
|
||||
|
||||
## Installation
|
||||
## How to use
|
||||
|
||||
> [!WARNING]
|
||||
> 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
|
||||
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
|
||||
|
||||
```bash
|
||||
npx t3
|
||||
```
|
||||
|
||||
### Desktop app
|
||||
You can also just install the desktop app. It's cooler.
|
||||
|
||||
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
|
||||
|
||||
#### Windows (`winget`)
|
||||
|
||||
```bash
|
||||
winget install T3Tools.T3Code
|
||||
```
|
||||
|
||||
#### macOS (Homebrew)
|
||||
|
||||
```bash
|
||||
brew install --cask t3-code
|
||||
```
|
||||
|
||||
#### Arch Linux (AUR)
|
||||
|
||||
```bash
|
||||
yay -S t3code-bin
|
||||
```
|
||||
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
|
||||
|
||||
## Some notes
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.15",
|
||||
"version": "0.0.14",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -14,7 +14,7 @@ export async function showDesktopConfirmDialog(
|
||||
const options = {
|
||||
type: "question" as const,
|
||||
buttons: ["No", "Yes"],
|
||||
defaultId: 0,
|
||||
defaultId: CONFIRM_BUTTON_INDEX,
|
||||
cancelId: 0,
|
||||
noLink: true,
|
||||
message: normalizedMessage,
|
||||
|
||||
@@ -20,7 +20,6 @@ import * as Effect from "effect/Effect";
|
||||
import type {
|
||||
DesktopTheme,
|
||||
DesktopUpdateActionResult,
|
||||
DesktopUpdateCheckResult,
|
||||
DesktopUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import { autoUpdater } from "electron-updater";
|
||||
@@ -57,7 +56,6 @@ 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");
|
||||
@@ -289,12 +287,10 @@ 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;
|
||||
@@ -758,13 +754,13 @@ function shouldEnableAutoUpdates(): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
async function checkForUpdates(reason: string): Promise<boolean> {
|
||||
if (isQuitting || !updaterConfigured || updateCheckInFlight) return false;
|
||||
async function checkForUpdates(reason: string): Promise<void> {
|
||||
if (isQuitting || !updaterConfigured || updateCheckInFlight) return;
|
||||
if (updateState.status === "downloading" || updateState.status === "downloaded") {
|
||||
console.info(
|
||||
`[desktop-updater] Skipping update check (${reason}) while status=${updateState.status}.`,
|
||||
);
|
||||
return false;
|
||||
return;
|
||||
}
|
||||
updateCheckInFlight = true;
|
||||
setUpdateState(reduceDesktopUpdateStateOnCheckStart(updateState, new Date().toISOString()));
|
||||
@@ -772,14 +768,12 @@ async function checkForUpdates(reason: string): Promise<boolean> {
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -813,22 +807,13 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed
|
||||
}
|
||||
|
||||
isQuitting = true;
|
||||
updateInstallInFlight = true;
|
||||
clearUpdatePollTimer();
|
||||
try {
|
||||
await stopBackendAndWaitForExit();
|
||||
// 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 };
|
||||
autoUpdater.quitAndInstall();
|
||||
return { accepted: true, completed: true };
|
||||
} catch (error: unknown) {
|
||||
const message = formatErrorMessage(error);
|
||||
updateInstallInFlight = false;
|
||||
isQuitting = false;
|
||||
setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
|
||||
console.error(`[desktop-updater] Failed to install update: ${message}`);
|
||||
@@ -865,13 +850,6 @@ function configureAutoUpdater(): void {
|
||||
}
|
||||
}
|
||||
|
||||
if (process.env.T3CODE_DESKTOP_MOCK_UPDATES) {
|
||||
autoUpdater.setFeedURL({
|
||||
provider: "generic",
|
||||
url: `http://localhost:${process.env.T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT ?? 3000}`,
|
||||
});
|
||||
}
|
||||
|
||||
autoUpdater.autoDownload = false;
|
||||
autoUpdater.autoInstallOnAppQuit = false;
|
||||
// Keep alpha branding, but force all installs onto the stable update track.
|
||||
@@ -908,13 +886,6 @@ 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",
|
||||
@@ -1170,7 +1141,6 @@ function registerIpcHandlers(): void {
|
||||
id: item.id,
|
||||
label: item.label,
|
||||
destructive: item.destructive === true,
|
||||
disabled: item.disabled === true,
|
||||
}));
|
||||
if (normalizedItems.length === 0) {
|
||||
return null;
|
||||
@@ -1201,7 +1171,6 @@ function registerIpcHandlers(): void {
|
||||
}
|
||||
const itemOption: MenuItemConstructorOptions = {
|
||||
label: item.label,
|
||||
enabled: !item.disabled,
|
||||
click: () => resolve(item.id),
|
||||
};
|
||||
if (item.destructive) {
|
||||
@@ -1267,21 +1236,6 @@ 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> {
|
||||
@@ -1405,7 +1359,6 @@ async function bootstrap(): Promise<void> {
|
||||
|
||||
app.on("before-quit", () => {
|
||||
isQuitting = true;
|
||||
updateInstallInFlight = false;
|
||||
writeDesktopLogHeader("before-quit received");
|
||||
clearUpdatePollTimer();
|
||||
stopBackend();
|
||||
@@ -1435,7 +1388,7 @@ app
|
||||
});
|
||||
|
||||
app.on("window-all-closed", () => {
|
||||
if (process.platform !== "darwin" && !isQuitting) {
|
||||
if (process.platform !== "darwin") {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -9,7 +9,6 @@ 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";
|
||||
@@ -36,7 +35,6 @@ 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) => {
|
||||
|
||||
@@ -62,13 +62,14 @@ describe("syncShellEnvironment", () => {
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
||||
});
|
||||
|
||||
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () => {
|
||||
it("does nothing outside macOS", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/inherited.sock",
|
||||
};
|
||||
const readEnvironment = vi.fn(() => ({
|
||||
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
|
||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||
}));
|
||||
|
||||
@@ -77,29 +78,8 @@ 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("C:\\Windows\\System32");
|
||||
expect(env.PATH).toBe("/usr/bin");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
readEnvironmentFromLoginShell,
|
||||
resolveLoginShell,
|
||||
ShellEnvironmentReader,
|
||||
} from "@t3tools/shared/shell";
|
||||
import { readEnvironmentFromLoginShell, ShellEnvironmentReader } from "@t3tools/shared/shell";
|
||||
|
||||
export function syncShellEnvironment(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
@@ -11,13 +7,10 @@ export function syncShellEnvironment(
|
||||
readEnvironment?: ShellEnvironmentReader;
|
||||
} = {},
|
||||
): void {
|
||||
const platform = options.platform ?? process.platform;
|
||||
if (platform !== "darwin" && platform !== "linux") return;
|
||||
if ((options.platform ?? process.platform) !== "darwin") return;
|
||||
|
||||
try {
|
||||
const shell = resolveLoginShell(platform, env.SHELL);
|
||||
if (!shell) return;
|
||||
|
||||
const shell = env.SHELL ?? "/bin/zsh";
|
||||
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "T3 Code Keybindings",
|
||||
"description": "Ordered list of custom keybinding rules persisted in `keybindings.json`.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"key": {
|
||||
"type": "string",
|
||||
"description": "Keyboard shortcut to listen for."
|
||||
},
|
||||
"command": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"terminal.toggle",
|
||||
"terminal.split",
|
||||
"terminal.new",
|
||||
"terminal.close",
|
||||
"diff.toggle",
|
||||
"chat.new",
|
||||
"chat.newLocal",
|
||||
"editor.openFavorite",
|
||||
"thread.previous",
|
||||
"thread.next",
|
||||
"thread.jump.1",
|
||||
"thread.jump.2",
|
||||
"thread.jump.3",
|
||||
"thread.jump.4",
|
||||
"thread.jump.5",
|
||||
"thread.jump.6",
|
||||
"thread.jump.7",
|
||||
"thread.jump.8",
|
||||
"thread.jump.9"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^script\\.[\\s\\S]*?\\.run$",
|
||||
"description": "Command identifier for running a project script, formatted as `script.<id>.run`."
|
||||
}
|
||||
],
|
||||
"description": "Command to execute when the shortcut matches."
|
||||
},
|
||||
"when": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional expression limiting when the shortcut is active."
|
||||
}
|
||||
},
|
||||
"required": ["key", "command"],
|
||||
"additionalProperties": false,
|
||||
"description": "Single keybinding rule entry in `keybindings.json`."
|
||||
},
|
||||
"allOf": [
|
||||
{
|
||||
"maxItems": 256,
|
||||
"description": "Ordered list of custom keybinding rules persisted in `keybindings.json`."
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "T3 Code Keybindings",
|
||||
"description": "Ordered list of custom keybinding rules persisted in `keybindings.json`.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"key": {
|
||||
"type": "string",
|
||||
"description": "Keyboard shortcut to listen for."
|
||||
},
|
||||
"command": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"terminal.toggle",
|
||||
"terminal.split",
|
||||
"terminal.new",
|
||||
"terminal.close",
|
||||
"diff.toggle",
|
||||
"chat.new",
|
||||
"chat.newLocal",
|
||||
"editor.openFavorite",
|
||||
"thread.previous",
|
||||
"thread.next",
|
||||
"thread.jump.1",
|
||||
"thread.jump.2",
|
||||
"thread.jump.3",
|
||||
"thread.jump.4",
|
||||
"thread.jump.5",
|
||||
"thread.jump.6",
|
||||
"thread.jump.7",
|
||||
"thread.jump.8",
|
||||
"thread.jump.9"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^script\\.[\\s\\S]*?\\.run$",
|
||||
"description": "Command identifier for running a project script, formatted as `script.<id>.run`."
|
||||
}
|
||||
],
|
||||
"description": "Command to execute when the shortcut matches."
|
||||
},
|
||||
"when": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional expression limiting when the shortcut is active."
|
||||
}
|
||||
},
|
||||
"required": ["key", "command"],
|
||||
"additionalProperties": false,
|
||||
"description": "Single keybinding rule entry in `keybindings.json`."
|
||||
},
|
||||
"allOf": [
|
||||
{
|
||||
"maxItems": 256,
|
||||
"description": "Ordered list of custom keybinding rules persisted in `keybindings.json`."
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,302 +0,0 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "T3 Code Server Settings",
|
||||
"description": "Server-authoritative settings persisted in `settings.json`.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"$schema": {
|
||||
"type": "string",
|
||||
"description": "Optional JSON Schema reference for editor tooling. May point to the stable or versioned T3 Code settings schema URL."
|
||||
},
|
||||
"enableAssistantStreaming": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean",
|
||||
"description": "Whether server-driven assistant responses should stream incrementally to clients when the active provider supports it."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Show token-by-token output while a response is in progress."
|
||||
},
|
||||
"defaultThreadEnvMode": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": ["local", "worktree"],
|
||||
"description": "Default execution environment to use when creating new threads."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Pick the default workspace mode for newly created draft threads."
|
||||
},
|
||||
"textGenerationModelSelection": {
|
||||
"anyOf": [
|
||||
{
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"provider": {
|
||||
"type": "string",
|
||||
"enum": ["codex"],
|
||||
"description": "The provider used for text generation."
|
||||
},
|
||||
"model": {
|
||||
"type": "string",
|
||||
"description": "The Codex model slug to use for text generation."
|
||||
},
|
||||
"options": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"reasoningEffort": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": ["xhigh", "high", "medium", "low"]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Reasoning depth for Codex text generation. Higher values trade latency and cost for stronger reasoning."
|
||||
},
|
||||
"fastMode": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Whether to prefer Codex fast mode when the selected model supports it."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"description": "Optional Codex-specific tuning knobs for the selected model."
|
||||
}
|
||||
},
|
||||
"required": ["provider", "model"],
|
||||
"additionalProperties": false,
|
||||
"description": "Text generation model selection for the Codex provider."
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"provider": {
|
||||
"type": "string",
|
||||
"enum": ["claudeAgent"],
|
||||
"description": "The provider used for text generation."
|
||||
},
|
||||
"model": {
|
||||
"type": "string",
|
||||
"description": "The Claude model slug to use for text generation."
|
||||
},
|
||||
"options": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"thinking": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Whether Claude should enable extended thinking for the selected model."
|
||||
},
|
||||
"effort": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": ["low", "medium", "high", "max", "ultrathink"]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Reasoning effort for Claude text generation. Higher values trade latency and cost for stronger reasoning."
|
||||
},
|
||||
"fastMode": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Whether to prefer Claude fast mode when the selected model supports it."
|
||||
},
|
||||
"contextWindow": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional Claude context window preset to request for the selected model, if supported."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"description": "Optional Claude-specific tuning knobs for the selected model."
|
||||
}
|
||||
},
|
||||
"required": ["provider", "model"],
|
||||
"additionalProperties": false,
|
||||
"description": "Text generation model selection for the Claude provider."
|
||||
}
|
||||
],
|
||||
"description": "Default provider and model to use for server-side text generation features."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Configure the model used for generated commit messages, PR titles, and similar Git text."
|
||||
},
|
||||
"providers": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"codex": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean",
|
||||
"description": "Whether the Codex provider is enabled and available for selection."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Whether the Codex provider is enabled and available for selection."
|
||||
},
|
||||
"binaryPath": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Path to the Codex executable. Leave blank to resolve the `codex` executable from PATH."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Path to the Codex binary"
|
||||
},
|
||||
"homePath": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Optional Codex home directory. Leave blank to use the default provider-managed location."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional custom Codex home and config directory."
|
||||
},
|
||||
"customModels": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Additional Codex model slugs to surface in the UI alongside discovered defaults."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Additional Codex model slugs to surface in the UI alongside discovered defaults."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"description": "Configuration for the Codex provider."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Configuration for the Codex provider."
|
||||
},
|
||||
"claudeAgent": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean",
|
||||
"description": "Whether the Claude provider is enabled and available for selection."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Whether the Claude provider is enabled and available for selection."
|
||||
},
|
||||
"binaryPath": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Path to the Claude executable. Leave blank to resolve the `claude` executable from PATH."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Path to the Claude binary"
|
||||
},
|
||||
"customModels": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Additional Claude model slugs to surface in the UI alongside discovered defaults."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Additional Claude model slugs to surface in the UI alongside discovered defaults."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"description": "Configuration for the Claude provider."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Configuration for the Claude provider."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"description": "Provider-specific server configuration."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Provider-specific server configuration."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -1,302 +0,0 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "T3 Code Server Settings",
|
||||
"description": "Server-authoritative settings persisted in `settings.json`.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"$schema": {
|
||||
"type": "string",
|
||||
"description": "Optional JSON Schema reference for editor tooling. May point to the stable or versioned T3 Code settings schema URL."
|
||||
},
|
||||
"enableAssistantStreaming": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean",
|
||||
"description": "Whether server-driven assistant responses should stream incrementally to clients when the active provider supports it."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Show token-by-token output while a response is in progress."
|
||||
},
|
||||
"defaultThreadEnvMode": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": ["local", "worktree"],
|
||||
"description": "Default execution environment to use when creating new threads."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Pick the default workspace mode for newly created draft threads."
|
||||
},
|
||||
"textGenerationModelSelection": {
|
||||
"anyOf": [
|
||||
{
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"provider": {
|
||||
"type": "string",
|
||||
"enum": ["codex"],
|
||||
"description": "The provider used for text generation."
|
||||
},
|
||||
"model": {
|
||||
"type": "string",
|
||||
"description": "The Codex model slug to use for text generation."
|
||||
},
|
||||
"options": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"reasoningEffort": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": ["xhigh", "high", "medium", "low"]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Reasoning depth for Codex text generation. Higher values trade latency and cost for stronger reasoning."
|
||||
},
|
||||
"fastMode": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Whether to prefer Codex fast mode when the selected model supports it."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"description": "Optional Codex-specific tuning knobs for the selected model."
|
||||
}
|
||||
},
|
||||
"required": ["provider", "model"],
|
||||
"additionalProperties": false,
|
||||
"description": "Text generation model selection for the Codex provider."
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"provider": {
|
||||
"type": "string",
|
||||
"enum": ["claudeAgent"],
|
||||
"description": "The provider used for text generation."
|
||||
},
|
||||
"model": {
|
||||
"type": "string",
|
||||
"description": "The Claude model slug to use for text generation."
|
||||
},
|
||||
"options": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"thinking": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Whether Claude should enable extended thinking for the selected model."
|
||||
},
|
||||
"effort": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": ["low", "medium", "high", "max", "ultrathink"]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Reasoning effort for Claude text generation. Higher values trade latency and cost for stronger reasoning."
|
||||
},
|
||||
"fastMode": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Whether to prefer Claude fast mode when the selected model supports it."
|
||||
},
|
||||
"contextWindow": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional Claude context window preset to request for the selected model, if supported."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"description": "Optional Claude-specific tuning knobs for the selected model."
|
||||
}
|
||||
},
|
||||
"required": ["provider", "model"],
|
||||
"additionalProperties": false,
|
||||
"description": "Text generation model selection for the Claude provider."
|
||||
}
|
||||
],
|
||||
"description": "Default provider and model to use for server-side text generation features."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Configure the model used for generated commit messages, PR titles, and similar Git text."
|
||||
},
|
||||
"providers": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"codex": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean",
|
||||
"description": "Whether the Codex provider is enabled and available for selection."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Whether the Codex provider is enabled and available for selection."
|
||||
},
|
||||
"binaryPath": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Path to the Codex executable. Leave blank to resolve the `codex` executable from PATH."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Path to the Codex binary"
|
||||
},
|
||||
"homePath": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Optional Codex home directory. Leave blank to use the default provider-managed location."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional custom Codex home and config directory."
|
||||
},
|
||||
"customModels": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Additional Codex model slugs to surface in the UI alongside discovered defaults."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Additional Codex model slugs to surface in the UI alongside discovered defaults."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"description": "Configuration for the Codex provider."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Configuration for the Codex provider."
|
||||
},
|
||||
"claudeAgent": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean",
|
||||
"description": "Whether the Claude provider is enabled and available for selection."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Whether the Claude provider is enabled and available for selection."
|
||||
},
|
||||
"binaryPath": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Path to the Claude executable. Leave blank to resolve the `claude` executable from PATH."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Path to the Claude binary"
|
||||
},
|
||||
"customModels": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Additional Claude model slugs to surface in the UI alongside discovered defaults."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Additional Claude model slugs to surface in the UI alongside discovered defaults."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"description": "Configuration for the Claude provider."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Configuration for the Claude provider."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"description": "Provider-specific server configuration."
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Provider-specific server configuration."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -306,8 +306,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Effect.succeed({ branch: input.newBranch }),
|
||||
} as unknown as GitCoreShape);
|
||||
const textGenerationLayer = Layer.succeed(TextGeneration, {
|
||||
generateBranchName: () => Effect.succeed({ branch: "update" }),
|
||||
generateThreadTitle: () => Effect.succeed({ title: "New thread" }),
|
||||
generateBranchName: () => Effect.succeed({ branch: null }),
|
||||
} as unknown as TextGenerationShape);
|
||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
@@ -360,7 +359,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,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.15",
|
||||
"version": "0.0.14",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -8,33 +8,10 @@ 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) => {
|
||||
@@ -70,36 +47,6 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to reading the inherited fd when path duplication fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
||||
|
||||
yield* fs.writeFileString(
|
||||
filePath,
|
||||
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
|
||||
mode: "desktop",
|
||||
})}\n`,
|
||||
);
|
||||
|
||||
// Open without acquireRelease: the direct-stream fallback uses autoClose: true,
|
||||
// so the stream owns the fd lifecycle and closes it asynchronously on end.
|
||||
// Attempting to also close it synchronously in a finalizer races with the
|
||||
// stream's async close and produces an uncaught EBADF.
|
||||
const fd = NFS.openSync(filePath, "r");
|
||||
|
||||
openSyncInterceptor.failPath = `/proc/self/fd/${fd}`;
|
||||
try {
|
||||
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
|
||||
assertSome(payload, {
|
||||
mode: "desktop",
|
||||
});
|
||||
} finally {
|
||||
openSyncInterceptor.failPath = null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns none when the fd is unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fd = NFS.openSync("/dev/null", "r");
|
||||
|
||||
@@ -108,26 +108,21 @@ const makeBootstrapInputStream = (fd: number) =>
|
||||
try: () => {
|
||||
const fdPath = resolveFdPath(fd);
|
||||
if (fdPath === undefined) {
|
||||
return makeDirectBootstrapStream(fd);
|
||||
const stream = new Net.Socket({
|
||||
fd,
|
||||
readable: true,
|
||||
writable: false,
|
||||
});
|
||||
stream.setEncoding("utf8");
|
||||
return stream;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
const streamFd = NFS.openSync(fdPath, "r");
|
||||
return NFS.createReadStream("", {
|
||||
fd: streamFd,
|
||||
encoding: "utf8",
|
||||
autoClose: true,
|
||||
});
|
||||
},
|
||||
catch: (error) =>
|
||||
new BootstrapError({
|
||||
@@ -136,29 +131,6 @@ 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,
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
import crypto from "node:crypto";
|
||||
import type { IncomingHttpHeaders } from "node:http";
|
||||
|
||||
import { Effect, FileSystem, Layer, Path, Ref, Schema, ServiceMap } from "effect";
|
||||
|
||||
import { ServerConfig, type ServerConfigShape } from "./config";
|
||||
|
||||
const BOOTSTRAP_TOKEN_TTL_MS = 5 * 60 * 1_000;
|
||||
const AUTH_COOKIE_MAX_AGE_SECONDS = 30 * 24 * 60 * 60;
|
||||
const AUTH_COOKIE_NAME = "t3_auth";
|
||||
const BOOTSTRAP_HASH_KEY = "t3_bootstrap";
|
||||
const COOKIE_SECRET_FILENAME = "browser-auth-secret";
|
||||
|
||||
interface BootstrapState {
|
||||
readonly token: string;
|
||||
readonly expiresAt: number;
|
||||
readonly consumedAt: number | null;
|
||||
}
|
||||
|
||||
interface AuthCookiePayload {
|
||||
readonly v: 1;
|
||||
readonly purpose: "browser-auth";
|
||||
readonly iat: number;
|
||||
readonly exp: number;
|
||||
}
|
||||
|
||||
export class BrowserAuthError extends Schema.TaggedErrorClass<BrowserAuthError>()(
|
||||
"BrowserAuthError",
|
||||
{
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
|
||||
export interface BrowserAuthShape {
|
||||
readonly getPairingUrl: (baseUrl: string) => Effect.Effect<string, never>;
|
||||
readonly getAllowedOrigins: Effect.Effect<ReadonlySet<string>, never>;
|
||||
readonly isAllowedOrigin: (origin: string | undefined) => Effect.Effect<boolean, never>;
|
||||
readonly consumeBootstrapToken: (token: string) => Effect.Effect<boolean, never>;
|
||||
readonly isAuthenticatedRequest: (headers: IncomingHttpHeaders) => Effect.Effect<boolean, never>;
|
||||
readonly createAuthCookie: (isSecure: boolean) => Effect.Effect<string, never>;
|
||||
}
|
||||
|
||||
export class BrowserAuth extends ServiceMap.Service<BrowserAuth, BrowserAuthShape>()(
|
||||
"t3/browserAuth",
|
||||
) {}
|
||||
|
||||
function makeBootstrapToken(): string {
|
||||
return crypto.randomBytes(32).toString("base64url");
|
||||
}
|
||||
|
||||
function makeCookieSecret(): string {
|
||||
return crypto.randomBytes(32).toString("base64url");
|
||||
}
|
||||
|
||||
function toBase64Url(input: string): string {
|
||||
return Buffer.from(input, "utf8").toString("base64url");
|
||||
}
|
||||
|
||||
function fromBase64Url(input: string): string {
|
||||
return Buffer.from(input, "base64url").toString("utf8");
|
||||
}
|
||||
|
||||
function signCookie(payload: AuthCookiePayload, secret: string): string {
|
||||
const payloadEncoded = toBase64Url(JSON.stringify(payload));
|
||||
const signature = crypto.createHmac("sha256", secret).update(payloadEncoded).digest("base64url");
|
||||
return `${payloadEncoded}.${signature}`;
|
||||
}
|
||||
|
||||
function verifyCookie(cookie: string, secret: string, now = Date.now()): boolean {
|
||||
const separatorIndex = cookie.lastIndexOf(".");
|
||||
if (separatorIndex <= 0 || separatorIndex >= cookie.length - 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const payloadEncoded = cookie.slice(0, separatorIndex);
|
||||
const providedSignature = cookie.slice(separatorIndex + 1);
|
||||
const expectedSignature = crypto
|
||||
.createHmac("sha256", secret)
|
||||
.update(payloadEncoded)
|
||||
.digest("base64url");
|
||||
|
||||
const providedBuffer = Buffer.from(providedSignature, "utf8");
|
||||
const expectedBuffer = Buffer.from(expectedSignature, "utf8");
|
||||
if (providedBuffer.length !== expectedBuffer.length) {
|
||||
return false;
|
||||
}
|
||||
if (!crypto.timingSafeEqual(providedBuffer, expectedBuffer)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(fromBase64Url(payloadEncoded)) as Partial<AuthCookiePayload>;
|
||||
if (parsed.v !== 1 || parsed.purpose !== "browser-auth") {
|
||||
return false;
|
||||
}
|
||||
if (typeof parsed.exp !== "number" || !Number.isFinite(parsed.exp)) {
|
||||
return false;
|
||||
}
|
||||
return parsed.exp > now;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function parseCookies(cookieHeader: string | string[] | undefined): Map<string, string> {
|
||||
const raw = Array.isArray(cookieHeader) ? cookieHeader.join("; ") : cookieHeader;
|
||||
if (!raw) return new Map();
|
||||
|
||||
const cookies = new Map<string, string>();
|
||||
for (const segment of raw.split(";")) {
|
||||
const trimmed = segment.trim();
|
||||
if (trimmed.length === 0) continue;
|
||||
const separatorIndex = trimmed.indexOf("=");
|
||||
if (separatorIndex <= 0) continue;
|
||||
const key = trimmed.slice(0, separatorIndex).trim();
|
||||
const value = trimmed.slice(separatorIndex + 1).trim();
|
||||
if (key.length === 0 || value.length === 0) continue;
|
||||
cookies.set(key, value);
|
||||
}
|
||||
return cookies;
|
||||
}
|
||||
|
||||
function normalizeOriginSet(serverConfig: ServerConfigShape): ReadonlySet<string> {
|
||||
const origins = new Set<string>();
|
||||
origins.add(`http://localhost:${serverConfig.port}`);
|
||||
origins.add(`http://127.0.0.1:${serverConfig.port}`);
|
||||
origins.add(`http://[::1]:${serverConfig.port}`);
|
||||
|
||||
if (
|
||||
serverConfig.host &&
|
||||
serverConfig.host !== "0.0.0.0" &&
|
||||
serverConfig.host !== "::" &&
|
||||
serverConfig.host !== "[::]"
|
||||
) {
|
||||
const host =
|
||||
serverConfig.host.includes(":") && !serverConfig.host.startsWith("[")
|
||||
? `[${serverConfig.host}]`
|
||||
: serverConfig.host;
|
||||
origins.add(`http://${host}:${serverConfig.port}`);
|
||||
}
|
||||
|
||||
if (serverConfig.devUrl) {
|
||||
origins.add(serverConfig.devUrl.origin);
|
||||
}
|
||||
|
||||
return origins;
|
||||
}
|
||||
|
||||
function formatAuthCookie(cookieValue: string, isSecure: boolean): string {
|
||||
const attributes = [
|
||||
`${AUTH_COOKIE_NAME}=${cookieValue}`,
|
||||
"HttpOnly",
|
||||
"Path=/",
|
||||
"SameSite=Strict",
|
||||
`Max-Age=${AUTH_COOKIE_MAX_AGE_SECONDS}`,
|
||||
];
|
||||
if (isSecure) {
|
||||
attributes.push("Secure");
|
||||
}
|
||||
return attributes.join("; ");
|
||||
}
|
||||
|
||||
export const BrowserAuthLive = Layer.effect(
|
||||
BrowserAuth,
|
||||
Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const cookieSecretPath = path.join(serverConfig.stateDir, COOKIE_SECRET_FILENAME);
|
||||
|
||||
const existingSecret = yield* fileSystem
|
||||
.readFileString(cookieSecretPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
const cookieSecret =
|
||||
existingSecret && existingSecret.trim().length > 0
|
||||
? existingSecret.trim()
|
||||
: makeCookieSecret();
|
||||
|
||||
if (existingSecret === null || existingSecret.trim().length === 0) {
|
||||
yield* fileSystem.makeDirectory(path.dirname(cookieSecretPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(cookieSecretPath, `${cookieSecret}\n`);
|
||||
}
|
||||
|
||||
const bootstrapState = yield* Ref.make<BootstrapState>({
|
||||
token: makeBootstrapToken(),
|
||||
expiresAt: Date.now() + BOOTSTRAP_TOKEN_TTL_MS,
|
||||
consumedAt: null,
|
||||
});
|
||||
const allowedOrigins = normalizeOriginSet(serverConfig);
|
||||
|
||||
const getPairingUrl: BrowserAuthShape["getPairingUrl"] = (baseUrl) =>
|
||||
Ref.get(bootstrapState).pipe(
|
||||
Effect.map((state) => {
|
||||
const target = new URL(baseUrl);
|
||||
target.hash = `${BOOTSTRAP_HASH_KEY}=${state.token}`;
|
||||
return target.toString();
|
||||
}),
|
||||
);
|
||||
|
||||
const isAllowedOrigin: BrowserAuthShape["isAllowedOrigin"] = (origin) =>
|
||||
Effect.succeed(typeof origin === "string" && allowedOrigins.has(origin));
|
||||
|
||||
const consumeBootstrapToken: BrowserAuthShape["consumeBootstrapToken"] = (token) =>
|
||||
Ref.modify(bootstrapState, (state) => {
|
||||
const now = Date.now();
|
||||
const matches =
|
||||
token.length > 0 &&
|
||||
state.consumedAt === null &&
|
||||
state.expiresAt > now &&
|
||||
state.token === token;
|
||||
return [matches, matches ? { ...state, consumedAt: now } : state] as const;
|
||||
});
|
||||
|
||||
const isAuthenticatedRequest: BrowserAuthShape["isAuthenticatedRequest"] = (headers) =>
|
||||
Effect.succeed(
|
||||
verifyCookie(parseCookies(headers.cookie).get(AUTH_COOKIE_NAME) ?? "", cookieSecret),
|
||||
);
|
||||
|
||||
const createAuthCookie: BrowserAuthShape["createAuthCookie"] = (isSecure) =>
|
||||
Effect.succeed(
|
||||
formatAuthCookie(
|
||||
signCookie(
|
||||
{
|
||||
v: 1,
|
||||
purpose: "browser-auth",
|
||||
iat: Date.now(),
|
||||
exp: Date.now() + AUTH_COOKIE_MAX_AGE_SECONDS * 1_000,
|
||||
},
|
||||
cookieSecret,
|
||||
),
|
||||
isSecure,
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
getPairingUrl,
|
||||
getAllowedOrigins: Effect.succeed(allowedOrigins),
|
||||
isAllowedOrigin,
|
||||
consumeBootstrapToken,
|
||||
isAuthenticatedRequest,
|
||||
createAuthCookie,
|
||||
} satisfies BrowserAuthShape;
|
||||
}),
|
||||
);
|
||||
@@ -61,7 +61,6 @@ function makeSnapshot(input: {
|
||||
},
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
import path from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||
import { CheckpointStoreLive } from "./CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../Services/CheckpointStore.ts";
|
||||
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { GitCommandError } from "../../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");
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -207,42 +207,6 @@ describe("classifyCodexStderrLine", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("process stderr events", () => {
|
||||
it("emits classified stderr lines as notifications", () => {
|
||||
const manager = new CodexAppServerManager();
|
||||
const emitEvent = vi
|
||||
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
|
||||
.mockImplementation(() => {});
|
||||
|
||||
(
|
||||
manager as unknown as {
|
||||
emitNotificationEvent: (
|
||||
context: { session: { threadId: ThreadId } },
|
||||
method: string,
|
||||
message: string,
|
||||
) => void;
|
||||
}
|
||||
).emitNotificationEvent(
|
||||
{
|
||||
session: {
|
||||
threadId: asThreadId("thread-1"),
|
||||
},
|
||||
},
|
||||
"process/stderr",
|
||||
"fatal: permission denied",
|
||||
);
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
kind: "notification",
|
||||
method: "process/stderr",
|
||||
threadId: "thread-1",
|
||||
message: "fatal: permission denied",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeCodexModelSlug", () => {
|
||||
it("maps 5.3 aliases to gpt-5.3-codex", () => {
|
||||
expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
|
||||
@@ -310,7 +274,7 @@ describe("readCodexAccountSnapshot", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("disables spark for api key accounts", () => {
|
||||
it("keeps spark enabled for api key accounts", () => {
|
||||
expect(
|
||||
readCodexAccountSnapshot({
|
||||
type: "apiKey",
|
||||
@@ -318,20 +282,7 @@ describe("readCodexAccountSnapshot", () => {
|
||||
).toEqual({
|
||||
type: "apiKey",
|
||||
planType: null,
|
||||
sparkEnabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("disables spark for unknown chatgpt plans", () => {
|
||||
expect(
|
||||
readCodexAccountSnapshot({
|
||||
type: "chatgpt",
|
||||
email: "[email protected]",
|
||||
}),
|
||||
).toEqual({
|
||||
type: "chatgpt",
|
||||
planType: "unknown",
|
||||
sparkEnabled: false,
|
||||
sparkEnabled: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -356,16 +307,6 @@ describe("resolveCodexModelForAccount", () => {
|
||||
}),
|
||||
).toBe("gpt-5.3-codex-spark");
|
||||
});
|
||||
|
||||
it("falls back from spark to default for api key auth", () => {
|
||||
expect(
|
||||
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
|
||||
type: "apiKey",
|
||||
planType: null,
|
||||
sparkEnabled: false,
|
||||
}),
|
||||
).toBe("gpt-5.3-codex");
|
||||
});
|
||||
});
|
||||
|
||||
describe("startSession", () => {
|
||||
|
||||
@@ -26,15 +26,6 @@ import {
|
||||
isCodexCliVersionSupported,
|
||||
parseCodexCliVersion,
|
||||
} from "./provider/codexCliVersion";
|
||||
import {
|
||||
readCodexAccountSnapshot,
|
||||
resolveCodexModelForAccount,
|
||||
type CodexAccountSnapshot,
|
||||
} from "./provider/codexAccount";
|
||||
import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer";
|
||||
|
||||
export { buildCodexInitializeParams } from "./provider/codexAppServer";
|
||||
export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount";
|
||||
|
||||
type PendingRequestKey = string;
|
||||
|
||||
@@ -105,6 +96,23 @@ 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;
|
||||
@@ -154,6 +162,50 @@ 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.
|
||||
@@ -306,13 +358,32 @@ 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 {
|
||||
killCodexChildProcess(child);
|
||||
if (process.platform === "win32" && child.pid !== undefined) {
|
||||
try {
|
||||
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
||||
return;
|
||||
} catch {
|
||||
// fallback to direct kill
|
||||
}
|
||||
}
|
||||
child.kill();
|
||||
}
|
||||
|
||||
export function normalizeCodexModelSlug(
|
||||
@@ -331,6 +402,19 @@ 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;
|
||||
@@ -962,7 +1046,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
continue;
|
||||
}
|
||||
|
||||
this.emitNotificationEvent(context, "process/stderr", classified.message);
|
||||
this.emitErrorEvent(context, "process/stderr", classified.message);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1270,22 +1354,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
}
|
||||
|
||||
private emitNotificationEvent(
|
||||
context: CodexSessionContext,
|
||||
method: string,
|
||||
message: string,
|
||||
): void {
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method,
|
||||
message,
|
||||
});
|
||||
}
|
||||
|
||||
private emitEvent(event: ProviderEvent): void {
|
||||
this.emit("event", event);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ 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";
|
||||
|
||||
@@ -248,62 +247,4 @@ 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");
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -13,7 +13,6 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { ClaudeModelSelection } from "@t3tools/contracts";
|
||||
import { resolveApiModelId } from "@t3tools/shared/model";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
import { toJsonSchemaObject } from "@t3tools/shared/schemaJson";
|
||||
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
|
||||
@@ -21,17 +20,15 @@ import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "../Prompts.ts";
|
||||
import {
|
||||
normalizeCliError,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
toJsonSchemaObject,
|
||||
} from "../Utils.ts";
|
||||
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
|
||||
import { normalizeClaudeModelOptions } from "../../provider/Layers/ClaudeProvider.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts";
|
||||
|
||||
const CLAUDE_TIMEOUT_MS = 180_000;
|
||||
|
||||
@@ -73,11 +70,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||
outputSchemaJson,
|
||||
modelSelection,
|
||||
}: {
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
@@ -85,8 +78,8 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
|
||||
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
|
||||
getClaudeModelCapabilities(modelSelection.model),
|
||||
const normalizedOptions = normalizeClaudeModelOptions(
|
||||
modelSelection.model,
|
||||
modelSelection.options,
|
||||
);
|
||||
const settings = {
|
||||
@@ -306,39 +299,10 @@ 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;
|
||||
});
|
||||
|
||||
|
||||
@@ -358,70 +358,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("generates thread titles and trims them for sidebar use", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
title:
|
||||
' "Investigate websocket reconnect regressions after worktree restore" \nignored line',
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Please investigate websocket reconnect regressions after a worktree restore.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("Investigate websocket reconnect regressions aft...");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("falls back when thread title normalization becomes whitespace-only", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
title: ' """ """ ',
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Name this thread.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("New thread");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("trims whitespace exposed after quote removal in thread titles", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
title: ` "' hello world '" `,
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Name this thread.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("hello world");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("omits attachment metadata section when no attachments are provided", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
|
||||
@@ -5,14 +5,12 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { CodexModelSelection } from "@t3tools/contracts";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
import { toJsonSchemaObject } from "@t3tools/shared/schemaJson";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import {
|
||||
type BranchNameGenerationInput,
|
||||
type ThreadTitleGenerationResult,
|
||||
type TextGenerationShape,
|
||||
TextGeneration,
|
||||
} from "../Services/TextGeneration.ts";
|
||||
@@ -20,20 +18,19 @@ 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 { normalizeCodexModelOptions } 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;
|
||||
@@ -86,11 +83,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
const materializeImageAttachments = (
|
||||
_operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle",
|
||||
_operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName",
|
||||
attachments: BranchNameGenerationInput["attachments"],
|
||||
): Effect.Effect<MaterializedImageAttachments, TextGenerationError> =>
|
||||
Effect.gen(function* () {
|
||||
@@ -131,11 +124,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
cleanupPaths = [],
|
||||
modelSelection,
|
||||
}: {
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
@@ -157,8 +146,8 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
).pipe(Effect.catch(() => Effect.undefined));
|
||||
|
||||
const runCodexCommand = Effect.gen(function* () {
|
||||
const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
|
||||
getCodexModelCapabilities(modelSelection.model),
|
||||
const normalizedOptions = normalizeCodexModelOptions(
|
||||
modelSelection.model,
|
||||
modelSelection.options,
|
||||
);
|
||||
const reasoningEffort =
|
||||
@@ -374,44 +363,10 @@ 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;
|
||||
});
|
||||
|
||||
|
||||
@@ -132,12 +132,6 @@ function commitWithDate(
|
||||
});
|
||||
}
|
||||
|
||||
function buildLargeText(lineCount = 20_000): string {
|
||||
return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`)
|
||||
.join("\n")
|
||||
.concat("\n");
|
||||
}
|
||||
|
||||
// ── Tests ──
|
||||
|
||||
it.layer(TestLayer)("git integration", (it) => {
|
||||
@@ -421,9 +415,6 @@ 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();
|
||||
@@ -458,7 +449,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
const core = yield* GitCore;
|
||||
yield* Effect.promise(() =>
|
||||
vi.waitFor(async () => {
|
||||
const details = await runPromise(core.statusDetails(source));
|
||||
const details = await Effect.runPromise(core.statusDetails(source));
|
||||
expect(details.branch).toBe(featureBranch);
|
||||
expect(details.aheadCount).toBe(0);
|
||||
expect(details.behindCount).toBe(1);
|
||||
@@ -1676,40 +1667,6 @@ 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();
|
||||
|
||||
+1364
-1395
File diff suppressed because it is too large.
Load diff
@@ -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, ModelSelection } from "@t3tools/contracts";
|
||||
import type { GitActionProgressEvent } from "@t3tools/contracts";
|
||||
|
||||
import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts";
|
||||
import { type GitManagerShape } from "../Services/GitManager.ts";
|
||||
@@ -49,7 +49,6 @@ interface FakeGitTextGeneration {
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
includeBranch?: boolean;
|
||||
modelSelection: ModelSelection;
|
||||
}) => Effect.Effect<
|
||||
{ subject: string; body: string; branch?: string | undefined },
|
||||
TextGenerationError
|
||||
@@ -61,18 +60,11 @@ 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"]>;
|
||||
@@ -176,10 +168,6 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): T
|
||||
Effect.succeed({
|
||||
branch: "update-workflow",
|
||||
}),
|
||||
generateThreadTitle: () =>
|
||||
Effect.succeed({
|
||||
title: "Update workflow",
|
||||
}),
|
||||
...overrides,
|
||||
};
|
||||
|
||||
@@ -217,17 +205,6 @@ 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 } : {}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -525,7 +502,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,7 +47,6 @@ 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;
|
||||
});
|
||||
|
||||
|
||||
@@ -4,9 +4,8 @@ import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./Prompts.ts";
|
||||
import { normalizeCliError, sanitizeThreadTitle } from "./Utils.ts";
|
||||
import { normalizeCliError } from "./Utils.ts";
|
||||
import { TextGenerationError } from "./Errors.ts";
|
||||
|
||||
describe("buildCommitMessagePrompt", () => {
|
||||
@@ -104,48 +103,6 @@ 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(
|
||||
|
||||
@@ -119,24 +119,19 @@ export interface BranchNamePromptInput {
|
||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
}
|
||||
|
||||
interface PromptFromMessageInput {
|
||||
instruction: string;
|
||||
responseShape: string;
|
||||
rules: ReadonlyArray<string>;
|
||||
message: string;
|
||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
}
|
||||
|
||||
function buildPromptFromMessage(input: PromptFromMessageInput): string {
|
||||
export function buildBranchNamePrompt(input: BranchNamePromptInput) {
|
||||
const attachmentLines = (input.attachments ?? []).map(
|
||||
(attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
|
||||
);
|
||||
|
||||
const promptSections = [
|
||||
input.instruction,
|
||||
input.responseShape,
|
||||
"You generate concise git branch names.",
|
||||
"Return a JSON object with key: branch.",
|
||||
"Rules:",
|
||||
...input.rules.map((rule) => `- ${rule}`),
|
||||
"- Branch should describe the requested work from the user message.",
|
||||
"- Keep it short and specific (2-6 words).",
|
||||
"- Use plain words only, no issue prefixes and no punctuation-heavy text.",
|
||||
"- If images are attached, use them as primary context for visual/UI issues.",
|
||||
"",
|
||||
"User message:",
|
||||
limitSection(input.message, 8_000),
|
||||
@@ -149,54 +144,10 @@ function buildPromptFromMessage(input: PromptFromMessageInput): string {
|
||||
);
|
||||
}
|
||||
|
||||
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 prompt = promptSections.join("\n");
|
||||
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 };
|
||||
}
|
||||
@@ -32,7 +32,6 @@ export interface ExecuteGitInput {
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly truncateOutputAtMaxBytes?: boolean;
|
||||
readonly progress?: ExecuteGitProgress;
|
||||
}
|
||||
|
||||
|
||||
@@ -61,25 +61,12 @@ 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>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -106,13 +93,6 @@ 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>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -14,6 +14,15 @@ export function isGitRepository(cwd: string): boolean {
|
||||
return existsSync(join(cwd, ".git"));
|
||||
}
|
||||
|
||||
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
|
||||
export function toJsonSchemaObject(schema: Schema.Top): unknown {
|
||||
const document = Schema.toJsonSchemaDocument(schema);
|
||||
if (document.definitions && Object.keys(document.definitions).length > 0) {
|
||||
return { ...document.schema, $defs: document.definitions };
|
||||
}
|
||||
return document.schema;
|
||||
}
|
||||
|
||||
/** Truncate a text section to `maxChars`, appending a `[truncated]` marker when needed. */
|
||||
export function limitSection(value: string, maxChars: number): string {
|
||||
if (value.length <= maxChars) return value;
|
||||
@@ -44,27 +53,6 @@ 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);
|
||||
|
||||
@@ -165,19 +165,6 @@ 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;
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
MAX_WHEN_EXPRESSION_DEPTH,
|
||||
ResolvedKeybindingRule,
|
||||
ResolvedKeybindingsConfig,
|
||||
THREAD_JUMP_KEYBINDING_COMMANDS,
|
||||
type ServerConfigIssue,
|
||||
} from "@t3tools/contracts";
|
||||
import { Mutable } from "effect/Types";
|
||||
@@ -34,6 +33,7 @@ import {
|
||||
Predicate,
|
||||
PubSub,
|
||||
Schema,
|
||||
SchemaGetter,
|
||||
SchemaIssue,
|
||||
SchemaTransformation,
|
||||
Ref,
|
||||
@@ -43,7 +43,7 @@ import {
|
||||
} from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { ServerConfig } from "./config";
|
||||
import { encodePrettyJsonEffect, fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
|
||||
export class KeybindingsConfigError extends Schema.TaggedErrorClass<KeybindingsConfigError>()(
|
||||
"KeybindingsConfigParseError",
|
||||
@@ -76,12 +76,6 @@ 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 {
|
||||
@@ -417,7 +411,16 @@ function encodeWhenAst(node: KeybindingWhenNode): string {
|
||||
const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
|
||||
|
||||
const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
|
||||
const encodeKeybindingsConfigPrettyJson = encodePrettyJsonEffect(KeybindingsConfig);
|
||||
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
|
||||
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
|
||||
SchemaGetter.stringifyJson({ space: 2 }),
|
||||
);
|
||||
const KeybindingsConfigPrettyJson = KeybindingsConfigJson.pipe(
|
||||
Schema.encode({
|
||||
decode: PrettyJsonString,
|
||||
encode: PrettyJsonString,
|
||||
}),
|
||||
);
|
||||
|
||||
export interface KeybindingsConfigState {
|
||||
readonly keybindings: ResolvedKeybindingsConfig;
|
||||
@@ -666,7 +669,7 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
|
||||
const tempPath = `${keybindingsConfigPath}.${process.pid}.${Date.now()}.tmp`;
|
||||
|
||||
return encodeKeybindingsConfigPrettyJson(rules).pipe(
|
||||
return Schema.encodeEffect(KeybindingsConfigPrettyJson)(rules).pipe(
|
||||
Effect.map((encoded) => `${encoded}\n`),
|
||||
Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })),
|
||||
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
|
||||
|
||||
@@ -21,7 +21,6 @@ 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* () {
|
||||
@@ -37,7 +36,7 @@ const findAvailablePort = vi.fn((preferred: number) => Effect.succeed(preferred)
|
||||
const testLayer = Layer.mergeAll(
|
||||
Layer.succeed(CliConfig, {
|
||||
cwd: "/tmp/t3-test-workspace",
|
||||
fixPath: Effect.sync(fixPath),
|
||||
fixPath: Effect.void,
|
||||
resolveStaticDir: Effect.undefined,
|
||||
} satisfies CliConfigShape),
|
||||
Layer.succeed(NetService, {
|
||||
@@ -82,7 +81,6 @@ beforeEach(() => {
|
||||
resolvedConfig = null;
|
||||
start.mockImplementation(() => undefined);
|
||||
stop.mockImplementation(() => undefined);
|
||||
fixPath.mockImplementation(() => undefined);
|
||||
findAvailablePort.mockImplementation((preferred: number) => Effect.succeed(preferred));
|
||||
});
|
||||
|
||||
@@ -261,7 +259,7 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
assert.equal(resolvedConfig?.port, 4666);
|
||||
assert.equal(resolvedConfig?.host, undefined);
|
||||
assert.equal(resolvedConfig?.host, "127.0.0.1");
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -303,6 +301,19 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses fixed loopback defaults in web mode", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli([], {
|
||||
T3CODE_MODE: "web",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
assert.equal(resolvedConfig?.host, "127.0.0.1");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("allows overriding desktop host with --host", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--host", "0.0.0.0"], {
|
||||
@@ -331,21 +342,6 @@ 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(
|
||||
@@ -385,7 +381,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"]).pipe(Effect.catch(() => Effect.void));
|
||||
yield* runCli(["--mode", "invalid"]);
|
||||
|
||||
assert.equal(start.mock.calls.length, 0);
|
||||
assert.equal(stop.mock.calls.length, 0);
|
||||
@@ -403,7 +399,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"]).pipe(Effect.catch(() => Effect.void));
|
||||
yield* runCli(["--port", "70000"]);
|
||||
|
||||
// effect/unstable/cli renders help/errors for parse failures and returns success.
|
||||
assert.equal(start.mock.calls.length, 0);
|
||||
|
||||
+37
-13
@@ -29,6 +29,7 @@ import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
import { readBootstrapEnvelope } from "./bootstrap";
|
||||
import { ServerSettingsLive } from "./serverSettings";
|
||||
import { BrowserAuth, BrowserAuthLive } from "./browserAuth";
|
||||
|
||||
export class StartupError extends Data.TaggedError("StartupError")<{
|
||||
readonly message: string;
|
||||
@@ -268,7 +269,7 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
Option.fromUndefinedOr(env.host),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
|
||||
),
|
||||
() => (mode === "desktop" ? "127.0.0.1" : undefined),
|
||||
() => "127.0.0.1",
|
||||
);
|
||||
|
||||
const config: ServerConfigShape = {
|
||||
@@ -291,20 +292,28 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
);
|
||||
|
||||
const LayerLive = (input: CliInput) =>
|
||||
Layer.empty.pipe(
|
||||
Layer.provideMerge(makeServerRuntimeServicesLayer()),
|
||||
Layer.provideMerge(makeServerProviderLayer()),
|
||||
Layer.provideMerge(ProviderRegistryLive),
|
||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||
Layer.provideMerge(ServerLoggerLive),
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(ServerConfigLive(input)),
|
||||
);
|
||||
(() => {
|
||||
const serverConfigLayer = ServerConfigLive(input);
|
||||
const browserAuthLayer = BrowserAuthLive.pipe(Layer.provide(serverConfigLayer));
|
||||
return Layer.empty.pipe(
|
||||
Layer.provideMerge(makeServerRuntimeServicesLayer()),
|
||||
Layer.provideMerge(makeServerProviderLayer()),
|
||||
Layer.provideMerge(ProviderRegistryLive),
|
||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||
Layer.provideMerge(ServerLoggerLive),
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(serverConfigLayer),
|
||||
Layer.provideMerge(browserAuthLayer),
|
||||
);
|
||||
})();
|
||||
|
||||
const isWildcardHost = (host: string | undefined): boolean =>
|
||||
host === "0.0.0.0" || host === "::" || host === "[::]";
|
||||
|
||||
const isLoopbackHost = (host: string | undefined): boolean =>
|
||||
host === "127.0.0.1" || host === "::1" || host === "[::1]" || host === "localhost";
|
||||
|
||||
const formatHostForUrl = (host: string): string =>
|
||||
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
||||
|
||||
@@ -337,6 +346,7 @@ const makeServerRuntimeProgram = (input: CliInput) =>
|
||||
Effect.gen(function* () {
|
||||
const { start, stopSignal } = yield* Server;
|
||||
const openDeps = yield* Open;
|
||||
const browserAuth = yield* BrowserAuth;
|
||||
|
||||
const config = yield* ServerConfig;
|
||||
|
||||
@@ -357,15 +367,29 @@ const makeServerRuntimeProgram = (input: CliInput) =>
|
||||
config.host && !isWildcardHost(config.host)
|
||||
? `http://${formatHostForUrl(config.host)}:${config.port}`
|
||||
: localUrl;
|
||||
const browserBaseUrl =
|
||||
config.host && !isWildcardHost(config.host) && !isLoopbackHost(config.host)
|
||||
? bindUrl
|
||||
: localUrl;
|
||||
const pairingUrl = yield* browserAuth.getPairingUrl(browserBaseUrl);
|
||||
const { authToken, devUrl, ...safeConfig } = config;
|
||||
yield* Effect.logInfo("T3 Code running", {
|
||||
...safeConfig,
|
||||
devUrl: devUrl?.toString(),
|
||||
authEnabled: Boolean(authToken),
|
||||
localUrl,
|
||||
pairingUrl,
|
||||
});
|
||||
|
||||
if (config.host && !isWildcardHost(config.host) && !isLoopbackHost(config.host)) {
|
||||
yield* Effect.logWarning("server is exposed beyond loopback", {
|
||||
host: config.host,
|
||||
bindUrl,
|
||||
});
|
||||
}
|
||||
|
||||
if (!config.noBrowser) {
|
||||
const target = config.devUrl?.toString() ?? bindUrl;
|
||||
const target = pairingUrl;
|
||||
yield* openDeps.openBrowser(target).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.logInfo("browser auto-open unavailable", {
|
||||
@@ -416,7 +440,7 @@ const noBrowserFlag = Flag.boolean("no-browser").pipe(
|
||||
Flag.optional,
|
||||
);
|
||||
const authTokenFlag = Flag.string("auth-token").pipe(
|
||||
Flag.withDescription("Auth token required for WebSocket connections."),
|
||||
Flag.withDescription("Legacy auth token for non-browser WebSocket clients."),
|
||||
Flag.withAlias("token"),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
@@ -271,7 +271,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();
|
||||
|
||||
@@ -766,7 +766,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const worker = yield* makeDrainableWorker(processInputSafely);
|
||||
|
||||
const start: CheckpointReactorShape["start"] = Effect.fn("start")(function* () {
|
||||
const start: CheckpointReactorShape["start"] = Effect.gen(function* () {
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
|
||||
if (
|
||||
|
||||
@@ -120,73 +120,6 @@ 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,28 +24,25 @@ describe("OrchestrationReactor", () => {
|
||||
Layer.effect(OrchestrationReactor, makeOrchestrationReactor).pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProviderRuntimeIngestionService, {
|
||||
start: () => {
|
||||
start: Effect.sync(() => {
|
||||
started.push("provider-runtime-ingestion");
|
||||
return Effect.void;
|
||||
},
|
||||
}),
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProviderCommandReactor, {
|
||||
start: () => {
|
||||
start: Effect.sync(() => {
|
||||
started.push("provider-command-reactor");
|
||||
return Effect.void;
|
||||
},
|
||||
}),
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(CheckpointReactor, {
|
||||
start: () => {
|
||||
start: Effect.sync(() => {
|
||||
started.push("checkpoint-reactor");
|
||||
return Effect.void;
|
||||
},
|
||||
}),
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
@@ -54,7 +51,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.fn("start")(function* () {
|
||||
yield* providerRuntimeIngestion.start();
|
||||
yield* providerCommandReactor.start();
|
||||
yield* checkpointReactor.start();
|
||||
const start: OrchestrationReactorShape["start"] = Effect.gen(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("materializeAttachmentsForProjection")(
|
||||
const materializeAttachmentsForProjection = Effect.fn(
|
||||
(input: { readonly attachments: ReadonlyArray<ChatAttachment> }) =>
|
||||
Effect.succeed(input.attachments.length === 0 ? [] : input.attachments),
|
||||
);
|
||||
@@ -238,145 +238,124 @@ function collectThreadAttachmentRelativePaths(
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
const runAttachmentSideEffects = Effect.fn("runAttachmentSideEffects")(function* (
|
||||
sideEffects: AttachmentSideEffects,
|
||||
) {
|
||||
const runAttachmentSideEffects = Effect.fn(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>)));
|
||||
|
||||
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,
|
||||
});
|
||||
},
|
||||
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 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]) =>
|
||||
pruneThreadAttachments(threadId, keptThreadRelativePaths),
|
||||
([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 },
|
||||
);
|
||||
});
|
||||
},
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
});
|
||||
|
||||
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 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 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"] = Effect.fn(
|
||||
"applyProjectsProjection",
|
||||
)(function* (event, _attachmentSideEffects) {
|
||||
const applyProjectsProjection: ProjectorDefinition["apply"] = (event, _attachmentSideEffects) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "project.created":
|
||||
yield* projectionProjectRepository.upsert({
|
||||
@@ -433,9 +412,8 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadsProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyThreadsProjection",
|
||||
)(function* (event, attachmentSideEffects) {
|
||||
const applyThreadsProjection: ProjectorDefinition["apply"] = (event, attachmentSideEffects) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.created":
|
||||
yield* projectionThreadRepository.upsert({
|
||||
@@ -450,41 +428,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
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,
|
||||
@@ -619,9 +566,11 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadMessagesProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyThreadMessagesProjection",
|
||||
)(function* (event, attachmentSideEffects) {
|
||||
const applyThreadMessagesProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.message-sent": {
|
||||
const existingRows = yield* projectionThreadMessageRepository.listByThreadId({
|
||||
@@ -694,9 +643,11 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadProposedPlansProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyThreadProposedPlansProjection",
|
||||
)(function* (event, _attachmentSideEffects) {
|
||||
const applyThreadProposedPlansProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.proposed-plan-upserted":
|
||||
yield* projectionThreadProposedPlanRepository.upsert({
|
||||
@@ -745,9 +696,11 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyThreadActivitiesProjection",
|
||||
)(function* (event, _attachmentSideEffects) {
|
||||
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.activity-appended":
|
||||
yield* projectionThreadActivityRepository.upsert({
|
||||
@@ -797,9 +750,11 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyThreadSessionsProjection",
|
||||
)(function* (event, _attachmentSideEffects) {
|
||||
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
if (event.type !== "thread.session-set") {
|
||||
return;
|
||||
}
|
||||
@@ -814,9 +769,11 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
});
|
||||
});
|
||||
|
||||
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyThreadTurnsProjection",
|
||||
)(function* (event, _attachmentSideEffects) {
|
||||
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.turn-start-requested": {
|
||||
yield* projectionTurnRepository.replacePendingTurnStart({
|
||||
@@ -1070,11 +1027,13 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
}
|
||||
});
|
||||
|
||||
const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void;
|
||||
const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void;
|
||||
|
||||
const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyPendingApprovalsProjection",
|
||||
)(function* (event, _attachmentSideEffects) {
|
||||
const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.activity-appended": {
|
||||
const requestId =
|
||||
@@ -1160,49 +1119,47 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
}
|
||||
});
|
||||
|
||||
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 = Effect.fn("runProjectorForEvent")(function* (
|
||||
projector: ProjectorDefinition,
|
||||
event: OrchestrationEvent,
|
||||
) {
|
||||
const runProjectorForEvent = (projector: ProjectorDefinition, event: OrchestrationEvent) =>
|
||||
Effect.gen(function* () {
|
||||
const attachmentSideEffects: AttachmentSideEffects = {
|
||||
deletedThreadIds: new Set<string>(),
|
||||
prunedThreadRelativePaths: new Map<string, Set<string>>(),
|
||||
@@ -1232,64 +1189,63 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
);
|
||||
});
|
||||
|
||||
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),
|
||||
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),
|
||||
),
|
||||
);
|
||||
|
||||
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 bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.forEach(
|
||||
projectors,
|
||||
bootstrapProjector,
|
||||
{ concurrency: 1 },
|
||||
).pipe(
|
||||
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.tap(() =>
|
||||
Effect.log("orchestration projection pipeline bootstrapped").pipe(
|
||||
Effect.annotateLogs({ projectors: projectors.length }),
|
||||
),
|
||||
),
|
||||
Effect.catchTag("SqlError", (sqlError) =>
|
||||
Effect.fail(toPersistenceSqlError("ProjectionPipeline.bootstrap:query")(sqlError)),
|
||||
Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
bootstrap,
|
||||
projectEvent,
|
||||
} satisfies OrchestrationProjectionPipelineShape;
|
||||
},
|
||||
);
|
||||
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;
|
||||
});
|
||||
|
||||
export const OrchestrationProjectionPipelineLive = Layer.effect(
|
||||
OrchestrationProjectionPipeline,
|
||||
makeOrchestrationProjectionPipeline(),
|
||||
makeOrchestrationProjectionPipeline,
|
||||
).pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(ProjectionProjectRepositoryLive),
|
||||
|
||||
@@ -279,7 +279,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
},
|
||||
createdAt: "2026-02-24T00:00:02.000Z",
|
||||
updatedAt: "2026-02-24T00:00:03.000Z",
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [
|
||||
{
|
||||
|
||||
@@ -174,7 +174,6 @@ 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
|
||||
@@ -561,7 +560,6 @@ 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<TextGenerationShape["generateBranchName"]>((_) =>
|
||||
const generateBranchName = vi.fn(() =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation: "generateBranchName",
|
||||
@@ -184,14 +184,6 @@ 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 = {
|
||||
@@ -221,10 +213,7 @@ describe("ProviderCommandReactor", () => {
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, service)),
|
||||
Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)),
|
||||
Layer.provideMerge(
|
||||
Layer.mock(TextGeneration, {
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
}),
|
||||
Layer.succeed(TextGeneration, { generateBranchName } as unknown as TextGenerationShape),
|
||||
),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
|
||||
@@ -235,7 +224,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(
|
||||
@@ -275,7 +264,6 @@ describe("ProviderCommandReactor", () => {
|
||||
stopSession,
|
||||
renameBranch,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
stateDir,
|
||||
drain,
|
||||
};
|
||||
@@ -320,199 +308,6 @@ 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();
|
||||
|
||||
@@ -73,19 +73,6 @@ 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);
|
||||
@@ -413,6 +400,7 @@ 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>;
|
||||
}) {
|
||||
@@ -423,6 +411,16 @@ 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 ?? [];
|
||||
@@ -461,49 +459,6 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
});
|
||||
|
||||
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* (
|
||||
event: Extract<ProviderIntentEvent, { type: "thread.turn-start-requested" }>,
|
||||
) {
|
||||
@@ -530,35 +485,14 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
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* 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);
|
||||
|
||||
yield* sendTurnForThread({
|
||||
threadId: event.payload.threadId,
|
||||
@@ -773,24 +707,22 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const worker = yield* makeDrainableWorker(processDomainEventSafely);
|
||||
|
||||
const start: ProviderCommandReactorShape["start"] = Effect.fn("start")(function* () {
|
||||
const processEvent = Effect.fn("processEvent")(function* (event: OrchestrationEvent) {
|
||||
const start: ProviderCommandReactorShape["start"] = Effect.forkScoped(
|
||||
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
|
||||
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 yield* worker.enqueue(event);
|
||||
return Effect.void;
|
||||
}
|
||||
});
|
||||
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(orchestrationEngine.streamDomainEvents, processEvent),
|
||||
);
|
||||
});
|
||||
return worker.enqueue(event);
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
return {
|
||||
start,
|
||||
|
||||
@@ -4,6 +4,7 @@ import path from "node:path";
|
||||
|
||||
import type {
|
||||
OrchestrationReadModel,
|
||||
ProviderKind,
|
||||
ProviderRuntimeEvent,
|
||||
ProviderSession,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -55,7 +56,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: ProviderRuntimeEvent["provider"];
|
||||
readonly provider: ProviderKind;
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -65,23 +66,6 @@ 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[] = [];
|
||||
@@ -109,23 +93,8 @@ 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, normalizeLegacyEvent(event)));
|
||||
Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent));
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -214,7 +183,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();
|
||||
@@ -1726,37 +1695,6 @@ 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();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,12 +3,10 @@ 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,
|
||||
@@ -28,12 +26,10 @@ 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,7 +66,6 @@ const readModel: OrchestrationReadModel = {
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: null,
|
||||
@@ -89,7 +88,6 @@ const readModel: OrchestrationReadModel = {
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: null,
|
||||
|
||||
@@ -88,44 +88,6 @@ 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;
|
||||
|
||||
@@ -10,12 +10,11 @@ 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",
|
||||
@@ -191,51 +190,6 @@ 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,
|
||||
@@ -375,7 +329,6 @@ 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,7 +87,6 @@ describe("orchestration projector", () => {
|
||||
latestTurn: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
@@ -132,78 +131,6 @@ 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,14 +14,12 @@ import {
|
||||
ProjectDeletedPayload,
|
||||
ProjectMetaUpdatedPayload,
|
||||
ThreadActivityAppendedPayload,
|
||||
ThreadArchivedPayload,
|
||||
ThreadCreatedPayload,
|
||||
ThreadDeletedPayload,
|
||||
ThreadInteractionModeSetPayload,
|
||||
ThreadMetaUpdatedPayload,
|
||||
ThreadProposedPlanUpsertedPayload,
|
||||
ThreadRuntimeModeSetPayload,
|
||||
ThreadUnarchivedPayload,
|
||||
ThreadRevertedPayload,
|
||||
ThreadSessionSetPayload,
|
||||
ThreadTurnDiffCompletedPayload,
|
||||
@@ -262,7 +260,6 @@ export function projectEvent(
|
||||
latestTurn: null,
|
||||
createdAt: payload.createdAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
@@ -292,28 +289,6 @@ 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) => ({
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -1,25 +1,15 @@
|
||||
import * as OS from "node:os";
|
||||
import { Effect, Path } from "effect";
|
||||
import { readPathFromLoginShell, resolveLoginShell } from "@t3tools/shared/shell";
|
||||
import { readPathFromLoginShell } from "@t3tools/shared/shell";
|
||||
|
||||
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;
|
||||
export function fixPath(): void {
|
||||
if (process.platform !== "darwin") return;
|
||||
|
||||
try {
|
||||
const shell = resolveLoginShell(platform, env.SHELL);
|
||||
if (!shell) return;
|
||||
const result = (options.readPath ?? readPathFromLoginShell)(shell);
|
||||
const shell = process.env.SHELL ?? "/bin/zsh";
|
||||
const result = readPathFromLoginShell(shell);
|
||||
if (result) {
|
||||
env.PATH = result;
|
||||
process.env.PATH = result;
|
||||
}
|
||||
} catch {
|
||||
// Silently ignore — keep default PATH
|
||||
|
||||
@@ -87,7 +87,6 @@ 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,7 +39,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
latest_turn_id,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
@@ -54,7 +53,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.latestTurnId},
|
||||
${row.createdAt},
|
||||
${row.updatedAt},
|
||||
${row.archivedAt},
|
||||
${row.deletedAt}
|
||||
)
|
||||
ON CONFLICT (thread_id)
|
||||
@@ -69,7 +67,6 @@ 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
|
||||
`,
|
||||
});
|
||||
@@ -91,7 +88,6 @@ 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}
|
||||
@@ -115,7 +111,6 @@ 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,8 +29,6 @@ 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.
|
||||
@@ -59,8 +57,6 @@ 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,20 +128,6 @@ 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',
|
||||
@@ -298,16 +284,6 @@ 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",
|
||||
@@ -327,7 +303,7 @@ layer("016_CanonicalizeModelSelections", (it) => {
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[4]!.payloadJson), {
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[3]!.payloadJson), {
|
||||
threadId: "thread-2",
|
||||
projectId: "project-1",
|
||||
title: "Fallback Thread",
|
||||
@@ -346,7 +322,7 @@ layer("016_CanonicalizeModelSelections", (it) => {
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[5]!.payloadJson), {
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[4]!.payloadJson), {
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
input: "hi",
|
||||
@@ -360,7 +336,7 @@ layer("016_CanonicalizeModelSelections", (it) => {
|
||||
deliveryMode: "buffered",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[6]!.payloadJson), {
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[5]!.payloadJson), {
|
||||
threadId: "thread-3",
|
||||
projectId: "project-1",
|
||||
title: "Ancient Thread",
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
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
|
||||
`;
|
||||
});
|
||||
@@ -1,11 +0,0 @@
|
||||
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, classifySqliteError } from "effect/unstable/sql/SqlError";
|
||||
import { SqlError } from "effect/unstable/sql/SqlError";
|
||||
import * as Statement from "effect/unstable/sql/Statement";
|
||||
|
||||
const ATTR_DB_SYSTEM_NAME = "db.system.name";
|
||||
@@ -109,13 +109,7 @@ const makeWithDatabase = (
|
||||
lookup: (sql: string) =>
|
||||
Effect.try({
|
||||
try: () => db.prepare(sql),
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to prepare statement",
|
||||
operation: "prepare",
|
||||
}),
|
||||
}),
|
||||
catch: (cause) => new SqlError({ cause, message: "Failed to prepare statement" }),
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -133,14 +127,7 @@ 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({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to execute statement",
|
||||
operation: "execute",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
return Effect.fail(new SqlError({ cause, message: "Failed to execute statement" }));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -163,13 +150,7 @@ const makeWithDatabase = (
|
||||
statement.run(...(params as any));
|
||||
return [];
|
||||
},
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to execute statement",
|
||||
operation: "execute",
|
||||
}),
|
||||
}),
|
||||
catch: (cause) => new SqlError({ cause, message: "Failed to execute statement" }),
|
||||
}),
|
||||
(statement) =>
|
||||
Effect.sync(() => {
|
||||
|
||||
@@ -32,7 +32,6 @@ 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;
|
||||
|
||||
@@ -37,7 +37,7 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un
|
||||
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
|
||||
}
|
||||
|
||||
export function isWindowsCommandNotFound(code: number | null, stderr: string): boolean {
|
||||
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);
|
||||
|
||||
@@ -1100,13 +1100,10 @@ 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 = runFork(
|
||||
const runtimeEventsFiber = Effect.runFork(
|
||||
Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
@@ -1200,12 +1197,9 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const services = yield* Effect.services();
|
||||
const runFork = Effect.runForkWith(services);
|
||||
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = runFork(
|
||||
const runtimeEventsFiber = Effect.runFork(
|
||||
Stream.runForEach(adapter.streamEvents, () => Effect.void),
|
||||
);
|
||||
|
||||
@@ -2390,85 +2384,6 @@ 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
@@ -1,25 +1,25 @@
|
||||
import type {
|
||||
ClaudeSettings,
|
||||
ClaudeModelOptions,
|
||||
ModelCapabilities,
|
||||
ServerProvider,
|
||||
ServerProviderModel,
|
||||
ServerProviderAuth,
|
||||
ServerProviderAuthStatus,
|
||||
ServerProviderState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect";
|
||||
import { Effect, Equal, Layer, Option, Result, 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 { resolveContextWindow, resolveEffort } from "@t3tools/shared/model";
|
||||
|
||||
import {
|
||||
buildServerProvider,
|
||||
collectStreamAsString,
|
||||
DEFAULT_TIMEOUT_MS,
|
||||
detailFromResult,
|
||||
extractAuthBoolean,
|
||||
isCommandMissingCause,
|
||||
parseGenericCliVersion,
|
||||
providerModelsFromSettings,
|
||||
spawnAndCollect,
|
||||
type CommandResult,
|
||||
} from "../providerSnapshot";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider";
|
||||
@@ -43,8 +43,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
} satisfies ModelCapabilities,
|
||||
@@ -63,8 +63,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
} satisfies ModelCapabilities,
|
||||
@@ -96,9 +96,28 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo
|
||||
);
|
||||
}
|
||||
|
||||
export function normalizeClaudeModelOptions(
|
||||
model: string | null | undefined,
|
||||
modelOptions: ClaudeModelOptions | null | undefined,
|
||||
): ClaudeModelOptions | undefined {
|
||||
const caps = getClaudeModelCapabilities(model);
|
||||
const effort = resolveEffort(caps, modelOptions?.effort);
|
||||
const thinking =
|
||||
caps.supportsThinkingToggle && modelOptions?.thinking === false ? false : undefined;
|
||||
const fastMode = caps.supportsFastMode && modelOptions?.fastMode === true ? true : undefined;
|
||||
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
|
||||
const nextOptions: ClaudeModelOptions = {
|
||||
...(thinking === false ? { thinking: false } : {}),
|
||||
...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
...(contextWindow ? { contextWindow } : {}),
|
||||
};
|
||||
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
|
||||
}
|
||||
|
||||
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
|
||||
readonly status: Exclude<ServerProviderState, "disabled">;
|
||||
readonly auth: Pick<ServerProviderAuth, "status">;
|
||||
readonly authStatus: ServerProviderAuthStatus;
|
||||
readonly message?: string;
|
||||
} {
|
||||
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
|
||||
@@ -110,7 +129,7 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
|
||||
) {
|
||||
return {
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
"Claude Agent authentication status command is unavailable in this version of Claude.",
|
||||
};
|
||||
@@ -125,7 +144,7 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
|
||||
) {
|
||||
return {
|
||||
status: "error",
|
||||
auth: { status: "unauthenticated" },
|
||||
authStatus: "unauthenticated",
|
||||
message: "Claude is not authenticated. Run `claude auth login` and try again.",
|
||||
};
|
||||
}
|
||||
@@ -146,288 +165,40 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
|
||||
})();
|
||||
|
||||
if (parsedAuth.auth === true) {
|
||||
return { status: "ready", auth: { status: "authenticated" } };
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
}
|
||||
if (parsedAuth.auth === false) {
|
||||
return {
|
||||
status: "error",
|
||||
auth: { status: "unauthenticated" },
|
||||
authStatus: "unauthenticated",
|
||||
message: "Claude is not authenticated. Run `claude auth login` and try again.",
|
||||
};
|
||||
}
|
||||
if (parsedAuth.attemptedJsonParse) {
|
||||
return {
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
"Could not verify Claude authentication status from JSON output (missing auth marker).",
|
||||
};
|
||||
}
|
||||
if (result.code === 0) {
|
||||
return { status: "ready", auth: { status: "authenticated" } };
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
}
|
||||
|
||||
const detail = detailFromResult(result);
|
||||
return {
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
authStatus: "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 spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
|
||||
Effect.flatMap((service) => service.getSettings),
|
||||
Effect.map((settings) => settings.providers.claudeAgent),
|
||||
@@ -435,84 +206,158 @@ const runClaudeCommand = (args: ReadonlyArray<string>) =>
|
||||
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);
|
||||
const child = yield* spawner.spawn(command);
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectStreamAsString(child.stdout),
|
||||
collectStreamAsString(child.stderr),
|
||||
child.exitCode.pipe(Effect.map(Number)),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
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.",
|
||||
},
|
||||
});
|
||||
}
|
||||
return { stdout, stderr, code: exitCode } satisfies CommandResult;
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
function* (): Effect.fn.Return<
|
||||
ServerProvider,
|
||||
ServerSettingsError,
|
||||
ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
|
||||
> {
|
||||
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
|
||||
Effect.flatMap((service) => service.getSettings),
|
||||
Effect.map((settings) => settings.providers.claudeAgent),
|
||||
);
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(
|
||||
BUILT_IN_MODELS,
|
||||
PROVIDER,
|
||||
claudeSettings.customModels,
|
||||
);
|
||||
|
||||
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 (!claudeSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Claude is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (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 versionProbe = yield* runClaudeCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
const version = versionProbe.success.value;
|
||||
const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
|
||||
if (version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: !isCommandMissingCause(error),
|
||||
version: null,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: isCommandMissingCause(error)
|
||||
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
|
||||
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (Option.isNone(versionProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
"Claude Agent CLI is installed but failed to run. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const version = versionProbe.success.value;
|
||||
const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
|
||||
if (version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: detail
|
||||
? `Claude Agent CLI is installed but failed to run. ${detail}`
|
||||
: "Claude Agent CLI is installed but failed to run.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
error instanceof Error
|
||||
? `Could not verify Claude authentication status: ${error.message}.`
|
||||
: "Could not verify Claude authentication status.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (Option.isNone(authProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
"Could not verify Claude authentication status. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
@@ -521,99 +366,13 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
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.",
|
||||
status: parsed.status,
|
||||
authStatus: parsed.authStatus,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ── 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,
|
||||
@@ -621,16 +380,7 @@ export const ClaudeProviderLive = Layer.effect(
|
||||
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(
|
||||
const checkProvider = checkClaudeProviderStatus().pipe(
|
||||
Effect.provideService(ServerSettingsService, serverSettings),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
|
||||
@@ -474,40 +474,6 @@ 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;
|
||||
|
||||
@@ -20,7 +20,6 @@ import {
|
||||
ProviderItemId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
ProviderSendTurnInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, FileSystem, Layer, Queue, Schema, ServiceMap, Stream } from "effect";
|
||||
|
||||
@@ -1268,19 +1267,6 @@ 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 [
|
||||
{
|
||||
@@ -1328,40 +1314,38 @@ function mapToRuntimeEvents(
|
||||
return [];
|
||||
}
|
||||
|
||||
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 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 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 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 serverSettingsService = yield* ServerSettingsService;
|
||||
|
||||
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) {
|
||||
const startSession: CodexAdapterShape["startSession"] = Effect.fn(function* (input) {
|
||||
if (input.provider !== undefined && input.provider !== PROVIDER) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
@@ -1410,212 +1394,211 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
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 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 bytes = yield* fileSystem.readFile(attachmentPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRequestError({
|
||||
|
||||
const rollbackThread: CodexAdapterShape["rollbackThread"] = (threadId, numTurns) => {
|
||||
if (!Number.isInteger(numTurns) || numTurns < 1) {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
method: "turn/start",
|
||||
detail: toMessage(cause, "Failed to read attachment file."),
|
||||
cause,
|
||||
operation: "rollbackThread",
|
||||
issue: "numTurns must be an integer >= 1.",
|
||||
}),
|
||||
),
|
||||
);
|
||||
return {
|
||||
type: "image" as const,
|
||||
url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`,
|
||||
};
|
||||
});
|
||||
|
||||
const sendTurn: CodexAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {
|
||||
const codexAttachments = yield* Effect.forEach(
|
||||
input.attachments ?? [],
|
||||
(attachment) => resolveAttachment(input, attachment),
|
||||
{ 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 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;
|
||||
|
||||
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>();
|
||||
|
||||
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);
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
provider: PROVIDER,
|
||||
capabilities: {
|
||||
sessionModelSwitch: "in-session",
|
||||
},
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
readThread,
|
||||
rollbackThread,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions,
|
||||
hasSession,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromQueue(runtimeEventQueue),
|
||||
} satisfies CodexAdapterShape;
|
||||
});
|
||||
|
||||
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) {
|
||||
|
||||
@@ -1,35 +1,26 @@
|
||||
import * as OS from "node:os";
|
||||
import type {
|
||||
ModelCapabilities,
|
||||
CodexModelOptions,
|
||||
CodexSettings,
|
||||
ServerProvider,
|
||||
ServerProviderModel,
|
||||
ServerProviderAuth,
|
||||
ServerProviderAuthStatus,
|
||||
ServerProviderState,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
Cache,
|
||||
Duration,
|
||||
Effect,
|
||||
Equal,
|
||||
FileSystem,
|
||||
Layer,
|
||||
Option,
|
||||
Path,
|
||||
Result,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import { Effect, Equal, FileSystem, Layer, Option, Path, Result, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { resolveEffort } from "@t3tools/shared/model";
|
||||
|
||||
import {
|
||||
buildServerProvider,
|
||||
collectStreamAsString,
|
||||
DEFAULT_TIMEOUT_MS,
|
||||
detailFromResult,
|
||||
extractAuthBoolean,
|
||||
isCommandMissingCause,
|
||||
parseGenericCliVersion,
|
||||
providerModelsFromSettings,
|
||||
spawnAndCollect,
|
||||
type CommandResult,
|
||||
} from "../providerSnapshot";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider";
|
||||
@@ -38,13 +29,6 @@ import {
|
||||
isCodexCliVersionSupported,
|
||||
parseCodexCliVersion,
|
||||
} from "../codexCliVersion";
|
||||
import {
|
||||
adjustCodexModelsForAccount,
|
||||
codexAuthSubLabel,
|
||||
codexAuthSubType,
|
||||
type CodexAccountSnapshot,
|
||||
} from "../codexAccount";
|
||||
import { probeCodexAccount } from "../codexAppServer";
|
||||
import { CodexProvider } from "../Services/CodexProvider";
|
||||
import { ServerSettingsError, ServerSettingsService } from "../../serverSettings";
|
||||
|
||||
@@ -168,9 +152,25 @@ export function getCodexModelCapabilities(model: string | null | undefined): Mod
|
||||
);
|
||||
}
|
||||
|
||||
export function normalizeCodexModelOptions(
|
||||
model: string | null | undefined,
|
||||
modelOptions: CodexModelOptions | null | undefined,
|
||||
): CodexModelOptions | undefined {
|
||||
const caps = getCodexModelCapabilities(model);
|
||||
const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort);
|
||||
const fastModeEnabled = modelOptions?.fastMode === true;
|
||||
const nextOptions: CodexModelOptions = {
|
||||
...(reasoningEffort
|
||||
? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] }
|
||||
: {}),
|
||||
...(fastModeEnabled ? { fastMode: true } : {}),
|
||||
};
|
||||
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
|
||||
}
|
||||
|
||||
export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
readonly status: Exclude<ServerProviderState, "disabled">;
|
||||
readonly auth: Pick<ServerProviderAuth, "status">;
|
||||
readonly authStatus: ServerProviderAuthStatus;
|
||||
readonly message?: string;
|
||||
} {
|
||||
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
|
||||
@@ -182,7 +182,7 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
) {
|
||||
return {
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
authStatus: "unknown",
|
||||
message: "Codex CLI authentication status command is unavailable in this Codex version.",
|
||||
};
|
||||
}
|
||||
@@ -196,7 +196,7 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
) {
|
||||
return {
|
||||
status: "error",
|
||||
auth: { status: "unauthenticated" },
|
||||
authStatus: "unauthenticated",
|
||||
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
};
|
||||
}
|
||||
@@ -217,31 +217,31 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
})();
|
||||
|
||||
if (parsedAuth.auth === true) {
|
||||
return { status: "ready", auth: { status: "authenticated" } };
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
}
|
||||
if (parsedAuth.auth === false) {
|
||||
return {
|
||||
status: "error",
|
||||
auth: { status: "unauthenticated" },
|
||||
authStatus: "unauthenticated",
|
||||
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
};
|
||||
}
|
||||
if (parsedAuth.attemptedJsonParse) {
|
||||
return {
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
"Could not verify Codex authentication status from JSON output (missing auth marker).",
|
||||
};
|
||||
}
|
||||
if (result.code === 0) {
|
||||
return { status: "ready", auth: { status: "authenticated" } };
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
}
|
||||
|
||||
const detail = detailFromResult(result);
|
||||
return {
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
authStatus: "unknown",
|
||||
message: detail
|
||||
? `Could not verify Codex authentication status. ${detail}`
|
||||
: "Could not verify Codex authentication status.",
|
||||
@@ -290,23 +290,9 @@ export const hasCustomModelProvider = readCodexConfigModelProvider().pipe(
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
|
||||
const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
|
||||
|
||||
const probeCodexCapabilities = (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
}) =>
|
||||
Effect.tryPromise((signal) => probeCodexAccount({ ...input, signal })).pipe(
|
||||
Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
Effect.map((result) => {
|
||||
if (Result.isFailure(result)) return undefined;
|
||||
return Option.isSome(result.success) ? result.success.value : undefined;
|
||||
}),
|
||||
);
|
||||
|
||||
const runCodexCommand = (args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const settingsService = yield* ServerSettingsService;
|
||||
const codexSettings = yield* settingsService.getSettings.pipe(
|
||||
Effect.map((settings) => settings.providers.codex),
|
||||
@@ -318,91 +304,193 @@ const runCodexCommand = (args: ReadonlyArray<string>) =>
|
||||
...(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);
|
||||
const child = yield* spawner.spawn(command);
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectStreamAsString(child.stdout),
|
||||
collectStreamAsString(child.stderr),
|
||||
child.exitCode.pipe(Effect.map(Number)),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
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.",
|
||||
},
|
||||
});
|
||||
}
|
||||
return { stdout, stderr, code: exitCode } satisfies CommandResult;
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(
|
||||
function* (): Effect.fn.Return<
|
||||
ServerProvider,
|
||||
ServerSettingsError,
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| Path.Path
|
||||
| ServerSettingsService
|
||||
> {
|
||||
const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
|
||||
Effect.flatMap((service) => service.getSettings),
|
||||
Effect.map((settings) => settings.providers.codex),
|
||||
);
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(
|
||||
BUILT_IN_MODELS,
|
||||
PROVIDER,
|
||||
codexSettings.customModels,
|
||||
);
|
||||
|
||||
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 (!codexSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Codex is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (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 versionProbe = yield* runCodexCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
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);
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: !isCommandMissingCause(error),
|
||||
version: null,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: isCommandMissingCause(error)
|
||||
? "Codex CLI (`codex`) is not installed or not on PATH."
|
||||
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (Option.isNone(versionProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: "Codex CLI is installed but failed to run. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const version = versionProbe.success.value;
|
||||
const parsedVersion =
|
||||
parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ??
|
||||
parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
|
||||
if (version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: detail
|
||||
? `Codex CLI is installed but failed to run. ${detail}`
|
||||
: "Codex CLI is installed but failed to run.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: formatCodexCliUpgradeMessage(parsedVersion),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (yield* hasCustomModelProvider) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "ready",
|
||||
authStatus: "unknown",
|
||||
message: "Using a custom Codex model provider; OpenAI login check skipped.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
error instanceof Error
|
||||
? `Could not verify Codex authentication status: ${error.message}.`
|
||||
: "Could not verify Codex authentication status.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (Option.isNone(authProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Could not verify Codex authentication status. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
@@ -411,116 +499,13 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
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.",
|
||||
status: parsed.status,
|
||||
authStatus: parsed.authStatus,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -529,21 +514,8 @@ export const CodexProviderLive = Layer.effect(
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const accountProbeCache = yield* Cache.make({
|
||||
capacity: 4,
|
||||
timeToLive: Duration.minutes(5),
|
||||
lookup: (key: string) => {
|
||||
const [binaryPath, homePath] = JSON.parse(key) as [string, string | undefined];
|
||||
return probeCodexCapabilities({
|
||||
binaryPath,
|
||||
...(homePath ? { homePath } : {}),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const checkProvider = checkCodexProviderStatus((input) =>
|
||||
Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath])),
|
||||
).pipe(
|
||||
const checkProvider = checkCodexProviderStatus().pipe(
|
||||
Effect.provideService(ServerSettingsService, serverSettings),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
|
||||
@@ -173,7 +173,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
@@ -186,186 +186,58 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns the codex plan type in auth and keeps spark for supported plans", () =>
|
||||
it.effect("inherits PATH when launching the codex probe with a CODEX_HOME override", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus(() =>
|
||||
Effect.succeed({
|
||||
type: "chatgpt" as const,
|
||||
planType: "pro" as const,
|
||||
sparkEnabled: true,
|
||||
}),
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const binDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-test-codex-bin-",
|
||||
});
|
||||
const codexPath = path.join(binDir, "codex");
|
||||
yield* fileSystem.writeFileString(
|
||||
codexPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
'if [ "$1" = "--version" ]; then',
|
||||
' echo "codex-cli 1.0.0"',
|
||||
" exit 0",
|
||||
"fi",
|
||||
'if [ "$1" = "login" ] && [ "$2" = "status" ]; then',
|
||||
' echo "Logged in using ChatGPT"',
|
||||
" exit 0",
|
||||
"fi",
|
||||
'echo "unexpected args: $*" >&2',
|
||||
"exit 1",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* fileSystem.chmod(codexPath, 0o755);
|
||||
const customCodexHome = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-test-codex-home-",
|
||||
});
|
||||
const previousPath = process.env.PATH;
|
||||
process.env.PATH = binDir;
|
||||
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
assert.strictEqual(status.auth.type, "pro");
|
||||
assert.strictEqual(status.auth.label, "ChatGPT Pro Subscription");
|
||||
assert.deepStrictEqual(
|
||||
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
|
||||
true,
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("hides spark from codex models for unsupported chatgpt plans", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus(() =>
|
||||
Effect.succeed({
|
||||
type: "chatgpt" as const,
|
||||
planType: "plus" as const,
|
||||
sparkEnabled: false,
|
||||
}),
|
||||
);
|
||||
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
assert.strictEqual(status.auth.type, "plus");
|
||||
assert.strictEqual(status.auth.label, "ChatGPT Plus Subscription");
|
||||
assert.deepStrictEqual(
|
||||
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
|
||||
false,
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("hides spark from codex models for non-pro chatgpt subscriptions", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus(() =>
|
||||
Effect.succeed({
|
||||
type: "chatgpt" as const,
|
||||
planType: "team" as const,
|
||||
sparkEnabled: false,
|
||||
}),
|
||||
);
|
||||
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.auth.type, "team");
|
||||
assert.strictEqual(status.auth.label, "ChatGPT Team Subscription");
|
||||
assert.deepStrictEqual(
|
||||
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
|
||||
false,
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns an api key label for codex api key auth", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus(() =>
|
||||
Effect.succeed({
|
||||
type: "apiKey" as const,
|
||||
planType: null,
|
||||
sparkEnabled: false,
|
||||
}),
|
||||
);
|
||||
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
assert.strictEqual(status.auth.type, "apiKey");
|
||||
assert.strictEqual(status.auth.label, "OpenAI API Key");
|
||||
assert.deepStrictEqual(
|
||||
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
|
||||
false,
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
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.skipIf(process.platform === "win32")(
|
||||
"inherits PATH when launching the codex probe with a CODEX_HOME override",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const binDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-test-codex-bin-",
|
||||
});
|
||||
const codexPath = path.join(binDir, "codex");
|
||||
yield* fileSystem.writeFileString(
|
||||
codexPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
'if [ "$1" = "--version" ]; then',
|
||||
' echo "codex-cli 1.0.0"',
|
||||
" exit 0",
|
||||
"fi",
|
||||
'if [ "$1" = "login" ] && [ "$2" = "status" ]; then',
|
||||
' echo "Logged in using ChatGPT"',
|
||||
" exit 0",
|
||||
"fi",
|
||||
'echo "unexpected args: $*" >&2',
|
||||
"exit 1",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* fileSystem.chmod(codexPath, 0o755);
|
||||
const customCodexHome = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-test-codex-home-",
|
||||
});
|
||||
const previousPath = process.env.PATH;
|
||||
process.env.PATH = binDir;
|
||||
|
||||
try {
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
codex: {
|
||||
homePath: customCodexHome,
|
||||
},
|
||||
try {
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
codex: {
|
||||
homePath: customCodexHome,
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* checkCodexProviderStatus().pipe(
|
||||
Effect.provide(serverSettingsLayer),
|
||||
);
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
} finally {
|
||||
process.env.PATH = previousPath;
|
||||
}
|
||||
}),
|
||||
const status = yield* checkCodexProviderStatus().pipe(
|
||||
Effect.provide(serverSettingsLayer),
|
||||
);
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
} finally {
|
||||
process.env.PATH = previousPath;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when codex is missing", () =>
|
||||
@@ -375,7 +247,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, false);
|
||||
assert.strictEqual(status.auth.status, "unknown");
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI (`codex`) is not installed or not on PATH.",
|
||||
@@ -390,7 +262,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.auth.status, "unknown");
|
||||
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.",
|
||||
@@ -413,7 +285,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.auth.status, "unauthenticated");
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
@@ -439,7 +311,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.auth.status, "unauthenticated");
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
@@ -464,7 +336,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "warning");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.auth.status, "unknown");
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI authentication status command is unavailable in this Codex version.",
|
||||
@@ -492,7 +364,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
authStatus: "authenticated",
|
||||
checkedAt: "2026-03-25T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
@@ -502,7 +374,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
status: "warning",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "unknown" },
|
||||
authStatus: "unknown",
|
||||
checkedAt: "2026-03-25T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
@@ -620,7 +492,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.auth.status, "unknown");
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Using a custom Codex model provider; OpenAI login check skipped.",
|
||||
@@ -663,7 +535,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
const status = yield* checkCodexProviderStatus();
|
||||
// The auth probe runs and sees "not logged in" → error
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.auth.status, "unauthenticated");
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
@@ -684,7 +556,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
it("exit code 0 with no auth markers is ready", () => {
|
||||
const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
|
||||
assert.strictEqual(parsed.status, "ready");
|
||||
assert.strictEqual(parsed.auth.status, "authenticated");
|
||||
assert.strictEqual(parsed.authStatus, "authenticated");
|
||||
});
|
||||
|
||||
it("JSON with authenticated=false is unauthenticated", () => {
|
||||
@@ -694,7 +566,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "error");
|
||||
assert.strictEqual(parsed.auth.status, "unauthenticated");
|
||||
assert.strictEqual(parsed.authStatus, "unauthenticated");
|
||||
});
|
||||
|
||||
it("JSON without auth marker is warning", () => {
|
||||
@@ -704,7 +576,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "warning");
|
||||
assert.strictEqual(parsed.auth.status, "unknown");
|
||||
assert.strictEqual(parsed.authStatus, "unknown");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -841,7 +713,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
@@ -859,63 +731,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns a display label for claude subscription types", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus(() => Effect.succeed("maxplan"));
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
assert.strictEqual(status.auth.type, "maxplan");
|
||||
assert.strictEqual(status.auth.label, "Claude Max Subscription");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns an api key label for claude api key auth", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus();
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
assert.strictEqual(status.auth.type, "apiKey");
|
||||
assert.strictEqual(status.auth.label, "Claude API Key");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"api-key"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when claude is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus();
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, false);
|
||||
assert.strictEqual(status.auth.status, "unknown");
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude Agent CLI (`claude`) is not installed or not on PATH.",
|
||||
@@ -947,7 +769,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.auth.status, "unauthenticated");
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude is not authenticated. Run `claude auth login` and try again.",
|
||||
@@ -975,7 +797,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.auth.status, "unauthenticated");
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
@@ -995,7 +817,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "warning");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.auth.status, "unknown");
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude Agent authentication status command is unavailable in this version of Claude.",
|
||||
@@ -1020,7 +842,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
it("exit code 0 with no auth markers is ready", () => {
|
||||
const parsed = parseClaudeAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
|
||||
assert.strictEqual(parsed.status, "ready");
|
||||
assert.strictEqual(parsed.auth.status, "authenticated");
|
||||
assert.strictEqual(parsed.authStatus, "authenticated");
|
||||
});
|
||||
|
||||
it("JSON with loggedIn=true is authenticated", () => {
|
||||
@@ -1030,7 +852,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "ready");
|
||||
assert.strictEqual(parsed.auth.status, "authenticated");
|
||||
assert.strictEqual(parsed.authStatus, "authenticated");
|
||||
});
|
||||
|
||||
it("JSON with loggedIn=false is unauthenticated", () => {
|
||||
@@ -1040,7 +862,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "error");
|
||||
assert.strictEqual(parsed.auth.status, "unauthenticated");
|
||||
assert.strictEqual(parsed.authStatus, "unauthenticated");
|
||||
});
|
||||
|
||||
it("JSON without auth marker is warning", () => {
|
||||
@@ -1050,7 +872,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "warning");
|
||||
assert.strictEqual(parsed.auth.status, "unknown");
|
||||
assert.strictEqual(parsed.authStatus, "unknown");
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
import type { ServerProviderModel } from "@t3tools/contracts";
|
||||
|
||||
export type CodexPlanType =
|
||||
| "free"
|
||||
| "go"
|
||||
| "plus"
|
||||
| "pro"
|
||||
| "team"
|
||||
| "business"
|
||||
| "enterprise"
|
||||
| "edu"
|
||||
| "unknown";
|
||||
|
||||
export interface CodexAccountSnapshot {
|
||||
readonly type: "apiKey" | "chatgpt" | "unknown";
|
||||
readonly planType: CodexPlanType | null;
|
||||
readonly sparkEnabled: boolean;
|
||||
}
|
||||
|
||||
export const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
|
||||
export const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
|
||||
const CODEX_SPARK_ENABLED_PLAN_TYPES = new Set<CodexPlanType>(["pro"]);
|
||||
|
||||
function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
|
||||
const record = asObject(response);
|
||||
const account = asObject(record?.account) ?? record;
|
||||
const accountType = asString(account?.type);
|
||||
|
||||
if (accountType === "apiKey") {
|
||||
return {
|
||||
type: "apiKey",
|
||||
planType: null,
|
||||
sparkEnabled: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (accountType === "chatgpt") {
|
||||
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
|
||||
return {
|
||||
type: "chatgpt",
|
||||
planType,
|
||||
sparkEnabled: CODEX_SPARK_ENABLED_PLAN_TYPES.has(planType),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
type: "unknown",
|
||||
planType: null,
|
||||
sparkEnabled: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function codexAuthSubType(account: CodexAccountSnapshot | undefined): string | undefined {
|
||||
if (account?.type === "apiKey") {
|
||||
return "apiKey";
|
||||
}
|
||||
|
||||
if (account?.type !== "chatgpt") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return account.planType && account.planType !== "unknown" ? account.planType : "chatgpt";
|
||||
}
|
||||
|
||||
export function codexAuthSubLabel(account: CodexAccountSnapshot | undefined): string | undefined {
|
||||
switch (codexAuthSubType(account)) {
|
||||
case "apiKey":
|
||||
return "OpenAI API Key";
|
||||
case "chatgpt":
|
||||
return "ChatGPT Subscription";
|
||||
case "free":
|
||||
return "ChatGPT Free Subscription";
|
||||
case "go":
|
||||
return "ChatGPT Go Subscription";
|
||||
case "plus":
|
||||
return "ChatGPT Plus Subscription";
|
||||
case "pro":
|
||||
return "ChatGPT Pro Subscription";
|
||||
case "team":
|
||||
return "ChatGPT Team Subscription";
|
||||
case "business":
|
||||
return "ChatGPT Business Subscription";
|
||||
case "enterprise":
|
||||
return "ChatGPT Enterprise Subscription";
|
||||
case "edu":
|
||||
return "ChatGPT Edu Subscription";
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function adjustCodexModelsForAccount(
|
||||
baseModels: ReadonlyArray<ServerProviderModel>,
|
||||
account: CodexAccountSnapshot | undefined,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
if (account?.sparkEnabled !== false) {
|
||||
return baseModels;
|
||||
}
|
||||
|
||||
return baseModels.filter((model) => model.isCustom || model.slug !== CODEX_SPARK_MODEL);
|
||||
}
|
||||
|
||||
export function resolveCodexModelForAccount(
|
||||
model: string | undefined,
|
||||
account: CodexAccountSnapshot,
|
||||
): string | undefined {
|
||||
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
|
||||
return model;
|
||||
}
|
||||
|
||||
return CODEX_DEFAULT_MODEL;
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import readline from "node:readline";
|
||||
import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount";
|
||||
|
||||
interface JsonRpcProbeResponse {
|
||||
readonly id?: unknown;
|
||||
readonly result?: unknown;
|
||||
readonly error?: {
|
||||
readonly message?: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
function readErrorMessage(response: JsonRpcProbeResponse): string | undefined {
|
||||
return typeof response.error?.message === "string" ? response.error.message : undefined;
|
||||
}
|
||||
|
||||
export function buildCodexInitializeParams() {
|
||||
return {
|
||||
clientInfo: {
|
||||
name: "t3code_desktop",
|
||||
title: "T3 Code Desktop",
|
||||
version: "0.1.0",
|
||||
},
|
||||
capabilities: {
|
||||
experimentalApi: true,
|
||||
},
|
||||
} as const;
|
||||
}
|
||||
|
||||
export function killCodexChildProcess(child: ChildProcessWithoutNullStreams): void {
|
||||
if (process.platform === "win32" && child.pid !== undefined) {
|
||||
try {
|
||||
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
||||
return;
|
||||
} catch {
|
||||
// Fall through to direct kill when taskkill is unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
child.kill();
|
||||
}
|
||||
|
||||
export async function probeCodexAccount(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
readonly signal?: AbortSignal;
|
||||
}): Promise<CodexAccountSnapshot> {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const child = spawn(input.binaryPath, ["app-server"], {
|
||||
env: {
|
||||
...process.env,
|
||||
...(input.homePath ? { CODEX_HOME: input.homePath } : {}),
|
||||
},
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
|
||||
let completed = false;
|
||||
|
||||
const cleanup = () => {
|
||||
output.removeAllListeners();
|
||||
output.close();
|
||||
child.removeAllListeners();
|
||||
if (!child.killed) {
|
||||
killCodexChildProcess(child);
|
||||
}
|
||||
};
|
||||
|
||||
const finish = (callback: () => void) => {
|
||||
if (completed) return;
|
||||
completed = true;
|
||||
cleanup();
|
||||
callback();
|
||||
};
|
||||
|
||||
const fail = (error: unknown) =>
|
||||
finish(() =>
|
||||
reject(
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error(`Codex account probe failed: ${String(error)}.`),
|
||||
),
|
||||
);
|
||||
|
||||
if (input.signal?.aborted) {
|
||||
fail(new Error("Codex account probe aborted."));
|
||||
return;
|
||||
}
|
||||
input.signal?.addEventListener("abort", () => fail(new Error("Codex account probe aborted.")));
|
||||
|
||||
const writeMessage = (message: unknown) => {
|
||||
if (!child.stdin.writable) {
|
||||
fail(new Error("Cannot write to codex app-server stdin."));
|
||||
return;
|
||||
}
|
||||
|
||||
child.stdin.write(`${JSON.stringify(message)}\n`);
|
||||
};
|
||||
|
||||
output.on("line", (line) => {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(line);
|
||||
} catch {
|
||||
fail(new Error("Received invalid JSON from codex app-server during account probe."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!parsed || typeof parsed !== "object") {
|
||||
return;
|
||||
}
|
||||
|
||||
const response = parsed as JsonRpcProbeResponse;
|
||||
if (response.id === 1) {
|
||||
const errorMessage = readErrorMessage(response);
|
||||
if (errorMessage) {
|
||||
fail(new Error(`initialize failed: ${errorMessage}`));
|
||||
return;
|
||||
}
|
||||
|
||||
writeMessage({ method: "initialized" });
|
||||
writeMessage({ id: 2, method: "account/read", params: {} });
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.id === 2) {
|
||||
const errorMessage = readErrorMessage(response);
|
||||
if (errorMessage) {
|
||||
fail(new Error(`account/read failed: ${errorMessage}`));
|
||||
return;
|
||||
}
|
||||
|
||||
finish(() => resolve(readCodexAccountSnapshot(response.result)));
|
||||
}
|
||||
});
|
||||
|
||||
child.once("error", fail);
|
||||
child.once("exit", (code, signal) => {
|
||||
if (completed) return;
|
||||
fail(
|
||||
new Error(
|
||||
`codex app-server exited before probe completed (code=${code ?? "null"}, signal=${signal ?? "null"}).`,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
writeMessage({
|
||||
id: 1,
|
||||
method: "initialize",
|
||||
params: buildCodexInitializeParams(),
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,13 +1,11 @@
|
||||
import type {
|
||||
ServerProvider,
|
||||
ServerProviderAuth,
|
||||
ServerProviderAuthStatus,
|
||||
ServerProviderModel,
|
||||
ServerProviderState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { isWindowsCommandNotFound } from "../processRunner";
|
||||
|
||||
export const DEFAULT_TIMEOUT_MS = 4_000;
|
||||
|
||||
@@ -21,7 +19,7 @@ export interface ProviderProbeResult {
|
||||
readonly installed: boolean;
|
||||
readonly version: string | null;
|
||||
readonly status: Exclude<ServerProviderState, "disabled">;
|
||||
readonly auth: ServerProviderAuth;
|
||||
readonly authStatus: ServerProviderAuthStatus;
|
||||
readonly message?: string;
|
||||
}
|
||||
|
||||
@@ -37,26 +35,6 @@ export function isCommandMissingCause(error: unknown): boolean {
|
||||
return lower.includes("enoent") || lower.includes("notfound");
|
||||
}
|
||||
|
||||
export const spawnAndCollect = (binaryPath: string, command: ChildProcess.Command) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const child = yield* spawner.spawn(command);
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectStreamAsString(child.stdout),
|
||||
collectStreamAsString(child.stderr),
|
||||
child.exitCode.pipe(Effect.map(Number)),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const result: CommandResult = { stdout, stderr, code: exitCode };
|
||||
if (isWindowsCommandNotFound(exitCode, stderr)) {
|
||||
return yield* Effect.fail(new Error(`spawn ${binaryPath} ENOENT`));
|
||||
}
|
||||
return result;
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
export function detailFromResult(
|
||||
result: CommandResult & { readonly timedOut?: boolean },
|
||||
): string | undefined {
|
||||
@@ -137,7 +115,7 @@ export function buildServerProvider(input: {
|
||||
installed: input.probe.installed,
|
||||
version: input.probe.version,
|
||||
status: input.enabled ? input.probe.status : "disabled",
|
||||
auth: input.probe.auth,
|
||||
authStatus: input.probe.authStatus,
|
||||
checkedAt: input.checkedAt,
|
||||
...(input.probe.message ? { message: input.probe.message } : {}),
|
||||
models: input.models,
|
||||
|
||||
@@ -104,43 +104,6 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("preserves model when switching providers via textGenerationModelSelection", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
|
||||
// Start with Claude text generation selection
|
||||
yield* serverSettings.updateSettings({
|
||||
textGenerationModelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "high",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Switch to Codex — the stale Claude "effort" in options must not
|
||||
// cause the update to lose the selected model.
|
||||
const next = yield* serverSettings.updateSettings({
|
||||
textGenerationModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepEqual(next.textGenerationModelSelection, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("trims provider path settings when updates are applied", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
@@ -216,50 +179,4 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
});
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("preserves a top-level $schema declaration when rewriting settings", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
yield* fileSystem.writeFileString(
|
||||
serverConfig.settingsPath,
|
||||
`${JSON.stringify(
|
||||
{
|
||||
$schema: "https://t3.codes/schemas/settings/0.0.15.json",
|
||||
providers: {
|
||||
codex: {
|
||||
binaryPath: "/usr/local/bin/codex",
|
||||
},
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
);
|
||||
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
yield* serverSettings.start;
|
||||
yield* serverSettings.updateSettings({
|
||||
providers: {
|
||||
claudeAgent: {
|
||||
binaryPath: "/usr/local/bin/claude",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
|
||||
assert.deepEqual(JSON.parse(raw), {
|
||||
$schema: "https://t3.codes/schemas/settings/0.0.15.json",
|
||||
providers: {
|
||||
codex: {
|
||||
binaryPath: "/usr/local/bin/codex",
|
||||
},
|
||||
claudeAgent: {
|
||||
binaryPath: "/usr/local/bin/claude",
|
||||
},
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
});
|
||||
@@ -27,7 +27,6 @@ import {
|
||||
FileSystem,
|
||||
Layer,
|
||||
Path,
|
||||
Equal,
|
||||
PubSub,
|
||||
Ref,
|
||||
Schema,
|
||||
@@ -39,7 +38,7 @@ import {
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { ServerConfig } from "./config";
|
||||
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
|
||||
import { encodePrettyJsonEffect, fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
|
||||
export class ServerSettingsError extends Schema.TaggedErrorClass<ServerSettingsError>()(
|
||||
"ServerSettingsError",
|
||||
@@ -101,9 +100,6 @@ export class ServerSettingsService extends ServiceMap.Service<
|
||||
}
|
||||
|
||||
const ServerSettingsJson = fromLenientJson(ServerSettings);
|
||||
const UnknownJson = fromLenientJson(Schema.Unknown);
|
||||
const encodeServerSettingsDocument = encodePrettyJsonEffect(Schema.Unknown);
|
||||
const SETTINGS_SCHEMA_DECLARATION_KEY = "$schema";
|
||||
|
||||
const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent"];
|
||||
|
||||
@@ -134,12 +130,9 @@ function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings
|
||||
};
|
||||
}
|
||||
|
||||
// Values under these keys are compared as a whole — never stripped field-by-field.
|
||||
const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set(["textGenerationModelSelection"]);
|
||||
|
||||
function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
|
||||
if (Array.isArray(current) || Array.isArray(defaults)) {
|
||||
return Equal.equals(current, defaults) ? undefined : current;
|
||||
return JSON.stringify(current) === JSON.stringify(defaults) ? undefined : current;
|
||||
}
|
||||
|
||||
if (
|
||||
@@ -153,15 +146,9 @@ function stripDefaultServerSettings(current: unknown, defaults: unknown): unknow
|
||||
const next: Record<string, unknown> = {};
|
||||
|
||||
for (const key of Object.keys(currentRecord)) {
|
||||
if (ATOMIC_SETTINGS_KEYS.has(key)) {
|
||||
if (!Equal.equals(currentRecord[key], defaultsRecord[key])) {
|
||||
next[key] = currentRecord[key];
|
||||
}
|
||||
} else {
|
||||
const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);
|
||||
if (stripped !== undefined) {
|
||||
next[key] = stripped;
|
||||
}
|
||||
const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);
|
||||
if (stripped !== undefined) {
|
||||
next[key] = stripped;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,7 +167,6 @@ const makeServerSettings = Effect.gen(function* () {
|
||||
const changesPubSub = yield* PubSub.unbounded<ServerSettings>();
|
||||
const startedRef = yield* Ref.make(false);
|
||||
const startedDeferred = yield* Deferred.make<void, ServerSettingsError>();
|
||||
const schemaDeclarationRef = yield* Ref.make<string | undefined>(undefined);
|
||||
const watcherScope = yield* Scope.make("sequential");
|
||||
yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
|
||||
|
||||
@@ -211,27 +197,10 @@ const makeServerSettings = Effect.gen(function* () {
|
||||
|
||||
const loadSettingsFromDisk = Effect.gen(function* () {
|
||||
if (!(yield* readConfigExists)) {
|
||||
yield* Ref.set(schemaDeclarationRef, undefined);
|
||||
return DEFAULT_SERVER_SETTINGS;
|
||||
}
|
||||
|
||||
const raw = yield* readRawConfig;
|
||||
const rawJson = Schema.decodeUnknownExit(UnknownJson)(raw);
|
||||
if (rawJson._tag === "Success") {
|
||||
const value = rawJson.value;
|
||||
const valueRecord =
|
||||
value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: undefined;
|
||||
const schemaDeclaration =
|
||||
valueRecord && typeof valueRecord[SETTINGS_SCHEMA_DECLARATION_KEY] === "string"
|
||||
? valueRecord[SETTINGS_SCHEMA_DECLARATION_KEY]
|
||||
: undefined;
|
||||
yield* Ref.set(schemaDeclarationRef, schemaDeclaration);
|
||||
} else {
|
||||
yield* Ref.set(schemaDeclarationRef, undefined);
|
||||
}
|
||||
|
||||
const decoded = Schema.decodeUnknownExit(ServerSettingsJson)(raw);
|
||||
if (decoded._tag === "Failure") {
|
||||
yield* Effect.logWarning("failed to parse settings.json, using defaults", {
|
||||
@@ -253,17 +222,7 @@ const makeServerSettings = Effect.gen(function* () {
|
||||
const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`;
|
||||
const sparseSettings = stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {};
|
||||
|
||||
return Ref.get(schemaDeclarationRef).pipe(
|
||||
Effect.map((schemaDeclaration) =>
|
||||
schemaDeclaration
|
||||
? {
|
||||
[SETTINGS_SCHEMA_DECLARATION_KEY]: schemaDeclaration,
|
||||
...sparseSettings,
|
||||
}
|
||||
: sparseSettings,
|
||||
),
|
||||
Effect.flatMap(encodeServerSettingsDocument),
|
||||
Effect.map((encoded) => `${encoded}\n`),
|
||||
return Effect.succeed(`${JSON.stringify(sparseSettings, null, 2)}\n`).pipe(
|
||||
Effect.tap(() => fs.makeDirectory(pathService.dirname(settingsPath), { recursive: true })),
|
||||
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
|
||||
Effect.flatMap(() => fs.rename(tempPath, settingsPath)),
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -14,81 +14,47 @@ import {
|
||||
TerminalResizeInput,
|
||||
TerminalRestartInput,
|
||||
TerminalSessionSnapshot,
|
||||
TerminalSessionStatus,
|
||||
TerminalWriteInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { PtyProcess } from "./PTY";
|
||||
import { Effect, Schema, ServiceMap } from "effect";
|
||||
|
||||
export class TerminalCwdError extends Schema.TaggedErrorClass<TerminalCwdError>()(
|
||||
"TerminalCwdError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
reason: Schema.Literals(["notFound", "notDirectory", "statFailed"]),
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
if (this.reason === "notDirectory") {
|
||||
return `Terminal cwd is not a directory: ${this.cwd}`;
|
||||
}
|
||||
if (this.reason === "notFound") {
|
||||
return `Terminal cwd does not exist: ${this.cwd}`;
|
||||
}
|
||||
const causeMessage =
|
||||
this.cause && typeof this.cause === "object" && "message" in this.cause
|
||||
? this.cause.message
|
||||
: undefined;
|
||||
return causeMessage
|
||||
? `Failed to access terminal cwd: ${this.cwd} (${causeMessage})`
|
||||
: `Failed to access terminal cwd: ${this.cwd}`;
|
||||
}
|
||||
export class TerminalError extends Schema.TaggedErrorClass<TerminalError>()("TerminalError", {
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {}
|
||||
|
||||
export interface TerminalSessionState {
|
||||
threadId: string;
|
||||
terminalId: string;
|
||||
cwd: string;
|
||||
status: TerminalSessionStatus;
|
||||
pid: number | null;
|
||||
history: string;
|
||||
pendingHistoryControlSequence: string;
|
||||
exitCode: number | null;
|
||||
exitSignal: number | null;
|
||||
updatedAt: string;
|
||||
cols: number;
|
||||
rows: number;
|
||||
process: PtyProcess | null;
|
||||
unsubscribeData: (() => void) | null;
|
||||
unsubscribeExit: (() => void) | null;
|
||||
hasRunningSubprocess: boolean;
|
||||
runtimeEnv: Record<string, string> | null;
|
||||
}
|
||||
|
||||
export class TerminalHistoryError extends Schema.TaggedErrorClass<TerminalHistoryError>()(
|
||||
"TerminalHistoryError",
|
||||
{
|
||||
operation: Schema.Literals(["read", "truncate", "migrate"]),
|
||||
threadId: Schema.String,
|
||||
terminalId: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Failed to ${this.operation} terminal history for thread: ${this.threadId}, terminal: ${this.terminalId}`;
|
||||
}
|
||||
export interface ShellCandidate {
|
||||
shell: string;
|
||||
args?: string[];
|
||||
}
|
||||
|
||||
export class TerminalSessionLookupError extends Schema.TaggedErrorClass<TerminalSessionLookupError>()(
|
||||
"TerminalSessionLookupError",
|
||||
{
|
||||
threadId: Schema.String,
|
||||
terminalId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Unknown terminal thread: ${this.threadId}, terminal: ${this.terminalId}`;
|
||||
}
|
||||
export interface TerminalStartInput extends TerminalOpenInput {
|
||||
cols: number;
|
||||
rows: number;
|
||||
}
|
||||
|
||||
export class TerminalNotRunningError extends Schema.TaggedErrorClass<TerminalNotRunningError>()(
|
||||
"TerminalNotRunningError",
|
||||
{
|
||||
threadId: Schema.String,
|
||||
terminalId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Terminal is not running for thread: ${this.threadId}, terminal: ${this.terminalId}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const TerminalError = Schema.Union([
|
||||
TerminalCwdError,
|
||||
TerminalHistoryError,
|
||||
TerminalSessionLookupError,
|
||||
TerminalNotRunningError,
|
||||
]);
|
||||
export type TerminalError = typeof TerminalError.Type;
|
||||
|
||||
/**
|
||||
* TerminalManagerShape - Service API for terminal session lifecycle operations.
|
||||
*/
|
||||
@@ -135,13 +101,14 @@ export interface TerminalManagerShape {
|
||||
readonly close: (input: TerminalCloseInput) => Effect.Effect<void, TerminalError>;
|
||||
|
||||
/**
|
||||
* Subscribe to terminal runtime events with a direct callback.
|
||||
*
|
||||
* Returns an unsubscribe function.
|
||||
* Subscribe to terminal runtime events.
|
||||
*/
|
||||
readonly subscribe: (
|
||||
listener: (event: TerminalEvent) => Effect.Effect<void>,
|
||||
) => Effect.Effect<() => void>;
|
||||
readonly subscribe: (listener: (event: TerminalEvent) => void) => Effect.Effect<() => void>;
|
||||
|
||||
/**
|
||||
* Dispose all managed terminal resources.
|
||||
*/
|
||||
readonly dispose: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import * as Http from "node:http";
|
||||
import fs from "node:fs";
|
||||
import net from "node:net";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect, Exit, Fiber, Layer, PlatformError, PubSub, Scope, Stream } from "effect";
|
||||
import { Effect, Exit, Layer, PlatformError, PubSub, Scope, Stream } from "effect";
|
||||
import { describe, expect, it, afterEach, vi } from "vitest";
|
||||
import { createServer } from "./wsServer";
|
||||
import WebSocket from "ws";
|
||||
@@ -56,6 +57,7 @@ import { GitCommandError, GitManagerError } from "./git/Errors.ts";
|
||||
import { MigrationError } from "@effect/sql-sqlite-bun/SqliteMigrator";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
|
||||
import { ServerSettingsService } from "./serverSettings.ts";
|
||||
import { BrowserAuth, BrowserAuthLive } from "./browserAuth.ts";
|
||||
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asProviderItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
||||
@@ -74,7 +76,7 @@ const defaultProviderStatuses: ReadonlyArray<ServerProvider> = [
|
||||
installed: true,
|
||||
version: "0.116.0",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
authStatus: "authenticated",
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
models: [],
|
||||
},
|
||||
@@ -90,19 +92,20 @@ const defaultServerSettings = DEFAULT_SERVER_SETTINGS;
|
||||
|
||||
class MockTerminalManager implements TerminalManagerShape {
|
||||
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
|
||||
private readonly eventPubSub = Effect.runSync(PubSub.unbounded<TerminalEvent>());
|
||||
private activeSubscriptions = 0;
|
||||
private readonly listeners = new Set<(event: TerminalEvent) => void>();
|
||||
|
||||
private key(threadId: string, terminalId: string): string {
|
||||
return `${threadId}\u0000${terminalId}`;
|
||||
}
|
||||
|
||||
emitEvent(event: TerminalEvent): void {
|
||||
Effect.runSync(PubSub.publish(this.eventPubSub, event));
|
||||
for (const listener of this.listeners) {
|
||||
listener(event);
|
||||
}
|
||||
}
|
||||
|
||||
subscriptionCount(): number {
|
||||
return this.activeSubscriptions;
|
||||
return this.listeners.size;
|
||||
}
|
||||
|
||||
readonly open: TerminalManagerShape["open"] = (input: TerminalOpenInput) =>
|
||||
@@ -209,15 +212,13 @@ class MockTerminalManager implements TerminalManagerShape {
|
||||
|
||||
readonly subscribe: TerminalManagerShape["subscribe"] = (listener) =>
|
||||
Effect.sync(() => {
|
||||
this.activeSubscriptions += 1;
|
||||
const fiber = Effect.runFork(
|
||||
Stream.runForEach(Stream.fromPubSub(this.eventPubSub), (event) => listener(event)),
|
||||
);
|
||||
this.listeners.add(listener);
|
||||
return () => {
|
||||
this.activeSubscriptions -= 1;
|
||||
Effect.runFork(Fiber.interrupt(fiber).pipe(Effect.ignore));
|
||||
this.listeners.delete(listener);
|
||||
};
|
||||
});
|
||||
|
||||
readonly dispose: TerminalManagerShape["dispose"] = Effect.void;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -246,6 +247,8 @@ interface SocketChannels {
|
||||
}
|
||||
|
||||
const channelsBySocket = new WeakMap<WebSocket, SocketChannels>();
|
||||
let currentBootstrapToken: string | null = null;
|
||||
let currentBrowserCookie: string | null = null;
|
||||
|
||||
function enqueue<T>(channel: MessageChannel<T>, item: T) {
|
||||
const waiter = channel.waiters.shift();
|
||||
@@ -291,10 +294,46 @@ function asWebSocketResponse(message: unknown): WebSocketResponse | null {
|
||||
return message as WebSocketResponse;
|
||||
}
|
||||
|
||||
function connectWsOnce(port: number, token?: string): Promise<WebSocket> {
|
||||
interface ConnectWsOptions {
|
||||
readonly token?: string;
|
||||
readonly headers?: Record<string, string>;
|
||||
}
|
||||
|
||||
async function pairBrowserSession(
|
||||
port: number,
|
||||
origin = `http://127.0.0.1:${port}`,
|
||||
): Promise<string> {
|
||||
if (!currentBootstrapToken) {
|
||||
throw new Error("Browser bootstrap token not initialized");
|
||||
}
|
||||
|
||||
const response = await requestPath(port, "/api/auth/bootstrap", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Origin: origin,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ token: currentBootstrapToken }),
|
||||
});
|
||||
if (response.statusCode !== 204) {
|
||||
throw new Error(`Browser bootstrap failed with status ${response.statusCode}`);
|
||||
}
|
||||
|
||||
const setCookie = response.headers["set-cookie"];
|
||||
const cookieHeader = Array.isArray(setCookie) ? setCookie[0] : setCookie;
|
||||
if (!cookieHeader) {
|
||||
throw new Error("Browser bootstrap missing auth cookie");
|
||||
}
|
||||
|
||||
return cookieHeader.split(";", 1)[0] ?? "";
|
||||
}
|
||||
|
||||
function connectWsOnce(port: number, options: ConnectWsOptions = {}): Promise<WebSocket> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const query = token ? `?token=${encodeURIComponent(token)}` : "";
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`);
|
||||
const query = options.token ? `?token=${encodeURIComponent(options.token)}` : "";
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`, {
|
||||
headers: options.headers,
|
||||
});
|
||||
const channels: SocketChannels = {
|
||||
push: { queue: [], waiters: [] },
|
||||
response: { queue: [], waiters: [] },
|
||||
@@ -318,12 +357,25 @@ function connectWsOnce(port: number, token?: string): Promise<WebSocket> {
|
||||
});
|
||||
}
|
||||
|
||||
async function connectWs(port: number, token?: string, attempts = 5): Promise<WebSocket> {
|
||||
async function connectWs(
|
||||
port: number,
|
||||
options: ConnectWsOptions = {},
|
||||
attempts = 5,
|
||||
): Promise<WebSocket> {
|
||||
const normalizedOptions =
|
||||
options.token || options.headers
|
||||
? options
|
||||
: {
|
||||
headers: {
|
||||
Origin: `http://127.0.0.1:${port}`,
|
||||
Cookie: (currentBrowserCookie ??= await pairBrowserSession(port)),
|
||||
},
|
||||
};
|
||||
let lastError: unknown = new Error("WebSocket connection failed");
|
||||
|
||||
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
||||
try {
|
||||
return await connectWsOnce(port, token);
|
||||
return await connectWsOnce(port, normalizedOptions);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (attempt < attempts - 1) {
|
||||
@@ -338,9 +390,9 @@ async function connectWs(port: number, token?: string, attempts = 5): Promise<We
|
||||
/** Connect and wait for the server.welcome push. Returns [ws, welcomeData]. */
|
||||
async function connectAndAwaitWelcome(
|
||||
port: number,
|
||||
token?: string,
|
||||
options: ConnectWsOptions = {},
|
||||
): Promise<[WebSocket, WsPushMessage<typeof WS_CHANNELS.serverWelcome>]> {
|
||||
const ws = await connectWs(port, token);
|
||||
const ws = await connectWs(port, options);
|
||||
const welcome = await waitForPush(ws, WS_CHANNELS.serverWelcome);
|
||||
return [ws, welcome];
|
||||
}
|
||||
@@ -412,14 +464,20 @@ async function rewriteKeybindingsAndWaitForPush(
|
||||
async function requestPath(
|
||||
port: number,
|
||||
requestPath: string,
|
||||
): Promise<{ statusCode: number; body: string }> {
|
||||
options: {
|
||||
readonly method?: string;
|
||||
readonly headers?: Record<string, string>;
|
||||
readonly body?: string;
|
||||
} = {},
|
||||
): Promise<{ statusCode: number; body: string; headers: Http.IncomingHttpHeaders }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = Http.request(
|
||||
{
|
||||
hostname: "127.0.0.1",
|
||||
port,
|
||||
path: requestPath,
|
||||
method: "GET",
|
||||
method: options.method ?? "GET",
|
||||
headers: options.headers,
|
||||
},
|
||||
(res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
@@ -430,11 +488,15 @@ async function requestPath(
|
||||
resolve({
|
||||
statusCode: res.statusCode ?? 0,
|
||||
body: Buffer.concat(chunks).toString("utf8"),
|
||||
headers: res.headers,
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
req.once("error", reject);
|
||||
if (options.body) {
|
||||
req.write(options.body);
|
||||
}
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
@@ -484,6 +546,24 @@ describe("WebSocket Server", () => {
|
||||
return dir;
|
||||
}
|
||||
|
||||
async function reserveLoopbackPort(): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = net.createServer();
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
const port = typeof address === "object" && address !== null ? address.port : 0;
|
||||
server.close((error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve(port);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function createTestServer(
|
||||
options: {
|
||||
persistenceLayer?: Layer.Layer<
|
||||
@@ -513,6 +593,7 @@ describe("WebSocket Server", () => {
|
||||
const baseDir = options.baseDir ?? makeTempDir("t3code-ws-base-");
|
||||
const devUrl = options.devUrl ? new URL(options.devUrl) : undefined;
|
||||
const derivedPaths = deriveServerPathsSync(baseDir, devUrl);
|
||||
const reservedPort = await reserveLoopbackPort();
|
||||
const scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
const persistenceLayer = options.persistenceLayer ?? SqlitePersistenceMemory;
|
||||
const providerLayer = options.providerLayer ?? makeServerProviderLayer();
|
||||
@@ -523,8 +604,8 @@ describe("WebSocket Server", () => {
|
||||
const openLayer = Layer.succeed(Open, options.open ?? defaultOpenService);
|
||||
const serverConfigLayer = Layer.succeed(ServerConfig, {
|
||||
mode: "web",
|
||||
port: 0,
|
||||
host: undefined,
|
||||
port: reservedPort,
|
||||
host: "127.0.0.1",
|
||||
cwd: options.cwd ?? "/test/project",
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
@@ -535,6 +616,7 @@ describe("WebSocket Server", () => {
|
||||
autoBootstrapProjectFromCwd: options.autoBootstrapProjectFromCwd ?? false,
|
||||
logWebSocketEvents: options.logWebSocketEvents ?? Boolean(options.devUrl),
|
||||
} satisfies ServerConfigShape);
|
||||
const browserAuthLayer = BrowserAuthLive.pipe(Layer.provide(serverConfigLayer));
|
||||
const infrastructureLayer = providerLayer.pipe(Layer.provideMerge(persistenceLayer));
|
||||
const runtimeOverrides = Layer.mergeAll(
|
||||
options.gitManager ? Layer.succeed(GitManager, options.gitManager) : Layer.empty,
|
||||
@@ -559,12 +641,22 @@ describe("WebSocket Server", () => {
|
||||
Layer.provideMerge(openLayer),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest(options.serverSettings)),
|
||||
Layer.provideMerge(serverConfigLayer),
|
||||
Layer.provideMerge(browserAuthLayer),
|
||||
Layer.provideMerge(AnalyticsService.layerTest),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtimeServices = await Effect.runPromise(
|
||||
Layer.build(dependenciesLayer).pipe(Scope.provide(scope)),
|
||||
);
|
||||
currentBrowserCookie = null;
|
||||
currentBootstrapToken = null;
|
||||
currentBootstrapToken = await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const browserAuth = yield* BrowserAuth;
|
||||
const pairingUrl = yield* browserAuth.getPairingUrl("http://pair.test");
|
||||
return new URL(pairingUrl).hash.replace(/^#t3_bootstrap=/, "");
|
||||
}).pipe(Effect.provide(runtimeServices)),
|
||||
);
|
||||
|
||||
try {
|
||||
const runtime = await Effect.runPromise(
|
||||
@@ -592,6 +684,8 @@ describe("WebSocket Server", () => {
|
||||
connections.length = 0;
|
||||
await closeTestServer();
|
||||
server = null;
|
||||
currentBootstrapToken = null;
|
||||
currentBrowserCookie = null;
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
@@ -1455,25 +1549,19 @@ describe("WebSocket Server", () => {
|
||||
expect(push.channel).toBe(WS_CHANNELS.terminalEvent);
|
||||
});
|
||||
|
||||
it("shuts down cleanly for injected terminal managers", async () => {
|
||||
it("detaches terminal event listener on stop for injected manager", async () => {
|
||||
const terminalManager = new MockTerminalManager();
|
||||
server = await createTestServer({
|
||||
cwd: "/test",
|
||||
terminalManager,
|
||||
});
|
||||
|
||||
expect(terminalManager.subscriptionCount()).toBe(1);
|
||||
|
||||
await closeTestServer();
|
||||
server = null;
|
||||
|
||||
expect(() =>
|
||||
terminalManager.emitEvent({
|
||||
type: "output",
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
createdAt: new Date().toISOString(),
|
||||
data: "after shutdown\n",
|
||||
}),
|
||||
).not.toThrow();
|
||||
expect(terminalManager.subscriptionCount()).toBe(0);
|
||||
});
|
||||
|
||||
it("returns validation errors for invalid terminal open params", async () => {
|
||||
@@ -1961,9 +2049,120 @@ describe("WebSocket Server", () => {
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
await expect(connectWs(port)).rejects.toThrow("WebSocket connection failed");
|
||||
await expect(
|
||||
connectWs(port, { headers: { Origin: `http://127.0.0.1:${port}` } }),
|
||||
).rejects.toThrow("WebSocket connection failed");
|
||||
|
||||
const [authorizedWs] = await connectAndAwaitWelcome(port, "secret-token");
|
||||
const [authorizedWs] = await connectAndAwaitWelcome(port, { token: "secret-token" });
|
||||
connections.push(authorizedWs);
|
||||
});
|
||||
|
||||
it("issues an auth cookie from a valid bootstrap token", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const response = await requestPath(port, "/api/auth/bootstrap", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Origin: `http://127.0.0.1:${port}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ token: currentBootstrapToken }),
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(204);
|
||||
expect(String(response.headers["set-cookie"])).toContain("t3_auth=");
|
||||
});
|
||||
|
||||
it("rejects bootstrap requests from foreign origins", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const response = await requestPath(port, "/api/auth/bootstrap", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Origin: "https://evil.example",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ token: currentBootstrapToken }),
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("consumes bootstrap tokens exactly once", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const first = await requestPath(port, "/api/auth/bootstrap", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Origin: `http://127.0.0.1:${port}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ token: currentBootstrapToken }),
|
||||
});
|
||||
const second = await requestPath(port, "/api/auth/bootstrap", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Origin: `http://127.0.0.1:${port}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ token: currentBootstrapToken }),
|
||||
});
|
||||
|
||||
expect(first.statusCode).toBe(204);
|
||||
expect(second.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it("reports auth session state from the browser cookie", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const unauthenticated = await requestPath(port, "/api/auth/session");
|
||||
expect(unauthenticated.statusCode).toBe(200);
|
||||
expect(JSON.parse(unauthenticated.body)).toEqual({ authenticated: false });
|
||||
|
||||
const cookie = await pairBrowserSession(port);
|
||||
const authenticated = await requestPath(port, "/api/auth/session", {
|
||||
headers: {
|
||||
Origin: `http://127.0.0.1:${port}`,
|
||||
Cookie: cookie,
|
||||
},
|
||||
});
|
||||
|
||||
expect(authenticated.statusCode).toBe(200);
|
||||
expect(JSON.parse(authenticated.body)).toEqual({ authenticated: true });
|
||||
});
|
||||
|
||||
it("rejects websocket connections without a browser origin", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const cookie = await pairBrowserSession(port);
|
||||
await expect(connectWs(port, { headers: { Cookie: cookie } })).rejects.toThrow(
|
||||
"WebSocket connection failed",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects websocket connections from a foreign origin even with a valid cookie", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const cookie = await pairBrowserSession(port);
|
||||
await expect(
|
||||
connectWs(port, {
|
||||
headers: {
|
||||
Origin: "https://evil.example",
|
||||
Cookie: cookie,
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("WebSocket connection failed");
|
||||
});
|
||||
});
|
||||
+201
-29
@@ -79,6 +79,7 @@ import { expandHomePath } from "./os-jank.ts";
|
||||
import { makeServerPushBus } from "./wsServer/pushBus.ts";
|
||||
import { makeServerReadiness } from "./wsServer/readiness.ts";
|
||||
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
|
||||
import { BrowserAuth } from "./browserAuth";
|
||||
|
||||
/**
|
||||
* ServerShape - Service API for server lifecycle control.
|
||||
@@ -122,6 +123,27 @@ function rejectUpgrade(socket: Duplex, statusCode: number, message: string): voi
|
||||
);
|
||||
}
|
||||
|
||||
function readRequestBody(request: http.IncomingMessage): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks: Buffer[] = [];
|
||||
request.on("data", (chunk: Buffer | string) => {
|
||||
chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
|
||||
});
|
||||
request.once("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
||||
request.once("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
function corsHeaders(origin: string): Record<string, string> {
|
||||
return {
|
||||
"Access-Control-Allow-Origin": origin,
|
||||
"Access-Control-Allow-Credentials": "true",
|
||||
"Access-Control-Allow-Methods": "GET,POST,OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type",
|
||||
Vary: "Origin",
|
||||
};
|
||||
}
|
||||
|
||||
function websocketRawToString(raw: unknown): string | null {
|
||||
if (typeof raw === "string") {
|
||||
return raw;
|
||||
@@ -219,7 +241,8 @@ export type ServerRuntimeServices =
|
||||
| Keybindings
|
||||
| ServerSettingsService
|
||||
| Open
|
||||
| AnalyticsService;
|
||||
| AnalyticsService
|
||||
| BrowserAuth;
|
||||
|
||||
export class ServerLifecycleError extends Schema.TaggedErrorClass<ServerLifecycleError>()(
|
||||
"ServerLifecycleError",
|
||||
@@ -252,15 +275,11 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
} = serverConfig;
|
||||
const availableEditors = resolveAvailableEditors();
|
||||
|
||||
const runtimeServices = yield* Effect.services<
|
||||
ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
|
||||
>();
|
||||
const runPromise = Effect.runPromiseWith(runtimeServices);
|
||||
|
||||
const gitManager = yield* GitManager;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
const keybindingsManager = yield* Keybindings;
|
||||
const serverSettingsManager = yield* ServerSettingsService;
|
||||
const browserAuth = yield* BrowserAuth;
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const git = yield* GitCore;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -427,20 +446,148 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
const httpServer = http.createServer((req, res) => {
|
||||
const respond = (
|
||||
statusCode: number,
|
||||
headers: Record<string, string>,
|
||||
headers: http.OutgoingHttpHeaders,
|
||||
body?: string | Uint8Array,
|
||||
) => {
|
||||
res.writeHead(statusCode, headers);
|
||||
res.end(body);
|
||||
};
|
||||
|
||||
void runPromise(
|
||||
void Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
|
||||
if (tryHandleProjectFaviconRequest(url, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const requestOrigin = req.headers.origin;
|
||||
const authEndpointHeaders =
|
||||
typeof requestOrigin === "string" && (yield* browserAuth.isAllowedOrigin(requestOrigin))
|
||||
? corsHeaders(requestOrigin)
|
||||
: {};
|
||||
|
||||
if (url.pathname === "/api/auth/bootstrap") {
|
||||
if (req.method === "OPTIONS") {
|
||||
if (typeof requestOrigin !== "string") {
|
||||
respond(403, { "Content-Type": "text/plain" }, "Forbidden origin");
|
||||
return;
|
||||
}
|
||||
if (!(yield* browserAuth.isAllowedOrigin(requestOrigin))) {
|
||||
respond(403, { "Content-Type": "text/plain" }, "Forbidden origin");
|
||||
return;
|
||||
}
|
||||
respond(204, authEndpointHeaders);
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method !== "POST") {
|
||||
respond(405, { "Content-Type": "text/plain" }, "Method Not Allowed");
|
||||
return;
|
||||
}
|
||||
if (typeof requestOrigin !== "string") {
|
||||
respond(403, { "Content-Type": "text/plain" }, "Forbidden origin");
|
||||
return;
|
||||
}
|
||||
if (!(yield* browserAuth.isAllowedOrigin(requestOrigin))) {
|
||||
respond(
|
||||
403,
|
||||
{ "Content-Type": "text/plain", ...authEndpointHeaders },
|
||||
"Forbidden origin",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const bodyText = yield* Effect.tryPromise({
|
||||
try: () => readRequestBody(req),
|
||||
catch: () =>
|
||||
new RouteRequestError({ message: "Failed to read auth bootstrap request body." }),
|
||||
});
|
||||
|
||||
let parsedBody: unknown;
|
||||
try {
|
||||
parsedBody = JSON.parse(bodyText);
|
||||
} catch {
|
||||
respond(
|
||||
400,
|
||||
{ "Content-Type": "text/plain", ...authEndpointHeaders },
|
||||
"Invalid JSON body",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const token =
|
||||
typeof parsedBody === "object" &&
|
||||
parsedBody !== null &&
|
||||
"token" in parsedBody &&
|
||||
typeof (parsedBody as { token?: unknown }).token === "string"
|
||||
? (parsedBody as { token: string }).token
|
||||
: null;
|
||||
if (!token) {
|
||||
respond(
|
||||
400,
|
||||
{ "Content-Type": "text/plain", ...authEndpointHeaders },
|
||||
"Missing bootstrap token",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const consumed = yield* browserAuth.consumeBootstrapToken(token);
|
||||
if (!consumed) {
|
||||
respond(
|
||||
401,
|
||||
{ "Content-Type": "text/plain", ...authEndpointHeaders },
|
||||
"Invalid bootstrap token",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const cookieHeader = yield* browserAuth.createAuthCookie(url.protocol === "https:");
|
||||
respond(204, {
|
||||
...authEndpointHeaders,
|
||||
"Set-Cookie": cookieHeader,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/auth/session") {
|
||||
if (req.method === "OPTIONS") {
|
||||
if (typeof requestOrigin !== "string") {
|
||||
respond(204, {});
|
||||
return;
|
||||
}
|
||||
if (!(yield* browserAuth.isAllowedOrigin(requestOrigin))) {
|
||||
respond(403, { "Content-Type": "text/plain" }, "Forbidden origin");
|
||||
return;
|
||||
}
|
||||
respond(204, authEndpointHeaders);
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method !== "GET") {
|
||||
respond(405, { "Content-Type": "text/plain" }, "Method Not Allowed");
|
||||
return;
|
||||
}
|
||||
if (
|
||||
typeof requestOrigin === "string" &&
|
||||
!(yield* browserAuth.isAllowedOrigin(requestOrigin))
|
||||
) {
|
||||
respond(
|
||||
403,
|
||||
{ "Content-Type": "text/plain", ...authEndpointHeaders },
|
||||
"Forbidden origin",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const authenticated = yield* browserAuth.isAuthenticatedRequest(req.headers);
|
||||
respond(
|
||||
200,
|
||||
{ "Content-Type": "application/json", ...authEndpointHeaders },
|
||||
JSON.stringify({ authenticated }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname.startsWith(ATTACHMENTS_ROUTE_PREFIX)) {
|
||||
const rawRelativePath = url.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
|
||||
const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
|
||||
@@ -646,7 +793,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
}),
|
||||
).pipe(Effect.forkIn(subscriptionsScope));
|
||||
|
||||
yield* Scope.provide(orchestrationReactor.start(), subscriptionsScope);
|
||||
yield* Scope.provide(orchestrationReactor.start, subscriptionsScope);
|
||||
yield* readiness.markOrchestrationSubscriptionsReady;
|
||||
|
||||
let welcomeBootstrapProjectId: ProjectId | undefined;
|
||||
@@ -718,10 +865,15 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
);
|
||||
}
|
||||
|
||||
const unsubscribeTerminalEvents = yield* terminalManager.subscribe((event) =>
|
||||
pushBus.publishAll(WS_CHANNELS.terminalEvent, event),
|
||||
const runtimeServices = yield* Effect.services<
|
||||
ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
|
||||
>();
|
||||
const runPromise = Effect.runPromiseWith(runtimeServices);
|
||||
|
||||
const unsubscribeTerminalEvents = yield* terminalManager.subscribe(
|
||||
(event) => void Effect.runPromise(pushBus.publishAll(WS_CHANNELS.terminalEvent, event)),
|
||||
);
|
||||
yield* Scope.addFinalizer(subscriptionsScope, Effect.sync(unsubscribeTerminalEvents));
|
||||
yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
|
||||
yield* readiness.markTerminalSubscriptionsReady;
|
||||
|
||||
yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
|
||||
@@ -986,25 +1138,45 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
httpServer.on("upgrade", (request, socket, head) => {
|
||||
socket.on("error", () => {}); // Prevent unhandled `EPIPE`/`ECONNRESET` from crashing the process if the client disconnects mid-handshake
|
||||
|
||||
if (authToken) {
|
||||
let providedToken: string | null = null;
|
||||
try {
|
||||
const url = new URL(request.url ?? "/", `http://localhost:${port}`);
|
||||
providedToken = url.searchParams.get("token");
|
||||
} catch {
|
||||
rejectUpgrade(socket, 400, "Invalid WebSocket URL");
|
||||
return;
|
||||
}
|
||||
void runPromise(
|
||||
Effect.gen(function* () {
|
||||
let providedToken: string | null = null;
|
||||
try {
|
||||
const url = new URL(request.url ?? "/", `http://localhost:${port}`);
|
||||
providedToken = url.searchParams.get("token");
|
||||
} catch {
|
||||
rejectUpgrade(socket, 400, "Invalid WebSocket URL");
|
||||
return;
|
||||
}
|
||||
|
||||
if (providedToken !== authToken) {
|
||||
rejectUpgrade(socket, 401, "Unauthorized WebSocket connection");
|
||||
return;
|
||||
}
|
||||
}
|
||||
const requestOrigin = request.headers.origin;
|
||||
const hasLegacyToken = Boolean(authToken && providedToken === authToken);
|
||||
|
||||
wss.handleUpgrade(request, socket, head, (ws) => {
|
||||
wss.emit("connection", ws, request);
|
||||
});
|
||||
if (hasLegacyToken && !requestOrigin) {
|
||||
wss.handleUpgrade(request, socket, head, (ws) => {
|
||||
wss.emit("connection", ws, request);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof requestOrigin !== "string") {
|
||||
rejectUpgrade(socket, 401, "Missing WebSocket origin");
|
||||
return;
|
||||
}
|
||||
if (!(yield* browserAuth.isAllowedOrigin(requestOrigin))) {
|
||||
rejectUpgrade(socket, 401, "Forbidden WebSocket origin");
|
||||
return;
|
||||
}
|
||||
if (!(yield* browserAuth.isAuthenticatedRequest(request.headers))) {
|
||||
rejectUpgrade(socket, 401, "Unauthorized WebSocket connection");
|
||||
return;
|
||||
}
|
||||
|
||||
wss.handleUpgrade(request, socket, head, (ws) => {
|
||||
wss.emit("connection", ws, request);
|
||||
});
|
||||
}).pipe(Effect.ignoreCause({ log: true })),
|
||||
);
|
||||
});
|
||||
|
||||
wss.on("connection", (ws) => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.15",
|
||||
"version": "0.0.14",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
clearBootstrapTokenFromUrl,
|
||||
consumeBootstrapTokenFromHash,
|
||||
ensureBrowserPairing,
|
||||
resolveServerHttpOrigin,
|
||||
} from "./browserAuth";
|
||||
|
||||
describe("browserAuth", () => {
|
||||
const fetchMock = vi.fn<typeof fetch>();
|
||||
const setTestWindow = (href: string) => {
|
||||
let currentUrl = new URL(href);
|
||||
const location = {
|
||||
get hash() {
|
||||
return currentUrl.hash;
|
||||
},
|
||||
get host() {
|
||||
return currentUrl.host;
|
||||
},
|
||||
get hostname() {
|
||||
return currentUrl.hostname;
|
||||
},
|
||||
get href() {
|
||||
return currentUrl.toString();
|
||||
},
|
||||
get origin() {
|
||||
return currentUrl.origin;
|
||||
},
|
||||
get pathname() {
|
||||
return currentUrl.pathname;
|
||||
},
|
||||
get port() {
|
||||
return currentUrl.port;
|
||||
},
|
||||
get protocol() {
|
||||
return currentUrl.protocol;
|
||||
},
|
||||
get search() {
|
||||
return currentUrl.search;
|
||||
},
|
||||
toString() {
|
||||
return currentUrl.toString();
|
||||
},
|
||||
};
|
||||
const history = {
|
||||
state: {} as unknown,
|
||||
replaceState: (state: unknown, _unused: string, nextUrl?: string | URL | null) => {
|
||||
history.state = state;
|
||||
if (!nextUrl) return;
|
||||
currentUrl = new URL(String(nextUrl));
|
||||
},
|
||||
};
|
||||
vi.stubGlobal("window", {
|
||||
location,
|
||||
history,
|
||||
nativeApi: undefined,
|
||||
desktopBridge: undefined,
|
||||
});
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
setTestWindow("http://localhost:3773/");
|
||||
fetchMock.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("reads and clears bootstrap tokens from the url hash", () => {
|
||||
setTestWindow("http://localhost:3773/#t3_bootstrap=pair-me");
|
||||
|
||||
expect(consumeBootstrapTokenFromHash()).toBe("pair-me");
|
||||
|
||||
clearBootstrapTokenFromUrl();
|
||||
|
||||
expect(window.location.hash).toBe("");
|
||||
expect(consumeBootstrapTokenFromHash()).toBeNull();
|
||||
});
|
||||
|
||||
it("resolves the server http origin from the current location when no ws override exists", () => {
|
||||
setTestWindow("http://localhost:4123/chat");
|
||||
|
||||
expect(resolveServerHttpOrigin()).toBe("http://localhost:4123");
|
||||
});
|
||||
|
||||
it("exchanges a bootstrap token before checking the auth session", async () => {
|
||||
setTestWindow("http://localhost:3773/#t3_bootstrap=pair-me");
|
||||
fetchMock
|
||||
.mockResolvedValueOnce(
|
||||
new Response(null, {
|
||||
status: 204,
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ authenticated: true }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(ensureBrowserPairing()).resolves.toBe(true);
|
||||
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"http://localhost:3773/api/auth/bootstrap",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
}),
|
||||
);
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
"http://localhost:3773/api/auth/session",
|
||||
expect.objectContaining({
|
||||
credentials: "include",
|
||||
}),
|
||||
);
|
||||
expect(window.location.hash).toBe("");
|
||||
});
|
||||
|
||||
it("polls auth session after a successful bootstrap until the cookie is visible", async () => {
|
||||
setTestWindow("http://localhost:3773/#t3_bootstrap=pair-me");
|
||||
fetchMock
|
||||
.mockResolvedValueOnce(
|
||||
new Response(null, {
|
||||
status: 204,
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ authenticated: false }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ authenticated: false }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ authenticated: true }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(ensureBrowserPairing()).resolves.toBe(true);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(4);
|
||||
expect(window.location.hash).toBe("");
|
||||
});
|
||||
|
||||
it("returns false when bootstrap exchange fails", async () => {
|
||||
setTestWindow("http://localhost:3773/#t3_bootstrap=pair-me");
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
new Response("nope", {
|
||||
status: 401,
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(ensureBrowserPairing()).resolves.toBe(false);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(window.location.hash).toBe("#t3_bootstrap=pair-me");
|
||||
});
|
||||
|
||||
it("checks the existing auth session when no bootstrap token is present", async () => {
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ authenticated: false }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(ensureBrowserPairing()).resolves.toBe(false);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"http://localhost:3773/api/auth/session",
|
||||
expect.objectContaining({
|
||||
credentials: "include",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("bypasses browser pairing when the electron desktop bridge is available", async () => {
|
||||
vi.stubGlobal("window", {
|
||||
location: {
|
||||
href: "file:///app/index.html",
|
||||
origin: "file://",
|
||||
hash: "",
|
||||
},
|
||||
history: {
|
||||
state: undefined,
|
||||
replaceState: vi.fn(),
|
||||
},
|
||||
nativeApi: undefined,
|
||||
desktopBridge: {
|
||||
getWsUrl: () => "ws://127.0.0.1:3773",
|
||||
},
|
||||
});
|
||||
|
||||
await expect(ensureBrowserPairing()).resolves.toBe(true);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
const BOOTSTRAP_HASH_KEY = "t3_bootstrap";
|
||||
const AUTH_SESSION_POLL_ATTEMPTS = 50;
|
||||
const AUTH_SESSION_POLL_INTERVAL_MS = 100;
|
||||
|
||||
interface AuthSessionResponse {
|
||||
readonly authenticated: boolean;
|
||||
}
|
||||
|
||||
function normalizeServerHttpOrigin(rawUrl: string): string {
|
||||
const wsUrl = new URL(rawUrl);
|
||||
const protocol =
|
||||
wsUrl.protocol === "wss:" ? "https:" : wsUrl.protocol === "ws:" ? "http:" : wsUrl.protocol;
|
||||
return `${protocol}//${wsUrl.host}`;
|
||||
}
|
||||
|
||||
export function resolveServerHttpOrigin(): string {
|
||||
if (typeof window === "undefined") return "";
|
||||
|
||||
const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
|
||||
const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||
const wsCandidate =
|
||||
typeof bridgeWsUrl === "string" && bridgeWsUrl.length > 0
|
||||
? bridgeWsUrl
|
||||
: typeof envWsUrl === "string" && envWsUrl.length > 0
|
||||
? envWsUrl
|
||||
: null;
|
||||
|
||||
if (!wsCandidate) {
|
||||
return window.location.origin;
|
||||
}
|
||||
|
||||
try {
|
||||
return normalizeServerHttpOrigin(wsCandidate);
|
||||
} catch {
|
||||
return window.location.origin;
|
||||
}
|
||||
}
|
||||
|
||||
export function consumeBootstrapTokenFromHash(
|
||||
locationLike: Location = window.location,
|
||||
): string | null {
|
||||
const hash = locationLike.hash.startsWith("#") ? locationLike.hash.slice(1) : locationLike.hash;
|
||||
const params = new URLSearchParams(hash);
|
||||
const token = params.get(BOOTSTRAP_HASH_KEY);
|
||||
return token && token.length > 0 ? token : null;
|
||||
}
|
||||
|
||||
export function clearBootstrapTokenFromUrl(locationLike: Location = window.location): void {
|
||||
const currentUrl = new URL(locationLike.href);
|
||||
currentUrl.hash = "";
|
||||
window.history.replaceState(window.history.state, "", currentUrl.toString());
|
||||
}
|
||||
|
||||
async function exchangeBootstrapToken(serverOrigin: string, token: string): Promise<void> {
|
||||
const response = await fetch(`${serverOrigin}/api/auth/bootstrap`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
credentials: "include",
|
||||
body: JSON.stringify({ token }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Browser pairing failed with status ${response.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchSession(serverOrigin: string): Promise<boolean> {
|
||||
const response = await fetch(`${serverOrigin}/api/auth/session`, {
|
||||
credentials: "include",
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Auth session check failed with status ${response.status}`);
|
||||
}
|
||||
|
||||
const parsed = (await response.json()) as Partial<AuthSessionResponse>;
|
||||
return parsed.authenticated === true;
|
||||
}
|
||||
|
||||
async function waitForAuthenticatedSession(serverOrigin: string): Promise<boolean> {
|
||||
for (let attempt = 0; attempt < AUTH_SESSION_POLL_ATTEMPTS; attempt += 1) {
|
||||
if (await fetchSession(serverOrigin)) {
|
||||
return true;
|
||||
}
|
||||
if (attempt < AUTH_SESSION_POLL_ATTEMPTS - 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, AUTH_SESSION_POLL_INTERVAL_MS));
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function ensureBrowserPairing(): Promise<boolean> {
|
||||
if (typeof window === "undefined") return false;
|
||||
if (window.nativeApi || window.desktopBridge) return true;
|
||||
|
||||
const serverOrigin = resolveServerHttpOrigin();
|
||||
const bootstrapToken = consumeBootstrapTokenFromHash();
|
||||
|
||||
if (bootstrapToken) {
|
||||
try {
|
||||
await exchangeBootstrapToken(serverOrigin, bootstrapToken);
|
||||
clearBootstrapTokenFromUrl();
|
||||
return waitForAuthenticatedSession(serverOrigin);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return fetchSession(serverOrigin);
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
import { useEffect, type ReactNode } from "react";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
|
||||
import ThreadSidebar from "./Sidebar";
|
||||
import { Sidebar, SidebarProvider, SidebarRail } from "./ui/sidebar";
|
||||
|
||||
const THREAD_SIDEBAR_WIDTH_STORAGE_KEY = "chat_thread_sidebar_width";
|
||||
const THREAD_SIDEBAR_MIN_WIDTH = 13 * 16;
|
||||
const THREAD_MAIN_CONTENT_MIN_WIDTH = 40 * 16;
|
||||
|
||||
export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
const onMenuAction = window.desktopBridge?.onMenuAction;
|
||||
if (typeof onMenuAction !== "function") {
|
||||
return;
|
||||
}
|
||||
|
||||
const unsubscribe = onMenuAction((action) => {
|
||||
if (action !== "open-settings") return;
|
||||
void navigate({ to: "/settings" });
|
||||
});
|
||||
|
||||
return () => {
|
||||
unsubscribe?.();
|
||||
};
|
||||
}, [navigate]);
|
||||
|
||||
return (
|
||||
<SidebarProvider defaultOpen>
|
||||
<Sidebar
|
||||
side="left"
|
||||
collapsible="offcanvas"
|
||||
className="border-r border-border bg-card text-foreground"
|
||||
resizable={{
|
||||
minWidth: THREAD_SIDEBAR_MIN_WIDTH,
|
||||
shouldAcceptWidth: ({ nextWidth, wrapper }) =>
|
||||
wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
|
||||
storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
|
||||
}}
|
||||
>
|
||||
<ThreadSidebar />
|
||||
<SidebarRail />
|
||||
</Sidebar>
|
||||
{children}
|
||||
</SidebarProvider>
|
||||
);
|
||||
}
|
||||
@@ -397,6 +397,7 @@ export function BranchToolbarBranchSelector({
|
||||
key={itemValue}
|
||||
index={index}
|
||||
value={itemValue}
|
||||
className={itemValue === resolvedActiveBranch ? "bg-accent text-foreground" : undefined}
|
||||
style={style}
|
||||
onClick={() => selectBranch(branch)}
|
||||
>
|
||||
|
||||
@@ -243,7 +243,7 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
|
||||
a({ node: _node, href, ...props }) {
|
||||
const targetPath = resolveMarkdownFileLinkTarget(href, cwd);
|
||||
if (!targetPath) {
|
||||
return <a {...props} href={href} target="_blank" rel="noopener noreferrer" />;
|
||||
return <a {...props} href={href} target="_blank" rel="noreferrer" />;
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
Loaded 100 of 206 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user