Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ae625d277c | ||
|
|
a60daa1c76 | ||
|
|
bc1024caf0 | ||
|
|
a1c428b6e2 | ||
|
|
00f3efb95b | ||
|
|
7f3387a86c | ||
|
|
5462d50177 | ||
|
|
f82bae1668 | ||
|
|
9e60597174 | ||
|
|
afc807ac3f | ||
|
|
58ba4f1263 | ||
|
|
5513845fd5 | ||
|
|
33773ff17e | ||
|
|
64d21bd6d2 | ||
|
|
5210a833a5 | ||
|
|
5b1d5c1220 | ||
|
|
f4617e7b19 | ||
|
|
c426452239 | ||
|
|
73b2f255a9 | ||
|
|
ce463a5360 | ||
|
|
52fa6a7333 | ||
|
|
04298962be | ||
|
|
61f983098b | ||
|
|
32c1f98a02 | ||
|
|
5851b8aca4 | ||
|
|
3e2df5a782 | ||
|
|
f0cdaf94c2 | ||
|
|
48196e67a7 | ||
|
|
80a176fe1f | ||
|
|
42ea7cfae1 | ||
|
|
d2e6c82709 | ||
|
|
23b3f0c3d0 | ||
|
|
e08cea3a23 | ||
|
|
83eb396c40 | ||
|
|
59a383e1ea | ||
|
|
fb7260792f | ||
|
|
d8a485ea7e | ||
|
|
02989fe600 | ||
|
|
648f0676bd | ||
|
|
add5f34619 | ||
|
|
9403429a7a | ||
|
|
37cf0c1144 | ||
|
|
bf1f3e1c4f | ||
|
|
2aa11ae076 | ||
|
|
8888f6a0c9 | ||
|
|
ff8d87ddee | ||
|
|
3289a25e57 | ||
|
|
df5bde7e11 | ||
|
|
b3bca04caf | ||
|
|
bf71e0bc5e | ||
|
|
a542a3b168 | ||
|
|
56d13faa1a | ||
|
|
2a435aef66 | ||
|
|
28afb14004 | ||
|
|
8f3515572d |
No files matched your search
@@ -0,0 +1,2 @@
|
||||
# git autocrlf=true converts LF to CRLF on Windows, causing issues with oxfmt
|
||||
* text=auto eol=lf
|
||||
+2
-1
@@ -28,4 +28,5 @@ github:realAhmedRoach
|
||||
github:shiroyasha9
|
||||
github:Yash-Singh1
|
||||
github:eggfriedrice24
|
||||
github:Ymit24
|
||||
github:Ymit24
|
||||
github:shivamhwp
|
||||
@@ -124,25 +124,49 @@ jobs:
|
||||
group: pr-size-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
steps:
|
||||
- name: Checkout base repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Sync PR size label
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
|
||||
with:
|
||||
script: |
|
||||
const { execFileSync } = require("node:child_process");
|
||||
|
||||
const issueNumber = context.payload.pull_request.number;
|
||||
const baseSha = context.payload.pull_request.base.sha;
|
||||
const headSha = context.payload.pull_request.head.sha;
|
||||
const headTrackingRef = `refs/remotes/pr-size/${issueNumber}`;
|
||||
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
|
||||
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
|
||||
// Keep this aligned with the repo's test entrypoints and test-only support files.
|
||||
const testFilePatterns = [
|
||||
/(^|\/)__tests__(\/|$)/,
|
||||
/(^|\/)tests?(\/|$)/,
|
||||
/^apps\/server\/integration\//,
|
||||
/\.(test|spec|browser|integration)\.[^.\/]+$/,
|
||||
const testExcludePathspecs = [
|
||||
":(glob,exclude)**/__tests__/**",
|
||||
":(glob,exclude)**/test/**",
|
||||
":(glob,exclude)**/tests/**",
|
||||
":(glob,exclude)apps/server/integration/**",
|
||||
":(glob,exclude)**/*.test.*",
|
||||
":(glob,exclude)**/*.spec.*",
|
||||
":(glob,exclude)**/*.browser.*",
|
||||
":(glob,exclude)**/*.integration.*",
|
||||
];
|
||||
|
||||
const isTestFile = (filename) =>
|
||||
testFilePatterns.some((pattern) => pattern.test(filename));
|
||||
const sumNumstat = (text) =>
|
||||
text
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.reduce((total, line) => {
|
||||
const [insertionsRaw = "0", deletionsRaw = "0"] = line.split("\t");
|
||||
const additions =
|
||||
insertionsRaw === "-" ? 0 : Number.parseInt(insertionsRaw, 10) || 0;
|
||||
const deletions =
|
||||
deletionsRaw === "-" ? 0 : Number.parseInt(deletionsRaw, 10) || 0;
|
||||
|
||||
return total + additions + deletions;
|
||||
}, 0);
|
||||
|
||||
const resolveSizeLabel = (totalChangedLines) => {
|
||||
if (totalChangedLines < 10) {
|
||||
@@ -168,40 +192,53 @@ jobs:
|
||||
return "size:XXL";
|
||||
};
|
||||
|
||||
const files = await github.paginate(
|
||||
github.rest.pulls.listFiles,
|
||||
execFileSync("git", ["fetch", "--no-tags", "origin", baseSha], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
|
||||
execFileSync(
|
||||
"git",
|
||||
["fetch", "--no-tags", "origin", `+refs/pull/${issueNumber}/head:${headTrackingRef}`],
|
||||
{
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
pull_number: issueNumber,
|
||||
per_page: 100,
|
||||
stdio: "inherit",
|
||||
},
|
||||
(response) => response.data,
|
||||
);
|
||||
|
||||
if (files.length >= 3000) {
|
||||
const resolvedHeadSha = execFileSync("git", ["rev-parse", headTrackingRef], {
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
|
||||
if (resolvedHeadSha !== headSha) {
|
||||
core.warning(
|
||||
"The GitHub pull request files API may truncate results at 3,000 files; PR size may be undercounted.",
|
||||
`Fetched head SHA ${resolvedHeadSha} does not match pull request head SHA ${headSha}; using fetched ref for sizing.`,
|
||||
);
|
||||
}
|
||||
|
||||
let testChangedLines = 0;
|
||||
let nonTestChangedLines = 0;
|
||||
execFileSync("git", ["cat-file", "-e", `${baseSha}^{commit}`], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
|
||||
for (const file of files) {
|
||||
const changedLinesForFile = (file.additions ?? 0) + (file.deletions ?? 0);
|
||||
const diffArgs = [
|
||||
"diff",
|
||||
"--numstat",
|
||||
"--ignore-all-space",
|
||||
"--ignore-blank-lines",
|
||||
`${baseSha}...${resolvedHeadSha}`,
|
||||
];
|
||||
|
||||
if (changedLinesForFile === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isTestFile(file.filename)) {
|
||||
testChangedLines += changedLinesForFile;
|
||||
continue;
|
||||
}
|
||||
|
||||
nonTestChangedLines += changedLinesForFile;
|
||||
}
|
||||
const totalChangedLines = sumNumstat(
|
||||
execFileSync(
|
||||
"git",
|
||||
diffArgs,
|
||||
{ encoding: "utf8" },
|
||||
),
|
||||
);
|
||||
const nonTestChangedLines = sumNumstat(
|
||||
execFileSync("git", [...diffArgs, "--", ".", ...testExcludePathspecs], {
|
||||
encoding: "utf8",
|
||||
}),
|
||||
);
|
||||
const testChangedLines = Math.max(0, totalChangedLines - nonTestChangedLines);
|
||||
|
||||
const changedLines = nonTestChangedLines === 0 ? testChangedLines : nonTestChangedLines;
|
||||
const nextLabelName = resolveSizeLabel(changedLines);
|
||||
|
||||
@@ -12,6 +12,7 @@ packages/*/dist
|
||||
build/
|
||||
.logs/
|
||||
release/
|
||||
release-mock/
|
||||
.t3
|
||||
.idea/
|
||||
apps/web/.playwright
|
||||
|
||||
@@ -6,21 +6,24 @@ Use this when you want to open T3 Code from another device (phone, tablet, anoth
|
||||
|
||||
The T3 Code CLI accepts the following configuration options, available either as CLI flags or environment variables:
|
||||
|
||||
| CLI flag | Env var | Notes |
|
||||
| ----------------------- | --------------------- | ---------------------------------- |
|
||||
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
|
||||
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
|
||||
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
|
||||
| `--base-dir <path>` | `T3CODE_HOME` | Base directory. |
|
||||
| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
|
||||
| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
|
||||
| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. |
|
||||
| CLI flag | Env var | Notes |
|
||||
| ----------------------- | --------------------- | ------------------------------------------------------------------------------------ |
|
||||
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
|
||||
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
|
||||
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
|
||||
| `--base-dir <path>` | `T3CODE_HOME` | Base directory. |
|
||||
| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
|
||||
| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
|
||||
| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. Use this for standard CLI and remote-server flows. |
|
||||
| `--bootstrap-fd <fd>` | `T3CODE_BOOTSTRAP_FD` | Read a one-shot bootstrap envelope from an inherited file descriptor during startup. |
|
||||
|
||||
> TIP: Use the `--help` flag to see all available options and their descriptions.
|
||||
|
||||
## Security First
|
||||
|
||||
- Always set `--auth-token` before exposing the server outside localhost.
|
||||
- When you control the process launcher, prefer sending the auth token in a JSON envelope via `--bootstrap-fd <fd>`.
|
||||
With `--bootstrap-fd <fd>`, the launcher starts the server first, then sends a one-shot JSON envelope over the inherited file descriptor. This allows the auth token to be delivered without putting it in process environment or command line arguments.
|
||||
- Treat the token like a password.
|
||||
- Prefer binding to trusted interfaces (LAN IP or Tailnet IP) instead of opening all interfaces unless needed.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.13",
|
||||
"version": "0.0.15",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
|
||||
+95
-23
@@ -20,6 +20,7 @@ import * as Effect from "effect/Effect";
|
||||
import type {
|
||||
DesktopTheme,
|
||||
DesktopUpdateActionResult,
|
||||
DesktopUpdateCheckResult,
|
||||
DesktopUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import { autoUpdater } from "electron-updater";
|
||||
@@ -56,6 +57,8 @@ 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");
|
||||
const DESKTOP_SCHEME = "t3";
|
||||
@@ -113,6 +116,17 @@ function sanitizeLogValue(value: string): string {
|
||||
return value.replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
function backendChildEnv(): NodeJS.ProcessEnv {
|
||||
const env = { ...process.env };
|
||||
delete env.T3CODE_PORT;
|
||||
delete env.T3CODE_AUTH_TOKEN;
|
||||
delete env.T3CODE_MODE;
|
||||
delete env.T3CODE_NO_BROWSER;
|
||||
delete env.T3CODE_HOST;
|
||||
delete env.T3CODE_DESKTOP_WS_URL;
|
||||
return env;
|
||||
}
|
||||
|
||||
function writeDesktopLogHeader(message: string): void {
|
||||
if (!desktopLogSink) return;
|
||||
desktopLogSink.write(`[${logTimestamp()}] [${logScope("desktop")}] ${message}\n`);
|
||||
@@ -275,10 +289,12 @@ let updatePollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let updateStartupTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let updateCheckInFlight = false;
|
||||
let updateDownloadInFlight = false;
|
||||
let updateInstallInFlight = false;
|
||||
let updaterConfigured = false;
|
||||
let updateState: DesktopUpdateState = initialUpdateState();
|
||||
|
||||
function resolveUpdaterErrorContext(): DesktopUpdateErrorContext {
|
||||
if (updateInstallInFlight) return "install";
|
||||
if (updateDownloadInFlight) return "download";
|
||||
if (updateCheckInFlight) return "check";
|
||||
return updateState.errorContext;
|
||||
@@ -742,13 +758,13 @@ function shouldEnableAutoUpdates(): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
async function checkForUpdates(reason: string): Promise<void> {
|
||||
if (isQuitting || !updaterConfigured || updateCheckInFlight) return;
|
||||
async function checkForUpdates(reason: string): Promise<boolean> {
|
||||
if (isQuitting || !updaterConfigured || updateCheckInFlight) return false;
|
||||
if (updateState.status === "downloading" || updateState.status === "downloaded") {
|
||||
console.info(
|
||||
`[desktop-updater] Skipping update check (${reason}) while status=${updateState.status}.`,
|
||||
);
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
updateCheckInFlight = true;
|
||||
setUpdateState(reduceDesktopUpdateStateOnCheckStart(updateState, new Date().toISOString()));
|
||||
@@ -756,12 +772,14 @@ async function checkForUpdates(reason: string): Promise<void> {
|
||||
|
||||
try {
|
||||
await autoUpdater.checkForUpdates();
|
||||
return true;
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
setUpdateState(
|
||||
reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()),
|
||||
);
|
||||
console.error(`[desktop-updater] Failed to check for updates: ${message}`);
|
||||
return true;
|
||||
} finally {
|
||||
updateCheckInFlight = false;
|
||||
}
|
||||
@@ -795,13 +813,22 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed
|
||||
}
|
||||
|
||||
isQuitting = true;
|
||||
updateInstallInFlight = true;
|
||||
clearUpdatePollTimer();
|
||||
try {
|
||||
await stopBackendAndWaitForExit();
|
||||
autoUpdater.quitAndInstall();
|
||||
return { accepted: true, completed: true };
|
||||
// Destroy all windows before launching the NSIS installer to avoid the installer finding live windows it needs to close.
|
||||
for (const win of BrowserWindow.getAllWindows()) {
|
||||
win.destroy();
|
||||
}
|
||||
// `quitAndInstall()` only starts the handoff to the updater. The actual
|
||||
// install may still fail asynchronously, so keep the action incomplete
|
||||
// until we either quit or receive an updater error.
|
||||
autoUpdater.quitAndInstall(true, true);
|
||||
return { accepted: true, completed: false };
|
||||
} catch (error: unknown) {
|
||||
const message = formatErrorMessage(error);
|
||||
updateInstallInFlight = false;
|
||||
isQuitting = false;
|
||||
setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
|
||||
console.error(`[desktop-updater] Failed to install update: ${message}`);
|
||||
@@ -838,6 +865,13 @@ function configureAutoUpdater(): void {
|
||||
}
|
||||
}
|
||||
|
||||
if (process.env.T3CODE_DESKTOP_MOCK_UPDATES) {
|
||||
autoUpdater.setFeedURL({
|
||||
provider: "generic",
|
||||
url: `http://localhost:${process.env.T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT ?? 3000}`,
|
||||
});
|
||||
}
|
||||
|
||||
autoUpdater.autoDownload = false;
|
||||
autoUpdater.autoInstallOnAppQuit = false;
|
||||
// Keep alpha branding, but force all installs onto the stable update track.
|
||||
@@ -874,6 +908,13 @@ function configureAutoUpdater(): void {
|
||||
});
|
||||
autoUpdater.on("error", (error) => {
|
||||
const message = formatErrorMessage(error);
|
||||
if (updateInstallInFlight) {
|
||||
updateInstallInFlight = false;
|
||||
isQuitting = false;
|
||||
setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
|
||||
console.error(`[desktop-updater] Updater error: ${message}`);
|
||||
return;
|
||||
}
|
||||
if (!updateCheckInFlight && !updateDownloadInFlight) {
|
||||
setUpdateState({
|
||||
status: "error",
|
||||
@@ -918,17 +959,6 @@ function configureAutoUpdater(): void {
|
||||
}, AUTO_UPDATE_POLL_INTERVAL_MS);
|
||||
updatePollTimer.unref();
|
||||
}
|
||||
function backendEnv(): NodeJS.ProcessEnv {
|
||||
return {
|
||||
...process.env,
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_NO_BROWSER: "1",
|
||||
T3CODE_PORT: String(backendPort),
|
||||
T3CODE_HOME: BASE_DIR,
|
||||
T3CODE_AUTH_TOKEN: backendAuthToken,
|
||||
};
|
||||
}
|
||||
|
||||
function scheduleBackendRestart(reason: string): void {
|
||||
if (isQuitting || restartTimer) return;
|
||||
|
||||
@@ -952,16 +982,35 @@ function startBackend(): void {
|
||||
}
|
||||
|
||||
const captureBackendLogs = app.isPackaged && backendLogSink !== null;
|
||||
const child = ChildProcess.spawn(process.execPath, [backendEntry], {
|
||||
const child = ChildProcess.spawn(process.execPath, [backendEntry, "--bootstrap-fd", "3"], {
|
||||
cwd: resolveBackendCwd(),
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||
env: {
|
||||
...backendEnv(),
|
||||
...backendChildEnv(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
stdio: captureBackendLogs ? ["ignore", "pipe", "pipe"] : "inherit",
|
||||
stdio: captureBackendLogs
|
||||
? ["ignore", "pipe", "pipe", "pipe"]
|
||||
: ["ignore", "inherit", "inherit", "pipe"],
|
||||
});
|
||||
const bootstrapStream = child.stdio[3];
|
||||
if (bootstrapStream && "write" in bootstrapStream) {
|
||||
bootstrapStream.write(
|
||||
`${JSON.stringify({
|
||||
mode: "desktop",
|
||||
noBrowser: true,
|
||||
port: backendPort,
|
||||
t3Home: BASE_DIR,
|
||||
authToken: backendAuthToken,
|
||||
})}\n`,
|
||||
);
|
||||
bootstrapStream.end();
|
||||
} else {
|
||||
child.kill("SIGTERM");
|
||||
scheduleBackendRestart("missing desktop bootstrap pipe");
|
||||
return;
|
||||
}
|
||||
backendProcess = child;
|
||||
let backendSessionClosed = false;
|
||||
const closeBackendSession = (details: string) => {
|
||||
@@ -1072,6 +1121,11 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
|
||||
}
|
||||
|
||||
function registerIpcHandlers(): void {
|
||||
ipcMain.removeAllListeners(GET_WS_URL_CHANNEL);
|
||||
ipcMain.on(GET_WS_URL_CHANNEL, (event) => {
|
||||
event.returnValue = backendWsUrl;
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
|
||||
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
|
||||
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
|
||||
@@ -1116,6 +1170,7 @@ function registerIpcHandlers(): void {
|
||||
id: item.id,
|
||||
label: item.label,
|
||||
destructive: item.destructive === true,
|
||||
disabled: item.disabled === true,
|
||||
}));
|
||||
if (normalizedItems.length === 0) {
|
||||
return null;
|
||||
@@ -1146,6 +1201,7 @@ function registerIpcHandlers(): void {
|
||||
}
|
||||
const itemOption: MenuItemConstructorOptions = {
|
||||
label: item.label,
|
||||
enabled: !item.disabled,
|
||||
click: () => resolve(item.id),
|
||||
};
|
||||
if (item.destructive) {
|
||||
@@ -1211,6 +1267,21 @@ function registerIpcHandlers(): void {
|
||||
state: updateState,
|
||||
} satisfies DesktopUpdateActionResult;
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(UPDATE_CHECK_CHANNEL);
|
||||
ipcMain.handle(UPDATE_CHECK_CHANNEL, async () => {
|
||||
if (!updaterConfigured) {
|
||||
return {
|
||||
checked: false,
|
||||
state: updateState,
|
||||
} satisfies DesktopUpdateCheckResult;
|
||||
}
|
||||
const checked = await checkForUpdates("web-ui");
|
||||
return {
|
||||
checked,
|
||||
state: updateState,
|
||||
} satisfies DesktopUpdateCheckResult;
|
||||
});
|
||||
}
|
||||
|
||||
function getIconOption(): { icon: string } | Record<string, never> {
|
||||
@@ -1320,9 +1391,9 @@ async function bootstrap(): Promise<void> {
|
||||
);
|
||||
writeDesktopLogHeader(`reserved backend port via NetService port=${backendPort}`);
|
||||
backendAuthToken = Crypto.randomBytes(24).toString("hex");
|
||||
backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
|
||||
process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
|
||||
writeDesktopLogHeader(`bootstrap resolved websocket url=${backendWsUrl}`);
|
||||
const baseUrl = `ws://127.0.0.1:${backendPort}`;
|
||||
backendWsUrl = `${baseUrl}/?token=${encodeURIComponent(backendAuthToken)}`;
|
||||
writeDesktopLogHeader(`bootstrap resolved websocket endpoint baseUrl=${baseUrl}`);
|
||||
|
||||
registerIpcHandlers();
|
||||
writeDesktopLogHeader("bootstrap ipc handlers registered");
|
||||
@@ -1334,6 +1405,7 @@ async function bootstrap(): Promise<void> {
|
||||
|
||||
app.on("before-quit", () => {
|
||||
isQuitting = true;
|
||||
updateInstallInFlight = false;
|
||||
writeDesktopLogHeader("before-quit received");
|
||||
clearUpdatePollTimer();
|
||||
stopBackend();
|
||||
@@ -1363,7 +1435,7 @@ app
|
||||
});
|
||||
|
||||
app.on("window-all-closed", () => {
|
||||
if (process.platform !== "darwin") {
|
||||
if (process.platform !== "darwin" && !isQuitting) {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -9,12 +9,16 @@ 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 wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
||||
const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
|
||||
|
||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
getWsUrl: () => wsUrl,
|
||||
getWsUrl: () => {
|
||||
const result = ipcRenderer.sendSync(GET_WS_URL_CHANNEL);
|
||||
return typeof result === "string" ? result : null;
|
||||
},
|
||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
|
||||
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
||||
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
|
||||
@@ -32,6 +36,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
};
|
||||
},
|
||||
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
|
||||
checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL),
|
||||
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
|
||||
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
|
||||
onUpdateState: (listener) => {
|
||||
|
||||
@@ -62,14 +62,13 @@ describe("syncShellEnvironment", () => {
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
||||
});
|
||||
|
||||
it("does nothing outside macOS", () => {
|
||||
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/inherited.sock",
|
||||
};
|
||||
const readEnvironment = vi.fn(() => ({
|
||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
||||
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||
}));
|
||||
|
||||
@@ -78,8 +77,29 @@ describe("syncShellEnvironment", () => {
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
||||
expect(env.PATH).toBe("/home/linuxbrew/.linuxbrew/bin:/usr/bin");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
|
||||
});
|
||||
|
||||
it("does nothing outside macOS and linux", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "C:/Program Files/Git/bin/bash.exe",
|
||||
PATH: "C:\\Windows\\System32",
|
||||
SSH_AUTH_SOCK: "/tmp/inherited.sock",
|
||||
};
|
||||
const readEnvironment = vi.fn(() => ({
|
||||
PATH: "/usr/local/bin:/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||
}));
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "win32",
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).not.toHaveBeenCalled();
|
||||
expect(env.PATH).toBe("/usr/bin");
|
||||
expect(env.PATH).toBe("C:\\Windows\\System32");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,8 @@
|
||||
import { readEnvironmentFromLoginShell, ShellEnvironmentReader } from "@t3tools/shared/shell";
|
||||
import {
|
||||
readEnvironmentFromLoginShell,
|
||||
resolveLoginShell,
|
||||
ShellEnvironmentReader,
|
||||
} from "@t3tools/shared/shell";
|
||||
|
||||
export function syncShellEnvironment(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
@@ -7,10 +11,13 @@ export function syncShellEnvironment(
|
||||
readEnvironment?: ShellEnvironmentReader;
|
||||
} = {},
|
||||
): void {
|
||||
if ((options.platform ?? process.platform) !== "darwin") return;
|
||||
const platform = options.platform ?? process.platform;
|
||||
if (platform !== "darwin" && platform !== "linux") return;
|
||||
|
||||
try {
|
||||
const shell = env.SHELL ?? "/bin/zsh";
|
||||
const shell = resolveLoginShell(platform, env.SHELL);
|
||||
if (!shell) return;
|
||||
|
||||
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
|
||||
@@ -38,6 +38,7 @@ import { ProjectionPendingApprovalRepository } from "../src/persistence/Services
|
||||
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
|
||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
|
||||
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
|
||||
@@ -295,20 +296,24 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
providerLayer,
|
||||
RuntimeReceiptBusLive,
|
||||
);
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest();
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(serverSettingsLayer),
|
||||
);
|
||||
const gitCoreLayer = Layer.succeed(GitCore, {
|
||||
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
|
||||
Effect.succeed({ branch: input.newBranch }),
|
||||
} as unknown as GitCoreShape);
|
||||
const textGenerationLayer = Layer.succeed(TextGeneration, {
|
||||
generateBranchName: () => Effect.succeed({ branch: null }),
|
||||
generateBranchName: () => Effect.succeed({ branch: "update" }),
|
||||
generateThreadTitle: () => Effect.succeed({ title: "New thread" }),
|
||||
} as unknown as TextGenerationShape);
|
||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
Layer.provideMerge(serverSettingsLayer),
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
@@ -320,6 +325,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
);
|
||||
const layer = orchestrationReactorLayer.pipe(
|
||||
Layer.provide(persistenceLayer),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
@@ -354,7 +360,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) =>
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
ProjectId,
|
||||
ProviderKind,
|
||||
ThreadId,
|
||||
ModelSelection,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Option, Schema } from "effect";
|
||||
@@ -115,7 +116,10 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
defaultModel,
|
||||
defaultModelSelection: {
|
||||
provider,
|
||||
model: defaultModel,
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
|
||||
@@ -125,7 +129,10 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
model: defaultModel,
|
||||
modelSelection: {
|
||||
provider,
|
||||
model: defaultModel,
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -139,7 +146,7 @@ const startTurn = (input: {
|
||||
readonly commandId: string;
|
||||
readonly messageId: string;
|
||||
readonly text: string;
|
||||
readonly provider?: IntegrationProvider;
|
||||
readonly modelSelection?: ModelSelection;
|
||||
}) =>
|
||||
input.harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
@@ -151,7 +158,11 @@ const startTurn = (input: {
|
||||
text: input.text,
|
||||
attachments: [],
|
||||
},
|
||||
...(input.provider !== undefined ? { provider: input.provider } : {}),
|
||||
...(input.modelSelection !== undefined
|
||||
? {
|
||||
modelSelection: input.modelSelection,
|
||||
}
|
||||
: {}),
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: nowIso(),
|
||||
@@ -254,7 +265,10 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
defaultModel: "gpt-5.3-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
|
||||
@@ -264,7 +278,10 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
@@ -922,7 +939,10 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
|
||||
commandId: "cmd-turn-start-claude-initial",
|
||||
messageId: "msg-user-claude-initial",
|
||||
text: "Use Claude",
|
||||
provider: "claudeAgent",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(
|
||||
@@ -976,7 +996,10 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
|
||||
commandId: "cmd-turn-start-claude-recover-1",
|
||||
messageId: "msg-user-claude-recover-1",
|
||||
text: "Before restart",
|
||||
provider: "claudeAgent",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
|
||||
yield* harness.waitForThread(
|
||||
@@ -1083,7 +1106,10 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
|
||||
commandId: "cmd-turn-start-claude-approval",
|
||||
messageId: "msg-user-claude-approval",
|
||||
text: "Need approval",
|
||||
provider: "claudeAgent",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
|
||||
@@ -1152,7 +1178,10 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
|
||||
commandId: "cmd-turn-start-claude-interrupt",
|
||||
messageId: "msg-user-claude-interrupt",
|
||||
text: "Start long turn",
|
||||
provider: "claudeAgent",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(
|
||||
@@ -1222,7 +1251,10 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
|
||||
commandId: "cmd-turn-start-claude-revert-1",
|
||||
messageId: "msg-user-claude-revert-1",
|
||||
text: "First Claude edit",
|
||||
provider: "claudeAgent",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
|
||||
yield* harness.waitForThread(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it, assert } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
|
||||
@@ -12,6 +13,7 @@ import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
} from "../src/provider/Services/ProviderService.ts";
|
||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
|
||||
@@ -60,6 +62,7 @@ const makeIntegrationFixture = Effect.gen(function* () {
|
||||
const shared = Layer.mergeAll(
|
||||
directoryLayer,
|
||||
Layer.succeed(ProviderAdapterRegistry, registry),
|
||||
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
|
||||
AnalyticsService.layerTest,
|
||||
).pipe(Layer.provide(SqlitePersistenceMemory));
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.13",
|
||||
"version": "0.0.15",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import * as NFS from "node:fs";
|
||||
import * as path from "node:path";
|
||||
import { execFileSync, spawn } from "node:child_process";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { FileSystem, Schema } from "effect";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { vi } from "vitest";
|
||||
|
||||
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap";
|
||||
import { assertNone, assertSome } from "@effect/vitest/utils";
|
||||
|
||||
const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null }));
|
||||
|
||||
vi.mock("node:fs", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("node:fs")>();
|
||||
return {
|
||||
...actual,
|
||||
openSync: (...args: Parameters<typeof actual.openSync>) => {
|
||||
const [filePath, flags] = args;
|
||||
if (
|
||||
typeof filePath === "string" &&
|
||||
filePath === openSyncInterceptor.failPath &&
|
||||
flags === "r"
|
||||
) {
|
||||
const error = new Error("no such device or address");
|
||||
Object.assign(error, { code: "ENXIO" });
|
||||
throw error;
|
||||
}
|
||||
return (actual.openSync as (...a: typeof args) => number)(...args);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const TestEnvelopeSchema = Schema.Struct({ mode: Schema.String });
|
||||
|
||||
it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
|
||||
it.effect("uses platform-specific fd paths", () =>
|
||||
Effect.sync(() => {
|
||||
assert.equal(resolveFdPath(3, "linux"), "/proc/self/fd/3");
|
||||
assert.equal(resolveFdPath(3, "darwin"), "/dev/fd/3");
|
||||
assert.equal(resolveFdPath(3, "win32"), undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads a bootstrap envelope from a provided fd", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
||||
|
||||
yield* fs.writeFileString(
|
||||
filePath,
|
||||
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
|
||||
mode: "desktop",
|
||||
})}\n`,
|
||||
);
|
||||
|
||||
const fd = yield* Effect.acquireRelease(
|
||||
Effect.sync(() => NFS.openSync(filePath, "r")),
|
||||
(fd) => Effect.sync(() => NFS.closeSync(fd)),
|
||||
);
|
||||
|
||||
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
|
||||
assertSome(payload, {
|
||||
mode: "desktop",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to reading the inherited fd when path duplication fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
||||
|
||||
yield* fs.writeFileString(
|
||||
filePath,
|
||||
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
|
||||
mode: "desktop",
|
||||
})}\n`,
|
||||
);
|
||||
|
||||
// Open without acquireRelease: the direct-stream fallback uses autoClose: true,
|
||||
// so the stream owns the fd lifecycle and closes it asynchronously on end.
|
||||
// Attempting to also close it synchronously in a finalizer races with the
|
||||
// stream's async close and produces an uncaught EBADF.
|
||||
const fd = NFS.openSync(filePath, "r");
|
||||
|
||||
openSyncInterceptor.failPath = `/proc/self/fd/${fd}`;
|
||||
try {
|
||||
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
|
||||
assertSome(payload, {
|
||||
mode: "desktop",
|
||||
});
|
||||
} finally {
|
||||
openSyncInterceptor.failPath = null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns none when the fd is unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fd = NFS.openSync("/dev/null", "r");
|
||||
NFS.closeSync(fd);
|
||||
|
||||
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
|
||||
assertNone(payload);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns none when the bootstrap read times out before any value arrives", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-bootstrap-" });
|
||||
const fifoPath = path.join(tempDir, "bootstrap.pipe");
|
||||
|
||||
yield* Effect.sync(() => execFileSync("mkfifo", [fifoPath]));
|
||||
|
||||
const _writer = yield* Effect.acquireRelease(
|
||||
Effect.sync(() =>
|
||||
spawn("sh", ["-c", 'exec 3>"$1"; sleep 60', "sh", fifoPath], {
|
||||
stdio: ["ignore", "ignore", "ignore"],
|
||||
}),
|
||||
),
|
||||
(writer) =>
|
||||
Effect.sync(() => {
|
||||
writer.kill("SIGKILL");
|
||||
}),
|
||||
);
|
||||
|
||||
const fd = yield* Effect.acquireRelease(
|
||||
Effect.sync(() => NFS.openSync(fifoPath, "r")),
|
||||
(fd) => Effect.sync(() => NFS.closeSync(fd)),
|
||||
);
|
||||
|
||||
const fiber = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
|
||||
timeoutMs: 100,
|
||||
}).pipe(Effect.forkScoped);
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
yield* TestClock.adjust(Duration.millis(100));
|
||||
|
||||
const payload = yield* Fiber.join(fiber);
|
||||
assertNone(payload);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
import * as NFS from "node:fs";
|
||||
import * as Net from "node:net";
|
||||
import * as readline from "node:readline";
|
||||
import type { Readable } from "node:stream";
|
||||
|
||||
import { Data, Effect, Option, Predicate, Result, Schema } from "effect";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
|
||||
class BootstrapError extends Data.TaggedError("BootstrapError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function* <A, I>(
|
||||
schema: Schema.Codec<A, I>,
|
||||
fd: number,
|
||||
options?: {
|
||||
timeoutMs?: number;
|
||||
},
|
||||
): Effect.fn.Return<Option.Option<A>, BootstrapError> {
|
||||
const fdReady = yield* isFdReady(fd);
|
||||
if (!fdReady) return Option.none();
|
||||
|
||||
const stream = yield* makeBootstrapInputStream(fd);
|
||||
|
||||
const timeoutMs = options?.timeoutMs ?? 1000;
|
||||
|
||||
return yield* Effect.callback<Option.Option<A>, BootstrapError>((resume) => {
|
||||
const input = readline.createInterface({
|
||||
input: stream,
|
||||
crlfDelay: Infinity,
|
||||
});
|
||||
|
||||
const cleanup = () => {
|
||||
stream.removeListener("error", handleError);
|
||||
input.removeListener("line", handleLine);
|
||||
input.removeListener("close", handleClose);
|
||||
input.close();
|
||||
stream.destroy();
|
||||
};
|
||||
|
||||
const handleError = (error: Error) => {
|
||||
if (isUnavailableBootstrapFdError(error)) {
|
||||
resume(Effect.succeedNone);
|
||||
return;
|
||||
}
|
||||
resume(
|
||||
Effect.fail(
|
||||
new BootstrapError({
|
||||
message: "Failed to read bootstrap envelope.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const handleLine = (line: string) => {
|
||||
const parsed = decodeJsonResult(schema)(line);
|
||||
if (Result.isSuccess(parsed)) {
|
||||
resume(Effect.succeedSome(parsed.success));
|
||||
} else {
|
||||
resume(
|
||||
Effect.fail(
|
||||
new BootstrapError({
|
||||
message: "Failed to decode bootstrap envelope.",
|
||||
cause: parsed.failure,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
resume(Effect.succeedNone);
|
||||
};
|
||||
|
||||
stream.once("error", handleError);
|
||||
input.once("line", handleLine);
|
||||
input.once("close", handleClose);
|
||||
|
||||
return Effect.sync(cleanup);
|
||||
}).pipe(Effect.timeoutOption(timeoutMs), Effect.map(Option.flatten));
|
||||
});
|
||||
|
||||
const isUnavailableBootstrapFdError = Predicate.compose(
|
||||
Predicate.hasProperty("code"),
|
||||
(_) => _.code === "EBADF" || _.code === "ENOENT",
|
||||
);
|
||||
|
||||
const isFdReady = (fd: number) =>
|
||||
Effect.try({
|
||||
try: () => NFS.fstatSync(fd),
|
||||
catch: (error) =>
|
||||
new BootstrapError({
|
||||
message: "Failed to stat bootstrap fd.",
|
||||
cause: error,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.as(true),
|
||||
Effect.catchIf(
|
||||
(error) => isUnavailableBootstrapFdError(error.cause),
|
||||
() => Effect.succeed(false),
|
||||
),
|
||||
);
|
||||
|
||||
const makeBootstrapInputStream = (fd: number) =>
|
||||
Effect.try<Readable, BootstrapError>({
|
||||
try: () => {
|
||||
const fdPath = resolveFdPath(fd);
|
||||
if (fdPath === undefined) {
|
||||
return makeDirectBootstrapStream(fd);
|
||||
}
|
||||
|
||||
let streamFd: number | undefined;
|
||||
try {
|
||||
streamFd = NFS.openSync(fdPath, "r");
|
||||
return NFS.createReadStream("", {
|
||||
fd: streamFd,
|
||||
encoding: "utf8",
|
||||
autoClose: true,
|
||||
});
|
||||
} catch (error) {
|
||||
if (isBootstrapFdPathDuplicationError(error)) {
|
||||
if (streamFd !== undefined) {
|
||||
NFS.closeSync(streamFd);
|
||||
}
|
||||
return makeDirectBootstrapStream(fd);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
catch: (error) =>
|
||||
new BootstrapError({
|
||||
message: "Failed to duplicate bootstrap fd.",
|
||||
cause: error,
|
||||
}),
|
||||
});
|
||||
|
||||
const makeDirectBootstrapStream = (fd: number): Readable => {
|
||||
try {
|
||||
return NFS.createReadStream("", {
|
||||
fd,
|
||||
encoding: "utf8",
|
||||
autoClose: true,
|
||||
});
|
||||
} catch {
|
||||
const stream = new Net.Socket({
|
||||
fd,
|
||||
readable: true,
|
||||
writable: false,
|
||||
});
|
||||
stream.setEncoding("utf8");
|
||||
return stream;
|
||||
}
|
||||
};
|
||||
|
||||
const isBootstrapFdPathDuplicationError = Predicate.compose(
|
||||
Predicate.hasProperty("code"),
|
||||
(_) => _.code === "ENXIO" || _.code === "EINVAL" || _.code === "EPERM",
|
||||
);
|
||||
|
||||
export function resolveFdPath(
|
||||
fd: number,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): string | undefined {
|
||||
if (platform === "linux") {
|
||||
return `/proc/self/fd/${fd}`;
|
||||
}
|
||||
if (platform === "win32") {
|
||||
return undefined;
|
||||
}
|
||||
return `/dev/fd/${fd}`;
|
||||
}
|
||||
@@ -31,7 +31,8 @@ function makeSnapshot(input: {
|
||||
id: input.projectId,
|
||||
title: "Project",
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
defaultModel: null,
|
||||
workspaceState: "available",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
@@ -43,11 +44,17 @@ function makeSnapshot(input: {
|
||||
id: input.threadId,
|
||||
projectId: input.projectId,
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: input.worktreePath,
|
||||
effectiveCwd: input.worktreePath ?? input.workspaceRoot,
|
||||
effectiveCwdSource: input.worktreePath ? "worktree" : "project",
|
||||
effectiveCwdState: "available",
|
||||
latestTurn: {
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
state: "completed",
|
||||
@@ -58,6 +65,7 @@ function makeSnapshot(input: {
|
||||
},
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import path from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||
import { CheckpointStoreLive } from "./CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../Services/CheckpointStore.ts";
|
||||
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { GitCommandError } from "../../git/Errors.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-checkpoint-store-test-",
|
||||
});
|
||||
const GitCoreTestLayer = GitCoreLive.pipe(
|
||||
Layer.provide(ServerConfigLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
const CheckpointStoreTestLayer = CheckpointStoreLive.pipe(
|
||||
Layer.provide(GitCoreTestLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
const TestLayer = Layer.mergeAll(NodeServices.layer, GitCoreTestLayer, CheckpointStoreTestLayer);
|
||||
|
||||
function makeTmpDir(
|
||||
prefix = "checkpoint-store-test-",
|
||||
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return yield* fileSystem.makeTempDirectoryScoped({ prefix });
|
||||
});
|
||||
}
|
||||
|
||||
function writeTextFile(
|
||||
filePath: string,
|
||||
contents: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.writeFileString(filePath, contents);
|
||||
});
|
||||
}
|
||||
|
||||
function git(
|
||||
cwd: string,
|
||||
args: ReadonlyArray<string>,
|
||||
): Effect.Effect<string, GitCommandError, GitCore> {
|
||||
return Effect.gen(function* () {
|
||||
const gitCore = yield* GitCore;
|
||||
const result = yield* gitCore.execute({
|
||||
operation: "CheckpointStore.test.git",
|
||||
cwd,
|
||||
args,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
return result.stdout.trim();
|
||||
});
|
||||
}
|
||||
|
||||
function initRepoWithCommit(
|
||||
cwd: string,
|
||||
): Effect.Effect<
|
||||
void,
|
||||
GitCommandError | PlatformError.PlatformError,
|
||||
GitCore | FileSystem.FileSystem
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const core = yield* GitCore;
|
||||
yield* core.initRepo({ cwd });
|
||||
yield* git(cwd, ["config", "user.email", "[email protected]"]);
|
||||
yield* git(cwd, ["config", "user.name", "Test"]);
|
||||
yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
|
||||
yield* git(cwd, ["add", "."]);
|
||||
yield* git(cwd, ["commit", "-m", "initial commit"]);
|
||||
});
|
||||
}
|
||||
|
||||
function buildLargeText(lineCount = 20_000): string {
|
||||
return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`)
|
||||
.join("\n")
|
||||
.concat("\n");
|
||||
}
|
||||
|
||||
it.layer(TestLayer)("CheckpointStoreLive", (it) => {
|
||||
describe("diffCheckpoints", () => {
|
||||
it.effect("returns full oversized checkpoint diffs without truncation", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
const threadId = ThreadId.makeUnsafe("thread-checkpoint-store");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({
|
||||
cwd: tmp,
|
||||
checkpointRef: fromCheckpointRef,
|
||||
});
|
||||
yield* writeTextFile(path.join(tmp, "README.md"), buildLargeText());
|
||||
yield* checkpointStore.captureCheckpoint({
|
||||
cwd: tmp,
|
||||
checkpointRef: toCheckpointRef,
|
||||
});
|
||||
|
||||
const diff = yield* checkpointStore.diffCheckpoints({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
});
|
||||
|
||||
expect(diff).toContain("diff --git");
|
||||
expect(diff).not.toContain("[truncated]");
|
||||
expect(diff).toContain("+line 19999");
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -207,6 +207,42 @@ describe("classifyCodexStderrLine", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("process stderr events", () => {
|
||||
it("emits classified stderr lines as notifications", () => {
|
||||
const manager = new CodexAppServerManager();
|
||||
const emitEvent = vi
|
||||
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
|
||||
.mockImplementation(() => {});
|
||||
|
||||
(
|
||||
manager as unknown as {
|
||||
emitNotificationEvent: (
|
||||
context: { session: { threadId: ThreadId } },
|
||||
method: string,
|
||||
message: string,
|
||||
) => void;
|
||||
}
|
||||
).emitNotificationEvent(
|
||||
{
|
||||
session: {
|
||||
threadId: asThreadId("thread-1"),
|
||||
},
|
||||
},
|
||||
"process/stderr",
|
||||
"fatal: permission denied",
|
||||
);
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
kind: "notification",
|
||||
method: "process/stderr",
|
||||
threadId: "thread-1",
|
||||
message: "fatal: permission denied",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeCodexModelSlug", () => {
|
||||
it("maps 5.3 aliases to gpt-5.3-codex", () => {
|
||||
expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
|
||||
@@ -342,6 +378,7 @@ describe("startSession", () => {
|
||||
manager.startSession({
|
||||
threadId: asThreadId("thread-1"),
|
||||
provider: "codex",
|
||||
binaryPath: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
).rejects.toThrow("cwd missing");
|
||||
@@ -390,6 +427,7 @@ describe("startSession", () => {
|
||||
manager.startSession({
|
||||
threadId: asThreadId("thread-1"),
|
||||
provider: "codex",
|
||||
binaryPath: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
@@ -948,12 +986,8 @@ describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume"
|
||||
provider: "codex",
|
||||
cwd: workspaceDir,
|
||||
runtimeMode: "full-access",
|
||||
providerOptions: {
|
||||
codex: {
|
||||
...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
|
||||
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
||||
},
|
||||
},
|
||||
binaryPath: process.env.CODEX_BINARY_PATH!,
|
||||
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
||||
});
|
||||
|
||||
const firstTurn = await manager.sendTurn({
|
||||
@@ -983,12 +1017,8 @@ describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume"
|
||||
cwd: workspaceDir,
|
||||
runtimeMode: "approval-required",
|
||||
resumeCursor: firstSession.resumeCursor,
|
||||
providerOptions: {
|
||||
codex: {
|
||||
...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
|
||||
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
||||
},
|
||||
},
|
||||
binaryPath: process.env.CODEX_BINARY_PATH!,
|
||||
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
||||
});
|
||||
|
||||
expect(resumedSession.threadId).toBe(originalThreadId);
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderEvent,
|
||||
type ProviderSession,
|
||||
type ProviderSessionStartInput,
|
||||
type ProviderTurnStartResult,
|
||||
RuntimeMode,
|
||||
ProviderInteractionMode,
|
||||
@@ -131,7 +130,8 @@ export interface CodexAppServerStartSessionInput {
|
||||
readonly model?: string;
|
||||
readonly serviceTier?: string;
|
||||
readonly resumeCursor?: unknown;
|
||||
readonly providerOptions?: ProviderSessionStartInput["providerOptions"];
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
}
|
||||
|
||||
@@ -541,9 +541,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const codexOptions = readCodexProviderOptions(input);
|
||||
const codexBinaryPath = codexOptions.binaryPath ?? "codex";
|
||||
const codexHomePath = codexOptions.homePath;
|
||||
const codexBinaryPath = input.binaryPath;
|
||||
const codexHomePath = input.homePath;
|
||||
this.assertSupportedCodexCliVersion({
|
||||
binaryPath: codexBinaryPath,
|
||||
cwd: resolvedCwd,
|
||||
@@ -1047,7 +1046,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
continue;
|
||||
}
|
||||
|
||||
this.emitErrorEvent(context, "process/stderr", classified.message);
|
||||
this.emitNotificationEvent(context, "process/stderr", classified.message);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1355,6 +1354,22 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
}
|
||||
|
||||
private emitNotificationEvent(
|
||||
context: CodexSessionContext,
|
||||
method: string,
|
||||
message: string,
|
||||
): void {
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method,
|
||||
message,
|
||||
});
|
||||
}
|
||||
|
||||
private emitEvent(event: ProviderEvent): void {
|
||||
this.emit("event", event);
|
||||
}
|
||||
@@ -1591,20 +1606,6 @@ function normalizeProviderThreadId(value: string | undefined): string | undefine
|
||||
return brandIfNonEmpty(value, (normalized) => normalized);
|
||||
}
|
||||
|
||||
function readCodexProviderOptions(input: CodexAppServerStartSessionInput): {
|
||||
readonly binaryPath?: string;
|
||||
readonly homePath?: string;
|
||||
} {
|
||||
const options = input.providerOptions?.codex;
|
||||
if (!options) {
|
||||
return {};
|
||||
}
|
||||
return {
|
||||
...(options.binaryPath ? { binaryPath: options.binaryPath } : {}),
|
||||
...(options.homePath ? { homePath: options.homePath } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function assertSupportedCodexCliVersion(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly cwd: string;
|
||||
@@ -1658,7 +1659,11 @@ function readResumeCursorThreadId(resumeCursor: unknown): string | undefined {
|
||||
return typeof rawThreadId === "string" ? normalizeProviderThreadId(rawThreadId) : undefined;
|
||||
}
|
||||
|
||||
function readResumeThreadId(input: CodexAppServerStartSessionInput): string | undefined {
|
||||
function readResumeThreadId(input: {
|
||||
readonly resumeCursor?: unknown;
|
||||
readonly threadId?: ThreadId;
|
||||
readonly runtimeMode?: RuntimeMode;
|
||||
}): string | undefined {
|
||||
return readResumeCursorThreadId(input.resumeCursor);
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ export interface ServerDerivedPaths {
|
||||
readonly stateDir: string;
|
||||
readonly dbPath: string;
|
||||
readonly keybindingsConfigPath: string;
|
||||
readonly settingsPath: string;
|
||||
readonly worktreesDir: string;
|
||||
readonly attachmentsDir: string;
|
||||
readonly logsDir: string;
|
||||
@@ -60,6 +61,7 @@ export const deriveServerPaths = Effect.fn(function* (
|
||||
stateDir,
|
||||
dbPath,
|
||||
keybindingsConfigPath: join(stateDir, "keybindings.json"),
|
||||
settingsPath: join(stateDir, "settings.json"),
|
||||
worktreesDir: join(baseDir, "worktrees"),
|
||||
attachmentsDir,
|
||||
logsDir,
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { sanitizeThreadTitle } from "../Utils.ts";
|
||||
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
const ClaudeTextGenerationTestLayer = ClaudeTextGenerationLive.pipe(
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-claude-text-generation-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
function makeFakeClaudeBinary(dir: string) {
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const binDir = path.join(dir, "bin");
|
||||
const claudePath = path.join(binDir, "claude");
|
||||
yield* fs.makeDirectory(binDir, { recursive: true });
|
||||
|
||||
yield* fs.writeFileString(
|
||||
claudePath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
'args="$*"',
|
||||
'stdin_content="$(cat)"',
|
||||
'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" ]; then',
|
||||
' printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" >/dev/null || {',
|
||||
' printf "%s\\n" "args missing expected content" >&2',
|
||||
" exit 2",
|
||||
" }",
|
||||
"fi",
|
||||
'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" ]; then',
|
||||
' if printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" >/dev/null; then',
|
||||
' printf "%s\\n" "args contained forbidden content" >&2',
|
||||
" exit 3",
|
||||
" fi",
|
||||
"fi",
|
||||
'if [ -n "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" ]; then',
|
||||
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" >/dev/null || {',
|
||||
' printf "%s\\n" "stdin missing expected content" >&2',
|
||||
" exit 4",
|
||||
" }",
|
||||
"fi",
|
||||
'if [ -n "$T3_FAKE_CLAUDE_STDERR" ]; then',
|
||||
' printf "%s\\n" "$T3_FAKE_CLAUDE_STDERR" >&2',
|
||||
"fi",
|
||||
'printf "%s" "$T3_FAKE_CLAUDE_OUTPUT"',
|
||||
'exit "${T3_FAKE_CLAUDE_EXIT_CODE:-0}"',
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* fs.chmod(claudePath, 0o755);
|
||||
return binDir;
|
||||
});
|
||||
}
|
||||
|
||||
function withFakeClaudeEnv<A, E, R>(
|
||||
input: {
|
||||
output: string;
|
||||
exitCode?: number;
|
||||
stderr?: string;
|
||||
argsMustContain?: string;
|
||||
argsMustNotContain?: string;
|
||||
stdinMustContain?: string;
|
||||
},
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
) {
|
||||
return Effect.acquireUseRelease(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });
|
||||
const binDir = yield* makeFakeClaudeBinary(tempDir);
|
||||
const previousPath = process.env.PATH;
|
||||
const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT;
|
||||
const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE;
|
||||
const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR;
|
||||
const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
|
||||
const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
|
||||
const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
|
||||
|
||||
yield* Effect.sync(() => {
|
||||
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
|
||||
process.env.T3_FAKE_CLAUDE_OUTPUT = input.output;
|
||||
|
||||
if (input.exitCode !== undefined) {
|
||||
process.env.T3_FAKE_CLAUDE_EXIT_CODE = String(input.exitCode);
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
|
||||
}
|
||||
|
||||
if (input.stderr !== undefined) {
|
||||
process.env.T3_FAKE_CLAUDE_STDERR = input.stderr;
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CLAUDE_STDERR;
|
||||
}
|
||||
|
||||
if (input.argsMustContain !== undefined) {
|
||||
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = input.argsMustContain;
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
|
||||
}
|
||||
|
||||
if (input.argsMustNotContain !== undefined) {
|
||||
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = input.argsMustNotContain;
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
|
||||
}
|
||||
|
||||
if (input.stdinMustContain !== undefined) {
|
||||
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = input.stdinMustContain;
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
previousPath,
|
||||
previousOutput,
|
||||
previousExitCode,
|
||||
previousStderr,
|
||||
previousArgsMustContain,
|
||||
previousArgsMustNotContain,
|
||||
previousStdinMustContain,
|
||||
};
|
||||
}),
|
||||
() => effect,
|
||||
(previous) =>
|
||||
Effect.sync(() => {
|
||||
process.env.PATH = previous.previousPath;
|
||||
|
||||
if (previous.previousOutput === undefined) {
|
||||
delete process.env.T3_FAKE_CLAUDE_OUTPUT;
|
||||
} else {
|
||||
process.env.T3_FAKE_CLAUDE_OUTPUT = previous.previousOutput;
|
||||
}
|
||||
|
||||
if (previous.previousExitCode === undefined) {
|
||||
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
|
||||
} else {
|
||||
process.env.T3_FAKE_CLAUDE_EXIT_CODE = previous.previousExitCode;
|
||||
}
|
||||
|
||||
if (previous.previousStderr === undefined) {
|
||||
delete process.env.T3_FAKE_CLAUDE_STDERR;
|
||||
} else {
|
||||
process.env.T3_FAKE_CLAUDE_STDERR = previous.previousStderr;
|
||||
}
|
||||
|
||||
if (previous.previousArgsMustContain === undefined) {
|
||||
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
|
||||
} else {
|
||||
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previous.previousArgsMustContain;
|
||||
}
|
||||
|
||||
if (previous.previousArgsMustNotContain === undefined) {
|
||||
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
|
||||
} else {
|
||||
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previous.previousArgsMustNotContain;
|
||||
}
|
||||
|
||||
if (previous.previousStdinMustContain === undefined) {
|
||||
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
|
||||
} else {
|
||||
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
|
||||
it.effect("forwards Claude thinking settings for Haiku without passing effort", () =>
|
||||
withFakeClaudeEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
structured_output: {
|
||||
subject: "Add important change",
|
||||
body: "",
|
||||
},
|
||||
}),
|
||||
argsMustContain: '--settings {"alwaysThinkingEnabled":false}',
|
||||
argsMustNotContain: "--effort",
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/claude-effect",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
options: {
|
||||
thinking: false,
|
||||
effort: "high",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Add important change");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("forwards Claude fast mode and supported effort", () =>
|
||||
withFakeClaudeEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
structured_output: {
|
||||
title: "Improve orchestration flow",
|
||||
body: "Body",
|
||||
},
|
||||
}),
|
||||
argsMustContain: '--effort max --settings {"fastMode":true}',
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generatePrContent({
|
||||
cwd: process.cwd(),
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/claude-effect",
|
||||
commitSummary: "Improve orchestration",
|
||||
diffSummary: "1 file changed",
|
||||
diffPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("Improve orchestration flow");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("generates thread titles through the Claude provider", () =>
|
||||
withFakeClaudeEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
structured_output: {
|
||||
title:
|
||||
' "Reconnect failures after restart because the session state does not recover" ',
|
||||
},
|
||||
}),
|
||||
stdinMustContain: "You write concise thread titles for coding conversations.",
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Please investigate reconnect failures after restarting the session.",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.title).toBe(
|
||||
sanitizeThreadTitle(
|
||||
'"Reconnect failures after restart because the session state does not recover"',
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>
|
||||
withFakeClaudeEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
structured_output: {
|
||||
title: ' """ """ ',
|
||||
},
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Name this thread.",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("New thread");
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,344 @@
|
||||
/**
|
||||
* ClaudeTextGeneration – Text generation layer using the Claude CLI.
|
||||
*
|
||||
* Implements the same TextGenerationShape contract as CodexTextGeneration but
|
||||
* delegates to the `claude` CLI (`claude -p`) with structured JSON output
|
||||
* instead of the `codex exec` CLI.
|
||||
*
|
||||
* @module ClaudeTextGeneration
|
||||
*/
|
||||
import { Effect, Layer, Option, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ClaudeModelSelection } from "@t3tools/contracts";
|
||||
import { resolveApiModelId } from "@t3tools/shared/model";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "../Prompts.ts";
|
||||
import {
|
||||
normalizeCliError,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
toJsonSchemaObject,
|
||||
} from "../Utils.ts";
|
||||
import { normalizeClaudeModelOptions } from "../../provider/Layers/ClaudeProvider.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
const CLAUDE_TIMEOUT_MS = 180_000;
|
||||
|
||||
/**
|
||||
* Schema for the wrapper JSON returned by `claude -p --output-format json`.
|
||||
* We only care about `structured_output`.
|
||||
*/
|
||||
const ClaudeOutputEnvelope = Schema.Struct({
|
||||
structured_output: Schema.Unknown,
|
||||
});
|
||||
|
||||
const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const serverSettingsService = yield* Effect.service(ServerSettingsService);
|
||||
|
||||
const readStreamAsString = <E>(
|
||||
operation: string,
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
): Effect.Effect<string, TextGenerationError> =>
|
||||
stream.pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.runFold(
|
||||
() => "",
|
||||
(acc, chunk) => acc + chunk,
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("claude", operation, cause, "Failed to collect process output"),
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* Spawn the Claude CLI with structured JSON output and return the parsed,
|
||||
* schema-validated result.
|
||||
*/
|
||||
const runClaudeJson = <S extends Schema.Top>({
|
||||
operation,
|
||||
cwd,
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
modelSelection,
|
||||
}: {
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
modelSelection: ClaudeModelSelection;
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
|
||||
const normalizedOptions = normalizeClaudeModelOptions(
|
||||
modelSelection.model,
|
||||
modelSelection.options,
|
||||
);
|
||||
const settings = {
|
||||
...(typeof normalizedOptions?.thinking === "boolean"
|
||||
? { alwaysThinkingEnabled: normalizedOptions.thinking }
|
||||
: {}),
|
||||
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
|
||||
};
|
||||
|
||||
const claudeSettings = yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => settings.providers.claudeAgent,
|
||||
).pipe(Effect.catch(() => Effect.undefined));
|
||||
|
||||
const runClaudeCommand = Effect.gen(function* () {
|
||||
const command = ChildProcess.make(
|
||||
claudeSettings?.binaryPath || "claude",
|
||||
[
|
||||
"-p",
|
||||
"--output-format",
|
||||
"json",
|
||||
"--json-schema",
|
||||
jsonSchemaStr,
|
||||
"--model",
|
||||
resolveApiModelId(modelSelection),
|
||||
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
|
||||
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
|
||||
"--dangerously-skip-permissions",
|
||||
],
|
||||
{
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdin: {
|
||||
stream: Stream.encodeText(Stream.make(prompt)),
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const child = yield* commandSpawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
|
||||
),
|
||||
);
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
readStreamAsString(operation, child.stdout),
|
||||
readStreamAsString(operation, child.stderr),
|
||||
child.exitCode.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError(
|
||||
"claude",
|
||||
operation,
|
||||
cause,
|
||||
"Failed to read Claude CLI exit code",
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
if (exitCode !== 0) {
|
||||
const stderrDetail = stderr.trim();
|
||||
const stdoutDetail = stdout.trim();
|
||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||
return yield* new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
detail.length > 0
|
||||
? `Claude CLI command failed: ${detail}`
|
||||
: `Claude CLI command failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
|
||||
return stdout;
|
||||
});
|
||||
|
||||
const rawStdout = yield* runClaudeCommand.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
|
||||
),
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
|
||||
rawStdout,
|
||||
).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Claude CLI returned unexpected output format.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Claude returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TextGenerationShape methods
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
|
||||
"ClaudeTextGeneration.generateCommitMessage",
|
||||
)(function* (input) {
|
||||
const { prompt, outputSchema } = buildCommitMessagePrompt({
|
||||
branch: input.branch,
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "claudeAgent") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateCommitMessage",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runClaudeJson({
|
||||
operation: "generateCommitMessage",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
subject: sanitizeCommitSubject(generated.subject),
|
||||
body: generated.body.trim(),
|
||||
...("branch" in generated && typeof generated.branch === "string"
|
||||
? { branch: sanitizeFeatureBranchName(generated.branch) }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
|
||||
"ClaudeTextGeneration.generatePrContent",
|
||||
)(function* (input) {
|
||||
const { prompt, outputSchema } = buildPrContentPrompt({
|
||||
baseBranch: input.baseBranch,
|
||||
headBranch: input.headBranch,
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "claudeAgent") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generatePrContent",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runClaudeJson({
|
||||
operation: "generatePrContent",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
title: sanitizePrTitle(generated.title),
|
||||
body: generated.body.trim(),
|
||||
};
|
||||
});
|
||||
|
||||
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
|
||||
"ClaudeTextGeneration.generateBranchName",
|
||||
)(function* (input) {
|
||||
const { prompt, outputSchema } = buildBranchNamePrompt({
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "claudeAgent") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateBranchName",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runClaudeJson({
|
||||
operation: "generateBranchName",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
branch: sanitizeBranchFragment(generated.branch),
|
||||
};
|
||||
});
|
||||
|
||||
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
|
||||
"ClaudeTextGeneration.generateThreadTitle",
|
||||
)(function* (input) {
|
||||
const { prompt, outputSchema } = buildThreadTitlePrompt({
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "claudeAgent") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateThreadTitle",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runClaudeJson({
|
||||
operation: "generateThreadTitle",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
title: sanitizeThreadTitle(generated.title),
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
} satisfies TextGenerationShape;
|
||||
});
|
||||
|
||||
export const ClaudeTextGenerationLive = Layer.effect(TextGeneration, makeClaudeTextGeneration);
|
||||
@@ -1,14 +1,21 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import { Effect, FileSystem, Layer, Path, Result } from "effect";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
const DEFAULT_TEST_MODEL_SELECTION = {
|
||||
provider: "codex" as const,
|
||||
model: "gpt-5.4-mini",
|
||||
};
|
||||
|
||||
const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-codex-text-generation-test-",
|
||||
@@ -17,7 +24,20 @@ const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
function makeFakeCodexBinary(dir: string) {
|
||||
function makeFakeCodexBinary(
|
||||
dir: string,
|
||||
input: {
|
||||
output: string;
|
||||
exitCode?: number;
|
||||
stderr?: string;
|
||||
requireImage?: boolean;
|
||||
requireFastServiceTier?: boolean;
|
||||
requireReasoningEffort?: string;
|
||||
forbidReasoningEffort?: boolean;
|
||||
stdinMustContain?: string;
|
||||
stdinMustNotContain?: string;
|
||||
},
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -30,49 +50,102 @@ function makeFakeCodexBinary(dir: string) {
|
||||
[
|
||||
"#!/bin/sh",
|
||||
'output_path=""',
|
||||
'seen_image="0"',
|
||||
'seen_fast_service_tier="0"',
|
||||
'seen_reasoning_effort=""',
|
||||
"while [ $# -gt 0 ]; do",
|
||||
' if [ "$1" = "--image" ]; then',
|
||||
" shift",
|
||||
' if [ -n "$1" ]; then',
|
||||
' seen_image="1"',
|
||||
" fi",
|
||||
" shift",
|
||||
" continue",
|
||||
" fi",
|
||||
' if [ "$1" = "--config" ]; then',
|
||||
" shift",
|
||||
' if [ "$1" = "service_tier=\\"fast\\"" ]; then',
|
||||
' seen_fast_service_tier="1"',
|
||||
" fi",
|
||||
' case "$1" in',
|
||||
" model_reasoning_effort=*)",
|
||||
' seen_reasoning_effort="$1"',
|
||||
" ;;",
|
||||
" esac",
|
||||
" shift",
|
||||
" continue",
|
||||
" fi",
|
||||
' if [ "$1" = "--output-last-message" ]; then',
|
||||
" shift",
|
||||
' output_path="$1"',
|
||||
" shift",
|
||||
" continue",
|
||||
" fi",
|
||||
" shift",
|
||||
"done",
|
||||
'stdin_content="$(cat)"',
|
||||
'if [ "$T3_FAKE_CODEX_REQUIRE_IMAGE" = "1" ] && [ "$seen_image" != "1" ]; then',
|
||||
' printf "%s\\n" "missing --image input" >&2',
|
||||
" exit 2",
|
||||
"fi",
|
||||
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" ]; then',
|
||||
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" >/dev/null || {',
|
||||
' printf "%s\\n" "stdin missing expected content" >&2',
|
||||
" exit 3",
|
||||
" }",
|
||||
"fi",
|
||||
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" ]; then',
|
||||
' if printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" >/dev/null; then',
|
||||
' printf "%s\\n" "stdin contained forbidden content" >&2',
|
||||
" exit 4",
|
||||
" fi",
|
||||
"fi",
|
||||
'if [ -n "$T3_FAKE_CODEX_STDERR" ]; then',
|
||||
' printf "%s\\n" "$T3_FAKE_CODEX_STDERR" >&2',
|
||||
"fi",
|
||||
...(input.requireImage
|
||||
? [
|
||||
'if [ "$seen_image" != "1" ]; then',
|
||||
' printf "%s\\n" "missing --image input" >&2',
|
||||
` exit 2`,
|
||||
"fi",
|
||||
]
|
||||
: []),
|
||||
...(input.requireFastServiceTier
|
||||
? [
|
||||
'if [ "$seen_fast_service_tier" != "1" ]; then',
|
||||
' printf "%s\\n" "missing fast service tier config" >&2',
|
||||
` exit 5`,
|
||||
"fi",
|
||||
]
|
||||
: []),
|
||||
...(input.requireReasoningEffort !== undefined
|
||||
? [
|
||||
`if [ "$seen_reasoning_effort" != "model_reasoning_effort=\\"${input.requireReasoningEffort}\\"" ]; then`,
|
||||
' printf "%s\\n" "unexpected reasoning effort config: $seen_reasoning_effort" >&2',
|
||||
` exit 6`,
|
||||
"fi",
|
||||
]
|
||||
: []),
|
||||
...(input.forbidReasoningEffort
|
||||
? [
|
||||
'if [ -n "$seen_reasoning_effort" ]; then',
|
||||
' printf "%s\\n" "reasoning effort config should be omitted: $seen_reasoning_effort" >&2',
|
||||
` exit 7`,
|
||||
"fi",
|
||||
]
|
||||
: []),
|
||||
...(input.stdinMustContain !== undefined
|
||||
? [
|
||||
`if ! printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustContain)} >/dev/null; then`,
|
||||
' printf "%s\\n" "stdin missing expected content" >&2',
|
||||
` exit 3`,
|
||||
"fi",
|
||||
]
|
||||
: []),
|
||||
...(input.stdinMustNotContain !== undefined
|
||||
? [
|
||||
`if printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustNotContain)} >/dev/null; then`,
|
||||
' printf "%s\\n" "stdin contained forbidden content" >&2',
|
||||
` exit 4`,
|
||||
"fi",
|
||||
]
|
||||
: []),
|
||||
...(input.stderr !== undefined
|
||||
? [`printf "%s\\n" ${JSON.stringify(input.stderr)} >&2`]
|
||||
: []),
|
||||
'if [ -n "$output_path" ]; then',
|
||||
' node -e \'const fs=require("node:fs"); const value=process.argv[2] ?? ""; fs.writeFileSync(process.argv[1], Buffer.from(value, "base64"));\' "$output_path" "${T3_FAKE_CODEX_OUTPUT_B64:-e30=}"',
|
||||
" cat > \"$output_path\" <<'__T3CODE_FAKE_CODEX_OUTPUT__'",
|
||||
input.output,
|
||||
"__T3CODE_FAKE_CODEX_OUTPUT__",
|
||||
"fi",
|
||||
'exit "${T3_FAKE_CODEX_EXIT_CODE:-0}"',
|
||||
`exit ${input.exitCode ?? 0}`,
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* fs.chmod(codexPath, 0o755);
|
||||
return binDir;
|
||||
return codexPath;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -82,6 +155,9 @@ function withFakeCodexEnv<A, E, R>(
|
||||
exitCode?: number;
|
||||
stderr?: string;
|
||||
requireImage?: boolean;
|
||||
requireFastServiceTier?: boolean;
|
||||
requireReasoningEffort?: string;
|
||||
forbidReasoningEffort?: boolean;
|
||||
stdinMustContain?: string;
|
||||
stdinMustNotContain?: string;
|
||||
},
|
||||
@@ -91,101 +167,29 @@ function withFakeCodexEnv<A, E, R>(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
|
||||
const binDir = yield* makeFakeCodexBinary(tempDir);
|
||||
const previousPath = process.env.PATH;
|
||||
const previousOutput = process.env.T3_FAKE_CODEX_OUTPUT_B64;
|
||||
const previousExitCode = process.env.T3_FAKE_CODEX_EXIT_CODE;
|
||||
const previousStderr = process.env.T3_FAKE_CODEX_STDERR;
|
||||
const previousRequireImage = process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||
const previousStdinMustContain = process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
||||
const previousStdinMustNotContain = process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
||||
|
||||
yield* Effect.sync(() => {
|
||||
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
|
||||
process.env.T3_FAKE_CODEX_OUTPUT_B64 = Buffer.from(input.output, "utf8").toString("base64");
|
||||
|
||||
if (input.exitCode !== undefined) {
|
||||
process.env.T3_FAKE_CODEX_EXIT_CODE = String(input.exitCode);
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
|
||||
}
|
||||
|
||||
if (input.stderr !== undefined) {
|
||||
process.env.T3_FAKE_CODEX_STDERR = input.stderr;
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CODEX_STDERR;
|
||||
}
|
||||
|
||||
if (input.requireImage) {
|
||||
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = "1";
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||
}
|
||||
|
||||
if (input.stdinMustContain !== undefined) {
|
||||
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = input.stdinMustContain;
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
||||
}
|
||||
|
||||
if (input.stdinMustNotContain !== undefined) {
|
||||
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = input.stdinMustNotContain;
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
||||
}
|
||||
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const previousSettings = yield* serverSettings.getSettings;
|
||||
yield* serverSettings.updateSettings({
|
||||
providers: {
|
||||
codex: {
|
||||
binaryPath: codexPath,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
previousPath,
|
||||
previousOutput,
|
||||
previousExitCode,
|
||||
previousStderr,
|
||||
previousRequireImage,
|
||||
previousStdinMustContain,
|
||||
previousStdinMustNotContain,
|
||||
};
|
||||
return { serverSettings, previousBinaryPath: previousSettings.providers.codex.binaryPath };
|
||||
}),
|
||||
() => effect,
|
||||
(previous) =>
|
||||
Effect.sync(() => {
|
||||
process.env.PATH = previous.previousPath;
|
||||
|
||||
if (previous.previousOutput === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_OUTPUT_B64;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_OUTPUT_B64 = previous.previousOutput;
|
||||
}
|
||||
|
||||
if (previous.previousExitCode === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_EXIT_CODE = previous.previousExitCode;
|
||||
}
|
||||
|
||||
if (previous.previousStderr === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_STDERR;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_STDERR = previous.previousStderr;
|
||||
}
|
||||
|
||||
if (previous.previousRequireImage === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = previous.previousRequireImage;
|
||||
}
|
||||
|
||||
if (previous.previousStdinMustContain === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
|
||||
}
|
||||
|
||||
if (previous.previousStdinMustNotContain === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = previous.previousStdinMustNotContain;
|
||||
}
|
||||
}),
|
||||
({ serverSettings, previousBinaryPath }) =>
|
||||
serverSettings
|
||||
.updateSettings({
|
||||
providers: {
|
||||
codex: {
|
||||
binaryPath: previousBinaryPath,
|
||||
},
|
||||
},
|
||||
})
|
||||
.pipe(Effect.asVoid),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -208,6 +212,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
branch: "feature/codex-effect",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.subject.length).toBeLessThanOrEqual(72);
|
||||
@@ -218,6 +223,63 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"forwards codex fast mode and non-default reasoning effort into codex exec config",
|
||||
() =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
subject: "Add important change",
|
||||
body: "",
|
||||
}),
|
||||
requireFastServiceTier: true,
|
||||
requireReasoningEffort: "xhigh",
|
||||
stdinMustNotContain: "branch must be a short semantic git branch fragment",
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/codex-effect",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("defaults git text generation codex effort to low", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
subject: "Add important change",
|
||||
body: "",
|
||||
}),
|
||||
requireReasoningEffort: "low",
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/codex-effect",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("generates commit message with branch when includeBranch is true", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
@@ -237,6 +299,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
includeBranch: true,
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Add important change");
|
||||
@@ -263,6 +326,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
commitSummary: "feat: improve orchestration flow",
|
||||
diffSummary: "2 files changed",
|
||||
diffPatch: "diff --git a/a.ts b/a.ts",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("Improve orchestration flow");
|
||||
@@ -286,6 +350,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
const generated = yield* textGeneration.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Please update session handling.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.branch).toBe("feat/session");
|
||||
@@ -293,6 +358,70 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("generates thread titles and trims them for sidebar use", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
title:
|
||||
' "Investigate websocket reconnect regressions after worktree restore" \nignored line',
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Please investigate websocket reconnect regressions after a worktree restore.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("Investigate websocket reconnect regressions aft...");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("falls back when thread title normalization becomes whitespace-only", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
title: ' """ """ ',
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Name this thread.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("New thread");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("trims whitespace exposed after quote removal in thread titles", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
title: ` "' hello world '" `,
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Name this thread.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("hello world");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("omits attachment metadata section when no attachments are provided", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
@@ -307,6 +436,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
const generated = yield* textGeneration.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix timeout behavior.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.branch).toBe("fix/session-timeout");
|
||||
@@ -333,21 +463,20 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
|
||||
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const generated = yield* textGeneration
|
||||
.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix layout bug from screenshot.",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: attachmentId,
|
||||
name: "bug.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
})
|
||||
.pipe(Effect.ensuring(fs.remove(attachmentPath).pipe(Effect.catch(() => Effect.void))));
|
||||
const generated = yield* textGeneration.generateBranchName({
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
cwd: process.cwd(),
|
||||
message: "Fix layout bug from screenshot.",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: attachmentId,
|
||||
name: "bug.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(generated.branch).toBe("fix/ui-regression");
|
||||
}),
|
||||
@@ -374,6 +503,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const generated = yield* textGeneration
|
||||
.generateBranchName({
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
cwd: process.cwd(),
|
||||
message: "Fix layout bug from screenshot.",
|
||||
attachments: [
|
||||
@@ -421,6 +551,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const result = yield* textGeneration
|
||||
.generateBranchName({
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
cwd: process.cwd(),
|
||||
message: "Fix layout bug from screenshot.",
|
||||
attachments: [
|
||||
@@ -433,17 +564,12 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
},
|
||||
],
|
||||
})
|
||||
.pipe(
|
||||
Effect.match({
|
||||
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
||||
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
||||
}),
|
||||
);
|
||||
.pipe(Effect.result);
|
||||
|
||||
expect(result._tag).toBe("Left");
|
||||
if (result._tag === "Left") {
|
||||
expect(result.left).toBeInstanceOf(TextGenerationError);
|
||||
expect(result.left.message).toContain("missing --image input");
|
||||
expect(Result.isFailure(result)).toBe(true);
|
||||
if (Result.isFailure(result)) {
|
||||
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
||||
expect(result.failure.message).toContain("missing --image input");
|
||||
}
|
||||
}),
|
||||
),
|
||||
@@ -465,18 +591,14 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix websocket reconnect flake",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
})
|
||||
.pipe(
|
||||
Effect.match({
|
||||
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
||||
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
||||
}),
|
||||
);
|
||||
.pipe(Effect.result);
|
||||
|
||||
expect(result._tag).toBe("Left");
|
||||
if (result._tag === "Left") {
|
||||
expect(result.left).toBeInstanceOf(TextGenerationError);
|
||||
expect(result.left.message).toContain("Codex returned invalid structured output");
|
||||
expect(Result.isFailure(result)).toBe(true);
|
||||
if (Result.isFailure(result)) {
|
||||
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
||||
expect(result.failure.message).toContain("Codex returned invalid structured output");
|
||||
}
|
||||
}),
|
||||
),
|
||||
@@ -498,18 +620,16 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
branch: "feature/codex-error",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
})
|
||||
.pipe(
|
||||
Effect.match({
|
||||
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
||||
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
||||
}),
|
||||
);
|
||||
.pipe(Effect.result);
|
||||
|
||||
expect(result._tag).toBe("Left");
|
||||
if (result._tag === "Left") {
|
||||
expect(result.left).toBeInstanceOf(TextGenerationError);
|
||||
expect(result.left.message).toContain("Codex CLI command failed: codex execution failed");
|
||||
expect(Result.isFailure(result)).toBe(true);
|
||||
if (Result.isFailure(result)) {
|
||||
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
||||
expect(result.failure.message).toContain(
|
||||
"Codex CLI command failed: codex execution failed",
|
||||
);
|
||||
}
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
|
||||
import { Effect, FileSystem, Layer, Option, Path, Schema, Scope, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { DEFAULT_GIT_TEXT_GENERATION_MODEL } from "@t3tools/contracts";
|
||||
import { CodexModelSelection } from "@t3tools/contracts";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
@@ -11,95 +11,34 @@ import { ServerConfig } from "../../config.ts";
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import {
|
||||
type BranchNameGenerationInput,
|
||||
type BranchNameGenerationResult,
|
||||
type CommitMessageGenerationResult,
|
||||
type PrContentGenerationResult,
|
||||
type ThreadTitleGenerationResult,
|
||||
type TextGenerationShape,
|
||||
TextGeneration,
|
||||
} from "../Services/TextGeneration.ts";
|
||||
import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "../Prompts.ts";
|
||||
import {
|
||||
normalizeCliError,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
toJsonSchemaObject,
|
||||
} from "../Utils.ts";
|
||||
import { normalizeCodexModelOptions } from "../../provider/Layers/CodexProvider.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
const CODEX_REASONING_EFFORT = "low";
|
||||
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
|
||||
const CODEX_TIMEOUT_MS = 180_000;
|
||||
|
||||
function toCodexOutputJsonSchema(schema: Schema.Top): unknown {
|
||||
const document = Schema.toJsonSchemaDocument(schema);
|
||||
if (document.definitions && Object.keys(document.definitions).length > 0) {
|
||||
return {
|
||||
...document.schema,
|
||||
$defs: document.definitions,
|
||||
};
|
||||
}
|
||||
return document.schema;
|
||||
}
|
||||
|
||||
function normalizeCodexError(
|
||||
operation: string,
|
||||
error: unknown,
|
||||
fallback: string,
|
||||
): TextGenerationError {
|
||||
if (Schema.is(TextGenerationError)(error)) {
|
||||
return error;
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
const lower = error.message.toLowerCase();
|
||||
if (
|
||||
error.message.includes("Command not found: codex") ||
|
||||
lower.includes("spawn codex") ||
|
||||
lower.includes("enoent")
|
||||
) {
|
||||
return new TextGenerationError({
|
||||
operation,
|
||||
detail: "Codex CLI (`codex`) is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
return new TextGenerationError({
|
||||
operation,
|
||||
detail: `${fallback}: ${error.message}`,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new TextGenerationError({
|
||||
operation,
|
||||
detail: fallback,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
function limitSection(value: string, maxChars: number): string {
|
||||
if (value.length <= maxChars) return value;
|
||||
const truncated = value.slice(0, maxChars);
|
||||
return `${truncated}\n\n[truncated]`;
|
||||
}
|
||||
|
||||
function sanitizeCommitSubject(raw: string): string {
|
||||
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
|
||||
if (withoutTrailingPeriod.length === 0) {
|
||||
return "Update project files";
|
||||
}
|
||||
|
||||
if (withoutTrailingPeriod.length <= 72) {
|
||||
return withoutTrailingPeriod;
|
||||
}
|
||||
return withoutTrailingPeriod.slice(0, 72).trimEnd();
|
||||
}
|
||||
|
||||
function sanitizePrTitle(raw: string): string {
|
||||
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||
if (singleLine.length > 0) {
|
||||
return singleLine;
|
||||
}
|
||||
return "Update project changes";
|
||||
}
|
||||
|
||||
const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const serverSettingsService = yield* Effect.service(ServerSettingsService);
|
||||
|
||||
type MaterializedImageAttachments = {
|
||||
readonly imagePaths: ReadonlyArray<string>;
|
||||
@@ -109,46 +48,48 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
operation: string,
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
): Effect.Effect<string, TextGenerationError> =>
|
||||
Effect.gen(function* () {
|
||||
let text = "";
|
||||
yield* Stream.runForEach(stream, (chunk) =>
|
||||
Effect.sync(() => {
|
||||
text += Buffer.from(chunk).toString("utf8");
|
||||
}),
|
||||
).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCodexError(operation, cause, "Failed to collect process output"),
|
||||
),
|
||||
);
|
||||
return text;
|
||||
});
|
||||
|
||||
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
|
||||
stream.pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.runFold(
|
||||
() => "",
|
||||
(acc, chunk) => acc + chunk,
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("codex", operation, cause, "Failed to collect process output"),
|
||||
),
|
||||
);
|
||||
|
||||
const writeTempFile = (
|
||||
operation: string,
|
||||
prefix: string,
|
||||
content: string,
|
||||
): Effect.Effect<string, TextGenerationError> => {
|
||||
const filePath = path.join(tempDir, `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`);
|
||||
return fileSystem.writeFileString(filePath, content).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: `Failed to write temp file at ${filePath}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.as(filePath),
|
||||
);
|
||||
): Effect.Effect<string, TextGenerationError, Scope.Scope> => {
|
||||
return fileSystem
|
||||
.makeTempFileScoped({
|
||||
prefix: `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`,
|
||||
})
|
||||
.pipe(
|
||||
Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: `Failed to write temp file`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
||||
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
const materializeImageAttachments = (
|
||||
_operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName",
|
||||
_operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle",
|
||||
attachments: BranchNameGenerationInput["attachments"],
|
||||
): Effect.Effect<MaterializedImageAttachments, TextGenerationError> =>
|
||||
Effect.gen(function* () {
|
||||
@@ -187,36 +128,52 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
outputSchemaJson,
|
||||
imagePaths = [],
|
||||
cleanupPaths = [],
|
||||
model,
|
||||
modelSelection,
|
||||
}: {
|
||||
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
imagePaths?: ReadonlyArray<string>;
|
||||
cleanupPaths?: ReadonlyArray<string>;
|
||||
model?: string;
|
||||
modelSelection: CodexModelSelection;
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const schemaPath = yield* writeTempFile(
|
||||
operation,
|
||||
"codex-schema",
|
||||
JSON.stringify(toCodexOutputJsonSchema(outputSchemaJson)),
|
||||
JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
|
||||
);
|
||||
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
||||
|
||||
const codexSettings = yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => settings.providers.codex,
|
||||
).pipe(Effect.catch(() => Effect.undefined));
|
||||
|
||||
const runCodexCommand = Effect.gen(function* () {
|
||||
const normalizedOptions = normalizeCodexModelOptions(
|
||||
modelSelection.model,
|
||||
modelSelection.options,
|
||||
);
|
||||
const reasoningEffort =
|
||||
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
|
||||
const command = ChildProcess.make(
|
||||
"codex",
|
||||
codexSettings?.binaryPath || "codex",
|
||||
[
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
model ?? DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
modelSelection.model,
|
||||
"--config",
|
||||
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
|
||||
`model_reasoning_effort="${reasoningEffort}"`,
|
||||
...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
@@ -225,10 +182,14 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
"-",
|
||||
],
|
||||
{
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
|
||||
},
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdin: {
|
||||
stream: Stream.make(new TextEncoder().encode(prompt)),
|
||||
stream: Stream.encodeText(Stream.make(prompt)),
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -237,7 +198,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCodexError(operation, cause, "Failed to spawn Codex CLI process"),
|
||||
normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -246,9 +207,8 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
readStreamAsString(operation, child.stdout),
|
||||
readStreamAsString(operation, child.stderr),
|
||||
child.exitCode.pipe(
|
||||
Effect.map((value) => Number(value)),
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCodexError(operation, cause, "Failed to read Codex CLI exit code"),
|
||||
normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -314,158 +274,143 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
}).pipe(Effect.ensuring(cleanup));
|
||||
});
|
||||
|
||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = (input) => {
|
||||
const wantsBranch = input.includeBranch === true;
|
||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
|
||||
"CodexTextGeneration.generateCommitMessage",
|
||||
)(function* (input) {
|
||||
const { prompt, outputSchema } = buildCommitMessagePrompt({
|
||||
branch: input.branch,
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
});
|
||||
|
||||
const prompt = [
|
||||
"You write concise git commit messages.",
|
||||
wantsBranch
|
||||
? "Return a JSON object with keys: subject, body, branch."
|
||||
: "Return a JSON object with keys: subject, body.",
|
||||
"Rules:",
|
||||
"- subject must be imperative, <= 72 chars, and no trailing period",
|
||||
"- body can be empty string or short bullet points",
|
||||
...(wantsBranch
|
||||
? ["- branch must be a short semantic git branch fragment for this change"]
|
||||
: []),
|
||||
"- capture the primary user-visible or developer-visible change",
|
||||
"",
|
||||
`Branch: ${input.branch ?? "(detached)"}`,
|
||||
"",
|
||||
"Staged files:",
|
||||
limitSection(input.stagedSummary, 6_000),
|
||||
"",
|
||||
"Staged patch:",
|
||||
limitSection(input.stagedPatch, 40_000),
|
||||
].join("\n");
|
||||
if (input.modelSelection.provider !== "codex") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateCommitMessage",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const outputSchemaJson = wantsBranch
|
||||
? Schema.Struct({
|
||||
subject: Schema.String,
|
||||
body: Schema.String,
|
||||
branch: Schema.String,
|
||||
})
|
||||
: Schema.Struct({
|
||||
subject: Schema.String,
|
||||
body: Schema.String,
|
||||
});
|
||||
|
||||
return runCodexJson({
|
||||
const generated = yield* runCodexJson({
|
||||
operation: "generateCommitMessage",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(generated) =>
|
||||
({
|
||||
subject: sanitizeCommitSubject(generated.subject),
|
||||
body: generated.body.trim(),
|
||||
...("branch" in generated && typeof generated.branch === "string"
|
||||
? { branch: sanitizeFeatureBranchName(generated.branch) }
|
||||
: {}),
|
||||
}) satisfies CommitMessageGenerationResult,
|
||||
),
|
||||
);
|
||||
};
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
const generatePrContent: TextGenerationShape["generatePrContent"] = (input) => {
|
||||
const prompt = [
|
||||
"You write GitHub pull request content.",
|
||||
"Return a JSON object with keys: title, body.",
|
||||
"Rules:",
|
||||
"- title should be concise and specific",
|
||||
"- body must be markdown and include headings '## Summary' and '## Testing'",
|
||||
"- under Summary, provide short bullet points",
|
||||
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
|
||||
"",
|
||||
`Base branch: ${input.baseBranch}`,
|
||||
`Head branch: ${input.headBranch}`,
|
||||
"",
|
||||
"Commits:",
|
||||
limitSection(input.commitSummary, 12_000),
|
||||
"",
|
||||
"Diff stat:",
|
||||
limitSection(input.diffSummary, 12_000),
|
||||
"",
|
||||
"Diff patch:",
|
||||
limitSection(input.diffPatch, 40_000),
|
||||
].join("\n");
|
||||
return {
|
||||
subject: sanitizeCommitSubject(generated.subject),
|
||||
body: generated.body.trim(),
|
||||
...("branch" in generated && typeof generated.branch === "string"
|
||||
? { branch: sanitizeFeatureBranchName(generated.branch) }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
return runCodexJson({
|
||||
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
|
||||
"CodexTextGeneration.generatePrContent",
|
||||
)(function* (input) {
|
||||
const { prompt, outputSchema } = buildPrContentPrompt({
|
||||
baseBranch: input.baseBranch,
|
||||
headBranch: input.headBranch,
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "codex") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generatePrContent",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runCodexJson({
|
||||
operation: "generatePrContent",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: Schema.Struct({
|
||||
title: Schema.String,
|
||||
body: Schema.String,
|
||||
}),
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(generated) =>
|
||||
({
|
||||
title: sanitizePrTitle(generated.title),
|
||||
body: generated.body.trim(),
|
||||
}) satisfies PrContentGenerationResult,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const generateBranchName: TextGenerationShape["generateBranchName"] = (input) => {
|
||||
return Effect.gen(function* () {
|
||||
const { imagePaths } = yield* materializeImageAttachments(
|
||||
"generateBranchName",
|
||||
input.attachments,
|
||||
);
|
||||
const attachmentLines = (input.attachments ?? []).map(
|
||||
(attachment) =>
|
||||
`- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
|
||||
);
|
||||
|
||||
const promptSections = [
|
||||
"You generate concise git branch names.",
|
||||
"Return a JSON object with key: branch.",
|
||||
"Rules:",
|
||||
"- Branch should describe the requested work from the user message.",
|
||||
"- Keep it short and specific (2-6 words).",
|
||||
"- Use plain words only, no issue prefixes and no punctuation-heavy text.",
|
||||
"- If images are attached, use them as primary context for visual/UI issues.",
|
||||
"",
|
||||
"User message:",
|
||||
limitSection(input.message, 8_000),
|
||||
];
|
||||
if (attachmentLines.length > 0) {
|
||||
promptSections.push(
|
||||
"",
|
||||
"Attachment metadata:",
|
||||
limitSection(attachmentLines.join("\n"), 4_000),
|
||||
);
|
||||
}
|
||||
const prompt = promptSections.join("\n");
|
||||
|
||||
const generated = yield* runCodexJson({
|
||||
operation: "generateBranchName",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: Schema.Struct({
|
||||
branch: Schema.String,
|
||||
}),
|
||||
imagePaths,
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
});
|
||||
|
||||
return {
|
||||
branch: sanitizeBranchFragment(generated.branch),
|
||||
} satisfies BranchNameGenerationResult;
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
title: sanitizePrTitle(generated.title),
|
||||
body: generated.body.trim(),
|
||||
};
|
||||
});
|
||||
|
||||
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
|
||||
"CodexTextGeneration.generateBranchName",
|
||||
)(function* (input) {
|
||||
const { imagePaths } = yield* materializeImageAttachments(
|
||||
"generateBranchName",
|
||||
input.attachments,
|
||||
);
|
||||
const { prompt, outputSchema } = buildBranchNamePrompt({
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "codex") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateBranchName",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runCodexJson({
|
||||
operation: "generateBranchName",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
imagePaths,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
branch: sanitizeBranchFragment(generated.branch),
|
||||
};
|
||||
});
|
||||
|
||||
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
|
||||
"CodexTextGeneration.generateThreadTitle",
|
||||
)(function* (input) {
|
||||
const { imagePaths } = yield* materializeImageAttachments(
|
||||
"generateThreadTitle",
|
||||
input.attachments,
|
||||
);
|
||||
const { prompt, outputSchema } = buildThreadTitlePrompt({
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "codex") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateThreadTitle",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runCodexJson({
|
||||
operation: "generateThreadTitle",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
imagePaths,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
title: sanitizeThreadTitle(generated.title),
|
||||
} satisfies ThreadTitleGenerationResult;
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
} satisfies TextGenerationShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
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 { Cause, Effect, Exit, FileSystem, Layer, PlatformError, Scope } from "effect";
|
||||
import { describe, expect, vi } from "vitest";
|
||||
|
||||
import { GitCoreLive, makeGitCore } from "./GitCore.ts";
|
||||
@@ -132,6 +133,12 @@ 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) => {
|
||||
@@ -415,6 +422,9 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
|
||||
it.effect("refreshes upstream behind count after checkout when remote branch advanced", () =>
|
||||
Effect.gen(function* () {
|
||||
const services = yield* Effect.services();
|
||||
const runPromise = Effect.runPromiseWith(services);
|
||||
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
const clone = yield* makeTmpDir();
|
||||
@@ -449,7 +459,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
const core = yield* GitCore;
|
||||
yield* Effect.promise(() =>
|
||||
vi.waitFor(async () => {
|
||||
const details = await Effect.runPromise(core.statusDetails(source));
|
||||
const details = await runPromise(core.statusDetails(source));
|
||||
expect(details.branch).toBe(featureBranch);
|
||||
expect(details.aheadCount).toBe(0);
|
||||
expect(details.behindCount).toBe(1);
|
||||
@@ -1274,6 +1284,20 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails cleanly when statusDetails is requested for a missing workspace", () =>
|
||||
Effect.gen(function* () {
|
||||
const missingCwd = path.join(os.tmpdir(), `git-missing-${crypto.randomUUID()}`);
|
||||
const result = yield* Effect.exit((yield* GitCore).statusDetails(missingCwd));
|
||||
|
||||
expect(Exit.isFailure(result)).toBe(true);
|
||||
if (Exit.isFailure(result)) {
|
||||
const error = Cause.squash(result.cause);
|
||||
expect(error).toBeInstanceOf(GitCommandError);
|
||||
expect((error as GitCommandError).detail).toContain("Workspace folder is missing");
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("computes ahead count against base branch when no upstream is configured", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
@@ -1667,6 +1691,40 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prepareCommitContext truncates oversized staged patches instead of failing", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const core = yield* GitCore;
|
||||
|
||||
yield* writeTextFile(path.join(tmp, "README.md"), buildLargeText());
|
||||
|
||||
const context = yield* core.prepareCommitContext(tmp);
|
||||
expect(context).not.toBeNull();
|
||||
expect(context!.stagedSummary).toContain("README.md");
|
||||
expect(context!.stagedPatch).toContain("[truncated]");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("readRangeContext truncates oversized diff patches instead of failing", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const { initialBranch } = yield* initRepoWithCommit(tmp);
|
||||
const core = yield* GitCore;
|
||||
|
||||
yield* core.createBranch({ cwd: tmp, branch: "feature/large-range-context" });
|
||||
yield* core.checkoutBranch({ cwd: tmp, branch: "feature/large-range-context" });
|
||||
yield* writeTextFile(path.join(tmp, "large.txt"), buildLargeText());
|
||||
yield* git(tmp, ["add", "large.txt"]);
|
||||
yield* git(tmp, ["commit", "-m", "Add large range context"]);
|
||||
|
||||
const rangeContext = yield* core.readRangeContext(tmp, initialBranch);
|
||||
expect(rangeContext.commitSummary).toContain("Add large range context");
|
||||
expect(rangeContext.diffSummary).toContain("large.txt");
|
||||
expect(rangeContext.diffPatch).toContain("[truncated]");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("pushes with upstream setup and then skips when up to date", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
|
||||
+1451
-1383
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 } from "@t3tools/contracts";
|
||||
import type { GitActionProgressEvent, ModelSelection } from "@t3tools/contracts";
|
||||
|
||||
import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts";
|
||||
import { type GitManagerShape } from "../Services/GitManager.ts";
|
||||
@@ -20,6 +20,7 @@ import { GitCoreLive } from "./GitCore.ts";
|
||||
import { GitCore } from "../Services/GitCore.ts";
|
||||
import { makeGitManager } from "./GitManager.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
interface FakeGhScenario {
|
||||
prListSequence?: string[];
|
||||
@@ -48,6 +49,7 @@ interface FakeGitTextGeneration {
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
includeBranch?: boolean;
|
||||
modelSelection: ModelSelection;
|
||||
}) => Effect.Effect<
|
||||
{ subject: string; body: string; branch?: string | undefined },
|
||||
TextGenerationError
|
||||
@@ -59,11 +61,18 @@ interface FakeGitTextGeneration {
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
modelSelection: ModelSelection;
|
||||
}) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;
|
||||
generateBranchName: (input: {
|
||||
cwd: string;
|
||||
message: string;
|
||||
modelSelection: ModelSelection;
|
||||
}) => Effect.Effect<{ branch: string }, TextGenerationError>;
|
||||
generateThreadTitle: (input: {
|
||||
cwd: string;
|
||||
message: string;
|
||||
modelSelection: ModelSelection;
|
||||
}) => Effect.Effect<{ title: string }, TextGenerationError>;
|
||||
}
|
||||
|
||||
type FakePullRequest = NonNullable<FakeGhScenario["pullRequest"]>;
|
||||
@@ -167,6 +176,10 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): T
|
||||
Effect.succeed({
|
||||
branch: "update-workflow",
|
||||
}),
|
||||
generateThreadTitle: () =>
|
||||
Effect.succeed({
|
||||
title: "Update workflow",
|
||||
}),
|
||||
...overrides,
|
||||
};
|
||||
|
||||
@@ -204,6 +217,17 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): T
|
||||
}),
|
||||
),
|
||||
),
|
||||
generateThreadTitle: (input) =>
|
||||
implementation.generateThreadTitle(input).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation: "generateThreadTitle",
|
||||
detail: "fake text generation failed",
|
||||
...(cause !== undefined ? { cause } : {}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -487,6 +511,8 @@ function makeManager(input?: {
|
||||
prefix: "t3-git-manager-test-",
|
||||
});
|
||||
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest();
|
||||
|
||||
const gitCoreLayer = GitCoreLive.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(ServerConfigLayer),
|
||||
@@ -496,9 +522,10 @@ function makeManager(input?: {
|
||||
Layer.succeed(GitHubCli, gitHubCli),
|
||||
Layer.succeed(TextGeneration, textGeneration),
|
||||
gitCoreLayer,
|
||||
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
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* RoutingTextGeneration – Dispatches text generation requests to either the
|
||||
* Codex CLI or Claude CLI implementation based on the provider in each
|
||||
* request input.
|
||||
*
|
||||
* When `modelSelection.provider` is `"claudeAgent"` the request is forwarded to
|
||||
* the Claude layer; for any other value (including the default `undefined`) it
|
||||
* falls through to the Codex layer.
|
||||
*
|
||||
* @module RoutingTextGeneration
|
||||
*/
|
||||
import { Effect, Layer, ServiceMap } from "effect";
|
||||
|
||||
import {
|
||||
TextGeneration,
|
||||
type TextGenerationProvider,
|
||||
type TextGenerationShape,
|
||||
} from "../Services/TextGeneration.ts";
|
||||
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Internal service tags so both concrete layers can coexist.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class CodexTextGen extends ServiceMap.Service<CodexTextGen, TextGenerationShape>()(
|
||||
"t3/git/Layers/RoutingTextGeneration/CodexTextGen",
|
||||
) {}
|
||||
|
||||
class ClaudeTextGen extends ServiceMap.Service<ClaudeTextGen, TextGenerationShape>()(
|
||||
"t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
|
||||
) {}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Routing implementation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const makeRoutingTextGeneration = Effect.gen(function* () {
|
||||
const codex = yield* CodexTextGen;
|
||||
const claude = yield* ClaudeTextGen;
|
||||
|
||||
const route = (provider?: TextGenerationProvider): TextGenerationShape =>
|
||||
provider === "claudeAgent" ? claude : codex;
|
||||
|
||||
return {
|
||||
generateCommitMessage: (input) =>
|
||||
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;
|
||||
});
|
||||
|
||||
const InternalCodexLayer = Layer.effect(
|
||||
CodexTextGen,
|
||||
Effect.gen(function* () {
|
||||
const svc = yield* TextGeneration;
|
||||
return svc;
|
||||
}),
|
||||
).pipe(Layer.provide(CodexTextGenerationLive));
|
||||
|
||||
const InternalClaudeLayer = Layer.effect(
|
||||
ClaudeTextGen,
|
||||
Effect.gen(function* () {
|
||||
const svc = yield* TextGeneration;
|
||||
return svc;
|
||||
}),
|
||||
).pipe(Layer.provide(ClaudeTextGenerationLive));
|
||||
|
||||
export const RoutingTextGenerationLive = Layer.effect(
|
||||
TextGeneration,
|
||||
makeRoutingTextGeneration,
|
||||
).pipe(Layer.provide(InternalCodexLayer), Layer.provide(InternalClaudeLayer));
|
||||
@@ -0,0 +1,193 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./Prompts.ts";
|
||||
import { normalizeCliError, sanitizeThreadTitle } from "./Utils.ts";
|
||||
import { TextGenerationError } from "./Errors.ts";
|
||||
|
||||
describe("buildCommitMessagePrompt", () => {
|
||||
it("includes staged patch and summary in the prompt", () => {
|
||||
const result = buildCommitMessagePrompt({
|
||||
branch: "main",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md\n+hello",
|
||||
includeBranch: false,
|
||||
});
|
||||
|
||||
expect(result.prompt).toContain("Staged files:");
|
||||
expect(result.prompt).toContain("M README.md");
|
||||
expect(result.prompt).toContain("Staged patch:");
|
||||
expect(result.prompt).toContain("diff --git a/README.md b/README.md");
|
||||
expect(result.prompt).toContain("Branch: main");
|
||||
// Should NOT include the branch generation instruction
|
||||
expect(result.prompt).not.toContain("branch must be a short semantic git branch fragment");
|
||||
});
|
||||
|
||||
it("includes branch generation instruction when includeBranch is true", () => {
|
||||
const result = buildCommitMessagePrompt({
|
||||
branch: "feature/foo",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff",
|
||||
includeBranch: true,
|
||||
});
|
||||
|
||||
expect(result.prompt).toContain("branch must be a short semantic git branch fragment");
|
||||
expect(result.prompt).toContain("Return a JSON object with keys: subject, body, branch.");
|
||||
});
|
||||
|
||||
it("shows (detached) when branch is null", () => {
|
||||
const result = buildCommitMessagePrompt({
|
||||
branch: null,
|
||||
stagedSummary: "M a.ts",
|
||||
stagedPatch: "diff",
|
||||
includeBranch: false,
|
||||
});
|
||||
|
||||
expect(result.prompt).toContain("Branch: (detached)");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildPrContentPrompt", () => {
|
||||
it("includes branch names, commits, and diff in the prompt", () => {
|
||||
const result = buildPrContentPrompt({
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/auth",
|
||||
commitSummary: "feat: add login page",
|
||||
diffSummary: "3 files changed",
|
||||
diffPatch: "diff --git a/auth.ts b/auth.ts\n+export function login()",
|
||||
});
|
||||
|
||||
expect(result.prompt).toContain("Base branch: main");
|
||||
expect(result.prompt).toContain("Head branch: feature/auth");
|
||||
expect(result.prompt).toContain("Commits:");
|
||||
expect(result.prompt).toContain("feat: add login page");
|
||||
expect(result.prompt).toContain("Diff stat:");
|
||||
expect(result.prompt).toContain("3 files changed");
|
||||
expect(result.prompt).toContain("Diff patch:");
|
||||
expect(result.prompt).toContain("export function login()");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildBranchNamePrompt", () => {
|
||||
it("includes the user message in the prompt", () => {
|
||||
const result = buildBranchNamePrompt({
|
||||
message: "Fix the login timeout bug",
|
||||
});
|
||||
|
||||
expect(result.prompt).toContain("User message:");
|
||||
expect(result.prompt).toContain("Fix the login timeout bug");
|
||||
expect(result.prompt).not.toContain("Attachment metadata:");
|
||||
});
|
||||
|
||||
it("includes attachment metadata when attachments are provided", () => {
|
||||
const result = buildBranchNamePrompt({
|
||||
message: "Fix the layout from screenshot",
|
||||
attachments: [
|
||||
{
|
||||
type: "image" as const,
|
||||
id: "att-123",
|
||||
name: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 12345,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(result.prompt).toContain("Attachment metadata:");
|
||||
expect(result.prompt).toContain("screenshot.png");
|
||||
expect(result.prompt).toContain("image/png");
|
||||
expect(result.prompt).toContain("12345 bytes");
|
||||
});
|
||||
});
|
||||
|
||||
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(
|
||||
"claude",
|
||||
"generateCommitMessage",
|
||||
new Error("Command not found: claude"),
|
||||
"Something went wrong",
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(TextGenerationError);
|
||||
expect(error.detail).toContain("Claude CLI");
|
||||
expect(error.detail).toContain("not available on PATH");
|
||||
});
|
||||
|
||||
it("uses the CLI name from the first argument for codex", () => {
|
||||
const error = normalizeCliError(
|
||||
"codex",
|
||||
"generateBranchName",
|
||||
new Error("Command not found: codex"),
|
||||
"Something went wrong",
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(TextGenerationError);
|
||||
expect(error.detail).toContain("Codex CLI");
|
||||
expect(error.detail).toContain("not available on PATH");
|
||||
});
|
||||
|
||||
it("returns the error as-is if it is already a TextGenerationError", () => {
|
||||
const existing = new TextGenerationError({
|
||||
operation: "generatePrContent",
|
||||
detail: "Already wrapped",
|
||||
});
|
||||
|
||||
const result = normalizeCliError("claude", "generatePrContent", existing, "fallback");
|
||||
|
||||
expect(result).toBe(existing);
|
||||
});
|
||||
|
||||
it("wraps unknown non-Error values with the fallback message", () => {
|
||||
const result = normalizeCliError("codex", "generateCommitMessage", "string error", "fallback");
|
||||
|
||||
expect(result).toBeInstanceOf(TextGenerationError);
|
||||
expect(result.detail).toBe("fallback");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* Shared prompt builders for text generation providers.
|
||||
*
|
||||
* Extracts the prompt construction logic that is identical across
|
||||
* Codex, Claude, and any future CLI-based text generation backends.
|
||||
*
|
||||
* @module textGenerationPrompts
|
||||
*/
|
||||
import { Schema } from "effect";
|
||||
import type { ChatAttachment } from "@t3tools/contracts";
|
||||
|
||||
import { limitSection } from "./Utils.ts";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Commit message
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface CommitMessagePromptInput {
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
includeBranch: boolean;
|
||||
}
|
||||
|
||||
export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
|
||||
const wantsBranch = input.includeBranch;
|
||||
|
||||
const prompt = [
|
||||
"You write concise git commit messages.",
|
||||
wantsBranch
|
||||
? "Return a JSON object with keys: subject, body, branch."
|
||||
: "Return a JSON object with keys: subject, body.",
|
||||
"Rules:",
|
||||
"- subject must be imperative, <= 72 chars, and no trailing period",
|
||||
"- body can be empty string or short bullet points",
|
||||
...(wantsBranch
|
||||
? ["- branch must be a short semantic git branch fragment for this change"]
|
||||
: []),
|
||||
"- capture the primary user-visible or developer-visible change",
|
||||
"",
|
||||
`Branch: ${input.branch ?? "(detached)"}`,
|
||||
"",
|
||||
"Staged files:",
|
||||
limitSection(input.stagedSummary, 6_000),
|
||||
"",
|
||||
"Staged patch:",
|
||||
limitSection(input.stagedPatch, 40_000),
|
||||
].join("\n");
|
||||
|
||||
if (wantsBranch) {
|
||||
return {
|
||||
prompt,
|
||||
outputSchema: Schema.Struct({
|
||||
subject: Schema.String,
|
||||
body: Schema.String,
|
||||
branch: Schema.String,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
prompt,
|
||||
outputSchema: Schema.Struct({
|
||||
subject: Schema.String,
|
||||
body: Schema.String,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PR content
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface PrContentPromptInput {
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
}
|
||||
|
||||
export function buildPrContentPrompt(input: PrContentPromptInput) {
|
||||
const prompt = [
|
||||
"You write GitHub pull request content.",
|
||||
"Return a JSON object with keys: title, body.",
|
||||
"Rules:",
|
||||
"- title should be concise and specific",
|
||||
"- body must be markdown and include headings '## Summary' and '## Testing'",
|
||||
"- under Summary, provide short bullet points",
|
||||
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
|
||||
"",
|
||||
`Base branch: ${input.baseBranch}`,
|
||||
`Head branch: ${input.headBranch}`,
|
||||
"",
|
||||
"Commits:",
|
||||
limitSection(input.commitSummary, 12_000),
|
||||
"",
|
||||
"Diff stat:",
|
||||
limitSection(input.diffSummary, 12_000),
|
||||
"",
|
||||
"Diff patch:",
|
||||
limitSection(input.diffPatch, 40_000),
|
||||
].join("\n");
|
||||
|
||||
const outputSchema = Schema.Struct({
|
||||
title: Schema.String,
|
||||
body: Schema.String,
|
||||
});
|
||||
|
||||
return { prompt, outputSchema };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Branch name
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface BranchNamePromptInput {
|
||||
message: string;
|
||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
}
|
||||
|
||||
interface PromptFromMessageInput {
|
||||
instruction: string;
|
||||
responseShape: string;
|
||||
rules: ReadonlyArray<string>;
|
||||
message: string;
|
||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
}
|
||||
|
||||
function buildPromptFromMessage(input: PromptFromMessageInput): string {
|
||||
const attachmentLines = (input.attachments ?? []).map(
|
||||
(attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
|
||||
);
|
||||
|
||||
const promptSections = [
|
||||
input.instruction,
|
||||
input.responseShape,
|
||||
"Rules:",
|
||||
...input.rules.map((rule) => `- ${rule}`),
|
||||
"",
|
||||
"User message:",
|
||||
limitSection(input.message, 8_000),
|
||||
];
|
||||
if (attachmentLines.length > 0) {
|
||||
promptSections.push(
|
||||
"",
|
||||
"Attachment metadata:",
|
||||
limitSection(attachmentLines.join("\n"), 4_000),
|
||||
);
|
||||
}
|
||||
|
||||
return promptSections.join("\n");
|
||||
}
|
||||
|
||||
export function buildBranchNamePrompt(input: BranchNamePromptInput) {
|
||||
const prompt = buildPromptFromMessage({
|
||||
instruction: "You generate concise git branch names.",
|
||||
responseShape: "Return a JSON object with key: branch.",
|
||||
rules: [
|
||||
"Branch should describe the requested work from the user message.",
|
||||
"Keep it short and specific (2-6 words).",
|
||||
"Use plain words only, no issue prefixes and no punctuation-heavy text.",
|
||||
"If images are attached, use them as primary context for visual/UI issues.",
|
||||
],
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
const outputSchema = Schema.Struct({
|
||||
branch: Schema.String,
|
||||
});
|
||||
|
||||
return { prompt, outputSchema };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Thread title
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface ThreadTitlePromptInput {
|
||||
message: string;
|
||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
}
|
||||
|
||||
export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
|
||||
const prompt = buildPromptFromMessage({
|
||||
instruction: "You write concise thread titles for coding conversations.",
|
||||
responseShape: "Return a JSON object with key: title.",
|
||||
rules: [
|
||||
"Title should summarize the user's request, not restate it verbatim.",
|
||||
"Keep it short and specific (3-8 words).",
|
||||
"Avoid quotes, filler, prefixes, and trailing punctuation.",
|
||||
"If images are attached, use them as primary context for visual/UI issues.",
|
||||
],
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
const outputSchema = Schema.Struct({
|
||||
title: Schema.String,
|
||||
});
|
||||
|
||||
return { prompt, outputSchema };
|
||||
}
|
||||
@@ -32,6 +32,7 @@ export interface ExecuteGitInput {
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly truncateOutputAtMaxBytes?: boolean;
|
||||
readonly progress?: ExecuteGitProgress;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,10 +8,13 @@
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type { ChatAttachment } from "@t3tools/contracts";
|
||||
import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
|
||||
|
||||
import type { TextGenerationError } from "../Errors.ts";
|
||||
|
||||
/** Providers that support git text generation (commit messages, PR content, branch names). */
|
||||
export type TextGenerationProvider = "codex" | "claudeAgent";
|
||||
|
||||
export interface CommitMessageGenerationInput {
|
||||
cwd: string;
|
||||
branch: string | null;
|
||||
@@ -19,8 +22,8 @@ export interface CommitMessageGenerationInput {
|
||||
stagedPatch: string;
|
||||
/** When true, the model also returns a semantic branch name for the change. */
|
||||
includeBranch?: boolean;
|
||||
/** Model to use for generation. Defaults to gpt-5.4-mini if not specified. */
|
||||
model?: string;
|
||||
/** What model and provider to use for generation. */
|
||||
modelSelection: ModelSelection;
|
||||
}
|
||||
|
||||
export interface CommitMessageGenerationResult {
|
||||
@@ -37,8 +40,8 @@ export interface PrContentGenerationInput {
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
/** Model to use for generation. Defaults to gpt-5.4-mini if not specified. */
|
||||
model?: string;
|
||||
/** What model and provider to use for generation. */
|
||||
modelSelection: ModelSelection;
|
||||
}
|
||||
|
||||
export interface PrContentGenerationResult {
|
||||
@@ -50,20 +53,33 @@ export interface BranchNameGenerationInput {
|
||||
cwd: string;
|
||||
message: string;
|
||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
/** Model to use for generation. Defaults to gpt-5.4-mini if not specified. */
|
||||
model?: string;
|
||||
/** What model and provider to use for generation. */
|
||||
modelSelection: ModelSelection;
|
||||
}
|
||||
|
||||
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>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -90,6 +106,13 @@ export interface TextGenerationShape {
|
||||
readonly generateBranchName: (
|
||||
input: BranchNameGenerationInput,
|
||||
) => Effect.Effect<BranchNameGenerationResult, TextGenerationError>;
|
||||
|
||||
/**
|
||||
* Generate a concise thread title from a user's first message.
|
||||
*/
|
||||
readonly generateThreadTitle: (
|
||||
input: ThreadTitleGenerationInput,
|
||||
) => Effect.Effect<ThreadTitleGenerationResult, TextGenerationError>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Shared utilities for text generation layers (Codex, Claude, etc.).
|
||||
*
|
||||
* @module textGenerationUtils
|
||||
*/
|
||||
import { Schema } from "effect";
|
||||
|
||||
import { TextGenerationError } from "./Errors.ts";
|
||||
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
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;
|
||||
const truncated = value.slice(0, maxChars);
|
||||
return `${truncated}\n\n[truncated]`;
|
||||
}
|
||||
|
||||
/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
|
||||
export function sanitizeCommitSubject(raw: string): string {
|
||||
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
|
||||
if (withoutTrailingPeriod.length === 0) {
|
||||
return "Update project files";
|
||||
}
|
||||
|
||||
if (withoutTrailingPeriod.length <= 72) {
|
||||
return withoutTrailingPeriod;
|
||||
}
|
||||
return withoutTrailingPeriod.slice(0, 72).trimEnd();
|
||||
}
|
||||
|
||||
/** Normalise a raw PR title to a single line with a sensible fallback. */
|
||||
export function sanitizePrTitle(raw: string): string {
|
||||
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||
if (singleLine.length > 0) {
|
||||
return singleLine;
|
||||
}
|
||||
return "Update project changes";
|
||||
}
|
||||
|
||||
/** 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);
|
||||
return `${capitalized} CLI (\`${cliName}\`)`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize an unknown error from a CLI text generation process into a
|
||||
* typed `TextGenerationError`. Parameterized by CLI name so both Codex
|
||||
* and Claude (and future providers) can share the same logic.
|
||||
*/
|
||||
export function normalizeCliError(
|
||||
cliName: string,
|
||||
operation: string,
|
||||
error: unknown,
|
||||
fallback: string,
|
||||
): TextGenerationError {
|
||||
if (Schema.is(TextGenerationError)(error)) {
|
||||
return error;
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
const lower = error.message.toLowerCase();
|
||||
if (
|
||||
error.message.includes(`Command not found: ${cliName}`) ||
|
||||
lower.includes(`spawn ${cliName}`) ||
|
||||
lower.includes("enoent")
|
||||
) {
|
||||
return new TextGenerationError({
|
||||
operation,
|
||||
detail: `${cliLabel(cliName)} is required but not available on PATH.`,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
return new TextGenerationError({
|
||||
operation,
|
||||
detail: `${fallback}: ${error.message}`,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new TextGenerationError({
|
||||
operation,
|
||||
detail: fallback,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
export function isGitRepository(cwd: string): boolean {
|
||||
return existsSync(join(cwd, ".git"));
|
||||
}
|
||||
@@ -165,6 +165,19 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("ships configurable thread navigation defaults", () =>
|
||||
Effect.sync(() => {
|
||||
const defaultsByCommand = new Map(
|
||||
DEFAULT_KEYBINDINGS.map((binding) => [binding.command, binding.key] as const),
|
||||
);
|
||||
|
||||
assert.equal(defaultsByCommand.get("thread.previous"), "mod+shift+[");
|
||||
assert.equal(defaultsByCommand.get("thread.next"), "mod+shift+]");
|
||||
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
|
||||
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses defaults in runtime when config is malformed without overriding file", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
MAX_WHEN_EXPRESSION_DEPTH,
|
||||
ResolvedKeybindingRule,
|
||||
ResolvedKeybindingsConfig,
|
||||
THREAD_JUMP_KEYBINDING_COMMANDS,
|
||||
type ServerConfigIssue,
|
||||
} from "@t3tools/contracts";
|
||||
import { Mutable } from "effect/Types";
|
||||
@@ -23,6 +24,7 @@ import {
|
||||
Cache,
|
||||
Cause,
|
||||
Deferred,
|
||||
Duration,
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
@@ -42,6 +44,7 @@ import {
|
||||
} from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { ServerConfig } from "./config";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
|
||||
export class KeybindingsConfigError extends Schema.TaggedErrorClass<KeybindingsConfigError>()(
|
||||
"KeybindingsConfigParseError",
|
||||
@@ -74,6 +77,12 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
|
||||
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
|
||||
{ key: "mod+o", command: "editor.openFavorite" },
|
||||
{ key: "mod+shift+[", command: "thread.previous" },
|
||||
{ key: "mod+shift+]", command: "thread.next" },
|
||||
...THREAD_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
|
||||
key: `mod+${index + 1}`,
|
||||
command,
|
||||
})),
|
||||
];
|
||||
|
||||
function normalizeKeyToken(token: string): string {
|
||||
@@ -408,7 +417,7 @@ function encodeWhenAst(node: KeybindingWhenNode): string {
|
||||
|
||||
const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
|
||||
|
||||
const RawKeybindingsEntries = Schema.fromJsonString(Schema.Array(Schema.Unknown));
|
||||
const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
|
||||
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
|
||||
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
|
||||
SchemaGetter.stringifyJson({ space: 2 }),
|
||||
@@ -672,6 +681,7 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })),
|
||||
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
|
||||
Effect.flatMap(() => fs.rename(tempPath, keybindingsConfigPath)),
|
||||
Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
@@ -817,16 +827,25 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
|
||||
const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
|
||||
|
||||
yield* Stream.runForEach(fs.watch(keybindingsConfigDir), (event) => {
|
||||
const isTargetConfigEvent =
|
||||
event.path === keybindingsConfigFile ||
|
||||
event.path === keybindingsConfigPath ||
|
||||
path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved;
|
||||
if (!isTargetConfigEvent) {
|
||||
return Effect.void;
|
||||
}
|
||||
return revalidateAndEmitSafely;
|
||||
}).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(watcherScope), Effect.asVoid);
|
||||
// Debounce watch events so the file is fully written before we read it.
|
||||
// Editors emit multiple events per save (truncate, write, rename) and
|
||||
// `fs.watch` can fire before the content has been flushed to disk.
|
||||
const debouncedKeybindingsEvents = fs.watch(keybindingsConfigDir).pipe(
|
||||
Stream.filter((event) => {
|
||||
return (
|
||||
event.path === keybindingsConfigFile ||
|
||||
event.path === keybindingsConfigPath ||
|
||||
path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved
|
||||
);
|
||||
}),
|
||||
Stream.debounce(Duration.millis(100)),
|
||||
);
|
||||
|
||||
yield* Stream.runForEach(debouncedKeybindingsEvents, () => revalidateAndEmitSafely).pipe(
|
||||
Effect.ignoreCause({ log: true }),
|
||||
Effect.forkIn(watcherScope),
|
||||
Effect.asVoid,
|
||||
);
|
||||
});
|
||||
|
||||
const start = Effect.gen(function* () {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { assert, it, vi } from "@effect/vitest";
|
||||
import type { OrchestrationReadModel } from "@t3tools/contracts";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Command from "effect/unstable/cli/Command";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
@@ -16,9 +17,11 @@ import { Open, type OpenShape } from "./open";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
import { Server, type ServerShape } from "./wsServer";
|
||||
import { ServerSettingsService } from "./serverSettings";
|
||||
|
||||
const start = vi.fn(() => undefined);
|
||||
const stop = vi.fn(() => undefined);
|
||||
const fixPath = vi.fn(() => undefined);
|
||||
let resolvedConfig: ServerConfigShape | null = null;
|
||||
const serverStart = Effect.acquireRelease(
|
||||
Effect.gen(function* () {
|
||||
@@ -34,7 +37,7 @@ const findAvailablePort = vi.fn((preferred: number) => Effect.succeed(preferred)
|
||||
const testLayer = Layer.mergeAll(
|
||||
Layer.succeed(CliConfig, {
|
||||
cwd: "/tmp/t3-test-workspace",
|
||||
fixPath: Effect.void,
|
||||
fixPath: Effect.sync(fixPath),
|
||||
resolveStaticDir: Effect.undefined,
|
||||
} satisfies CliConfigShape),
|
||||
Layer.succeed(NetService, {
|
||||
@@ -51,6 +54,7 @@ const testLayer = Layer.mergeAll(
|
||||
openBrowser: (_target: string) => Effect.void,
|
||||
openInEditor: () => Effect.void,
|
||||
} satisfies OpenShape),
|
||||
ServerSettingsService.layerTest(),
|
||||
AnalyticsService.layerTest,
|
||||
FetchHttpClient.layer,
|
||||
NodeServices.layer,
|
||||
@@ -78,6 +82,7 @@ beforeEach(() => {
|
||||
resolvedConfig = null;
|
||||
start.mockImplementation(() => undefined);
|
||||
stop.mockImplementation(() => undefined);
|
||||
fixPath.mockImplementation(() => undefined);
|
||||
findAvailablePort.mockImplementation((preferred: number) => Effect.succeed(preferred));
|
||||
});
|
||||
|
||||
@@ -151,6 +156,99 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
const openBootstrapFd = Effect.fn(function* (payload: Record<string, unknown>) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
||||
yield* fs.writeFileString(filePath, `${JSON.stringify(payload)}\n`);
|
||||
const { fd } = yield* fs.open(filePath, { flag: "r" });
|
||||
return fd;
|
||||
});
|
||||
|
||||
it.effect("recognizes bootstrap fd from environment config", () =>
|
||||
Effect.gen(function* () {
|
||||
const fd = yield* openBootstrapFd({ authToken: "bootstrap-token" });
|
||||
|
||||
yield* runCli([], {
|
||||
T3CODE_MODE: "web",
|
||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||
T3CODE_AUTH_TOKEN: "env-token",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
assert.equal(resolvedConfig?.authToken, "env-token");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses bootstrap envelope values as fallbacks when CLI and env are absent", () =>
|
||||
Effect.gen(function* () {
|
||||
const fd = yield* openBootstrapFd({
|
||||
mode: "desktop",
|
||||
port: 4888,
|
||||
host: "127.0.0.2",
|
||||
t3Home: "/tmp/t3-bootstrap-home",
|
||||
devUrl: "http://127.0.0.1:5173",
|
||||
noBrowser: true,
|
||||
authToken: "bootstrap-token",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
|
||||
yield* runCli([], {
|
||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "desktop");
|
||||
assert.equal(resolvedConfig?.port, 4888);
|
||||
assert.equal(resolvedConfig?.host, "127.0.0.2");
|
||||
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-bootstrap-home");
|
||||
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-bootstrap-home/dev");
|
||||
assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/");
|
||||
assert.equal(resolvedConfig?.noBrowser, true);
|
||||
assert.equal(resolvedConfig?.authToken, "bootstrap-token");
|
||||
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, false);
|
||||
assert.equal(resolvedConfig?.logWebSocketEvents, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("applies CLI then env precedence over bootstrap envelope values", () =>
|
||||
Effect.gen(function* () {
|
||||
const fd = yield* openBootstrapFd({
|
||||
mode: "desktop",
|
||||
port: 4888,
|
||||
host: "127.0.0.2",
|
||||
t3Home: "/tmp/t3-bootstrap-home",
|
||||
devUrl: "http://127.0.0.1:5173",
|
||||
noBrowser: false,
|
||||
authToken: "bootstrap-token",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
});
|
||||
|
||||
yield* runCli(["--port", "4999", "--host", "0.0.0.0", "--auth-token", "cli-token"], {
|
||||
T3CODE_MODE: "web",
|
||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||
T3CODE_HOME: "/tmp/t3-env-home",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
|
||||
T3CODE_LOG_WS_EVENTS: "true",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
assert.equal(resolvedConfig?.port, 4999);
|
||||
assert.equal(resolvedConfig?.host, "0.0.0.0");
|
||||
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-env-home");
|
||||
assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/");
|
||||
assert.equal(resolvedConfig?.noBrowser, true);
|
||||
assert.equal(resolvedConfig?.authToken, "cli-token");
|
||||
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, true);
|
||||
assert.equal(resolvedConfig?.logWebSocketEvents, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers --mode over T3CODE_MODE", () =>
|
||||
Effect.gen(function* () {
|
||||
findAvailablePort.mockImplementation((_preferred: number) => Effect.succeed(4666));
|
||||
@@ -233,6 +331,21 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("hydrates PATH before server startup", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli([]);
|
||||
|
||||
assert.equal(fixPath.mock.calls.length, 1);
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
const fixPathOrder = fixPath.mock.invocationCallOrder[0];
|
||||
const startOrder = start.mock.invocationCallOrder[0];
|
||||
if (typeof fixPathOrder !== "number" || typeof startOrder !== "number") {
|
||||
assert.fail("Expected fixPath and start to be called");
|
||||
}
|
||||
assert.isTrue(fixPathOrder < startOrder);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("records a startup heartbeat with thread/project counts", () =>
|
||||
Effect.gen(function* () {
|
||||
const recordTelemetry = vi.fn(
|
||||
@@ -272,7 +385,7 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
|
||||
it.effect("does not start server for invalid --mode values", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--mode", "invalid"]);
|
||||
yield* runCli(["--mode", "invalid"]).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
assert.equal(start.mock.calls.length, 0);
|
||||
assert.equal(stop.mock.calls.length, 0);
|
||||
@@ -290,7 +403,7 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
|
||||
it.effect("does not start server for out-of-range --port values", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--port", "70000"]);
|
||||
yield* runCli(["--port", "70000"]).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
// effect/unstable/cli renders help/errors for parse failures and returns success.
|
||||
assert.equal(start.mock.calls.length, 0);
|
||||
|
||||
+148
-35
@@ -22,17 +22,33 @@ import { Open } from "./open";
|
||||
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
|
||||
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
import { ProviderHealthLive } from "./provider/Layers/ProviderHealth";
|
||||
import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry";
|
||||
import { Server } from "./wsServer";
|
||||
import { ServerLoggerLive } from "./serverLogger";
|
||||
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
import { readBootstrapEnvelope } from "./bootstrap";
|
||||
import { ServerSettingsLive } from "./serverSettings";
|
||||
|
||||
export class StartupError extends Data.TaggedError("StartupError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
|
||||
|
||||
const BootstrapEnvelopeSchema = Schema.Struct({
|
||||
mode: Schema.optional(Schema.String),
|
||||
port: Schema.optional(PortSchema),
|
||||
host: Schema.optional(Schema.String),
|
||||
t3Home: Schema.optional(Schema.String),
|
||||
devUrl: Schema.optional(Schema.URLFromString),
|
||||
noBrowser: Schema.optional(Schema.Boolean),
|
||||
authToken: Schema.optional(Schema.String),
|
||||
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
|
||||
logWebSocketEvents: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
|
||||
interface CliInput {
|
||||
readonly mode: Option.Option<RuntimeMode>;
|
||||
readonly port: Option.Option<number>;
|
||||
@@ -41,6 +57,7 @@ interface CliInput {
|
||||
readonly devUrl: Option.Option<URL>;
|
||||
readonly noBrowser: Option.Option<boolean>;
|
||||
readonly authToken: Option.Option<string>;
|
||||
readonly bootstrapFd: Option.Option<number>;
|
||||
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
|
||||
readonly logWebSocketEvents: Option.Option<boolean>;
|
||||
}
|
||||
@@ -91,12 +108,8 @@ export class CliConfig extends ServiceMap.Service<CliConfig, CliConfigShape>()(
|
||||
const CliEnvConfig = Config.all({
|
||||
mode: Config.string("T3CODE_MODE").pipe(
|
||||
Config.option,
|
||||
Config.map(
|
||||
Option.match<RuntimeMode, string>({
|
||||
onNone: () => "web",
|
||||
onSome: (value) => (value === "desktop" ? "desktop" : "web"),
|
||||
}),
|
||||
),
|
||||
Config.map(Option.map((value) => (value === "desktop" ? "desktop" : "web"))),
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
@@ -110,6 +123,10 @@ const CliEnvConfig = Config.all({
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
@@ -123,6 +140,14 @@ const CliEnvConfig = Config.all({
|
||||
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
|
||||
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
|
||||
|
||||
const resolveOptionPrecedence = <Value>(
|
||||
...values: ReadonlyArray<Option.Option<Value>>
|
||||
): Option.Option<Value> => Option.firstSomeOf(values);
|
||||
|
||||
const isValidPort = (value: number): boolean => value >= 1 && value <= 65_535;
|
||||
const isRuntimeMode = (value: string): value is RuntimeMode =>
|
||||
value === "web" || value === "desktop";
|
||||
|
||||
const ServerConfigLive = (input: CliInput) =>
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
@@ -136,39 +161,115 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
),
|
||||
);
|
||||
|
||||
const mode = Option.getOrElse(input.mode, () => env.mode);
|
||||
const bootstrapFd = Option.getOrUndefined(input.bootstrapFd) ?? env.bootstrapFd;
|
||||
const bootstrapEnvelope =
|
||||
bootstrapFd !== undefined
|
||||
? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
|
||||
: Option.none();
|
||||
|
||||
const port = yield* Option.match(input.port, {
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
onNone: () => {
|
||||
if (env.port) {
|
||||
return Effect.succeed(env.port);
|
||||
}
|
||||
if (mode === "desktop") {
|
||||
return Effect.succeed(DEFAULT_PORT);
|
||||
}
|
||||
return findAvailablePort(DEFAULT_PORT);
|
||||
const mode: RuntimeMode = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
input.mode,
|
||||
Option.fromUndefinedOr(env.mode),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.filter(Option.fromUndefinedOr(bootstrap.mode), isRuntimeMode),
|
||||
),
|
||||
),
|
||||
() => "web",
|
||||
);
|
||||
const port = yield* Option.match(
|
||||
resolveOptionPrecedence(
|
||||
input.port,
|
||||
Option.fromUndefinedOr(env.port),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.filter(Option.fromUndefinedOr(bootstrap.port), isValidPort),
|
||||
),
|
||||
),
|
||||
{
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
onNone: () => {
|
||||
if (mode === "desktop") {
|
||||
return Effect.succeed(DEFAULT_PORT);
|
||||
}
|
||||
return findAvailablePort(DEFAULT_PORT);
|
||||
},
|
||||
},
|
||||
});
|
||||
);
|
||||
|
||||
const devUrl = Option.getOrElse(input.devUrl, () => env.devUrl);
|
||||
const baseDir = yield* resolveBaseDir(Option.getOrUndefined(input.t3Home) ?? env.t3Home);
|
||||
const devUrl = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
input.devUrl,
|
||||
Option.fromUndefinedOr(env.devUrl),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.devUrl),
|
||||
),
|
||||
),
|
||||
() => undefined,
|
||||
);
|
||||
const baseDir = yield* resolveBaseDir(
|
||||
Option.getOrUndefined(
|
||||
resolveOptionPrecedence(
|
||||
input.t3Home,
|
||||
Option.fromUndefinedOr(env.t3Home),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.t3Home),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
|
||||
const noBrowser = resolveBooleanFlag(input.noBrowser, env.noBrowser ?? mode === "desktop");
|
||||
const authToken = Option.getOrUndefined(input.authToken) ?? env.authToken;
|
||||
const noBrowser = resolveBooleanFlag(
|
||||
input.noBrowser,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.noBrowser),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.noBrowser),
|
||||
),
|
||||
),
|
||||
() => mode === "desktop",
|
||||
),
|
||||
);
|
||||
const authToken = resolveOptionPrecedence(
|
||||
input.authToken,
|
||||
Option.fromUndefinedOr(env.authToken),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.authToken),
|
||||
),
|
||||
);
|
||||
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
|
||||
input.autoBootstrapProjectFromCwd,
|
||||
env.autoBootstrapProjectFromCwd ?? mode === "web",
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
|
||||
),
|
||||
),
|
||||
() => mode === "web",
|
||||
),
|
||||
);
|
||||
const logWebSocketEvents = resolveBooleanFlag(
|
||||
input.logWebSocketEvents,
|
||||
env.logWebSocketEvents ?? Boolean(devUrl),
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.logWebSocketEvents),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.logWebSocketEvents),
|
||||
),
|
||||
),
|
||||
() => Boolean(devUrl),
|
||||
),
|
||||
);
|
||||
const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
|
||||
const host =
|
||||
Option.getOrUndefined(input.host) ??
|
||||
env.host ??
|
||||
(mode === "desktop" ? "127.0.0.1" : undefined);
|
||||
const host = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
input.host,
|
||||
Option.fromUndefinedOr(env.host),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
|
||||
),
|
||||
() => (mode === "desktop" ? "127.0.0.1" : undefined),
|
||||
);
|
||||
|
||||
const config: ServerConfigShape = {
|
||||
mode,
|
||||
@@ -180,7 +281,7 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
staticDir,
|
||||
devUrl,
|
||||
noBrowser,
|
||||
authToken,
|
||||
authToken: Option.getOrUndefined(authToken),
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
} satisfies ServerConfigShape;
|
||||
@@ -193,10 +294,11 @@ const LayerLive = (input: CliInput) =>
|
||||
Layer.empty.pipe(
|
||||
Layer.provideMerge(makeServerRuntimeServicesLayer()),
|
||||
Layer.provideMerge(makeServerProviderLayer()),
|
||||
Layer.provideMerge(ProviderHealthLive),
|
||||
Layer.provideMerge(ProviderRegistryLive),
|
||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||
Layer.provideMerge(ServerLoggerLive),
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(ServerConfigLive(input)),
|
||||
);
|
||||
|
||||
@@ -231,12 +333,10 @@ export const recordStartupHeartbeat = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
const makeServerProgram = (input: CliInput) =>
|
||||
const makeServerRuntimeProgram = (input: CliInput) =>
|
||||
Effect.gen(function* () {
|
||||
const cliConfig = yield* CliConfig;
|
||||
const { start, stopSignal } = yield* Server;
|
||||
const openDeps = yield* Open;
|
||||
yield* cliConfig.fixPath;
|
||||
|
||||
const config = yield* ServerConfig;
|
||||
|
||||
@@ -278,6 +378,13 @@ const makeServerProgram = (input: CliInput) =>
|
||||
return yield* stopSignal;
|
||||
}).pipe(Effect.provide(LayerLive(input)));
|
||||
|
||||
const makeServerProgram = (input: CliInput) =>
|
||||
Effect.gen(function* () {
|
||||
const cliConfig = yield* CliConfig;
|
||||
yield* cliConfig.fixPath;
|
||||
return yield* makeServerRuntimeProgram(input);
|
||||
});
|
||||
|
||||
/**
|
||||
* These flags mirrors the environment variables and the config shape.
|
||||
*/
|
||||
@@ -287,7 +394,7 @@ const modeFlag = Flag.choice("mode", ["web", "desktop"]).pipe(
|
||||
Flag.optional,
|
||||
);
|
||||
const portFlag = Flag.integer("port").pipe(
|
||||
Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
|
||||
Flag.withSchema(PortSchema),
|
||||
Flag.withDescription("Port for the HTTP/WebSocket server."),
|
||||
Flag.optional,
|
||||
);
|
||||
@@ -313,6 +420,11 @@ const authTokenFlag = Flag.string("auth-token").pipe(
|
||||
Flag.withAlias("token"),
|
||||
Flag.optional,
|
||||
);
|
||||
const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
|
||||
Flag.withSchema(Schema.Int),
|
||||
Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
|
||||
Flag.optional,
|
||||
);
|
||||
const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
|
||||
Flag.withDescription(
|
||||
"Create a project for the current working directory on startup when missing.",
|
||||
@@ -335,6 +447,7 @@ export const t3Cli = Command.make("t3", {
|
||||
devUrl: devUrlFlag,
|
||||
noBrowser: noBrowserFlag,
|
||||
authToken: authTokenFlag,
|
||||
bootstrapFd: bootstrapFdFlag,
|
||||
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
|
||||
logWebSocketEvents: logWebSocketEventsFlag,
|
||||
}).pipe(
|
||||
|
||||
@@ -40,6 +40,24 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodeInsidersLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode-insiders" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeInsidersLaunch, {
|
||||
command: "code-insiders",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodiumLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscodium" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodiumLaunch, {
|
||||
command: "codium",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const zedLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "zed" },
|
||||
"darwin",
|
||||
@@ -80,6 +98,24 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeInsidersLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode-insiders" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeInsidersLineAndColumn, {
|
||||
command: "code-insiders",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodiumLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscodium" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodiumLineAndColumn, {
|
||||
command: "codium",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const zedLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
|
||||
"darwin",
|
||||
@@ -220,13 +256,14 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
|
||||
|
||||
yield* fs.writeFileString(path.join(dir, "cursor.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
|
||||
const editors = resolveAvailableEditors("win32", {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, ["cursor", "file-manager"]);
|
||||
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -39,10 +39,8 @@ interface CommandAvailabilityOptions {
|
||||
|
||||
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
|
||||
|
||||
function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {
|
||||
return (
|
||||
(editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target)
|
||||
);
|
||||
function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean {
|
||||
return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target);
|
||||
}
|
||||
|
||||
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
|
||||
@@ -213,7 +211,7 @@ export const resolveEditorLaunch = Effect.fnUntraced(function* (
|
||||
}
|
||||
|
||||
if (editorDef.command) {
|
||||
return shouldUseGotoFlag(editorDef.id, input.cwd)
|
||||
return shouldUseGotoFlag(editorDef, input.cwd)
|
||||
? { command: editorDef.command, args: ["--goto", input.cwd] }
|
||||
: { command: editorDef.command, args: [input.cwd] };
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
@@ -282,7 +282,10 @@ describe("CheckpointReactor", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Test Project",
|
||||
workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -293,7 +296,10 @@ describe("CheckpointReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
|
||||
@@ -24,7 +24,11 @@ import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
|
||||
import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
|
||||
import { OrchestrationDispatchError } from "../Errors.ts";
|
||||
import { isGitRepository } from "../../git/isRepo.ts";
|
||||
import { isGitRepository } from "../../git/Utils.ts";
|
||||
import {
|
||||
inspectWorkspacePathState,
|
||||
resolveWorkspaceUnavailableReason,
|
||||
} from "../../workspacePaths.ts";
|
||||
|
||||
type ReactorInput =
|
||||
| {
|
||||
@@ -154,7 +158,12 @@ const make = Effect.gen(function* () {
|
||||
// a git repository.
|
||||
const resolveCheckpointCwd = Effect.fnUntraced(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null };
|
||||
readonly thread: {
|
||||
readonly projectId: ProjectId;
|
||||
readonly worktreePath: string | null;
|
||||
readonly effectiveCwd: string | null;
|
||||
readonly effectiveCwdState: string;
|
||||
};
|
||||
readonly projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>;
|
||||
readonly preferSessionRuntime: boolean;
|
||||
}): Effect.fn.Return<string | undefined> {
|
||||
@@ -175,7 +184,7 @@ const make = Effect.gen(function* () {
|
||||
onSome: (runtime) => runtime.cwd,
|
||||
}));
|
||||
|
||||
if (!cwd) {
|
||||
if (input.thread.effectiveCwdState !== "available" || !cwd) {
|
||||
return undefined;
|
||||
}
|
||||
if (!isGitWorkspace(cwd)) {
|
||||
@@ -583,6 +592,20 @@ const make = Effect.gen(function* () {
|
||||
}).pipe(Effect.catch(() => Effect.void));
|
||||
return;
|
||||
}
|
||||
const sessionWorkspaceState = yield* Effect.promise(() =>
|
||||
inspectWorkspacePathState(sessionRuntime.value.cwd),
|
||||
);
|
||||
if (sessionWorkspaceState !== "available") {
|
||||
yield* appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
detail:
|
||||
resolveWorkspaceUnavailableReason(sessionWorkspaceState) ??
|
||||
"Workspace folder is unavailable.",
|
||||
createdAt: now,
|
||||
}).pipe(Effect.catch(() => Effect.void));
|
||||
return;
|
||||
}
|
||||
if (!isGitWorkspace(sessionRuntime.value.cwd)) {
|
||||
yield* appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
@@ -766,7 +789,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const worker = yield* makeDrainableWorker(processInputSafely);
|
||||
|
||||
const start: CheckpointReactorShape["start"] = Effect.gen(function* () {
|
||||
const start: CheckpointReactorShape["start"] = Effect.fn("start")(function* () {
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
|
||||
if (
|
||||
|
||||
@@ -72,7 +72,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-1",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -83,7 +86,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -114,6 +120,73 @@ describe("OrchestrationEngine", () => {
|
||||
await system.dispose();
|
||||
});
|
||||
|
||||
it("archives and unarchives threads through orchestration commands", async () => {
|
||||
const system = await createOrchestrationSystem();
|
||||
const { engine } = system;
|
||||
const createdAt = now();
|
||||
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-archive-create"),
|
||||
projectId: asProjectId("project-archive"),
|
||||
title: "Project Archive",
|
||||
workspaceRoot: "/tmp/project-archive",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-archive-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-archive"),
|
||||
projectId: asProjectId("project-archive"),
|
||||
title: "Archive me",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-archive"),
|
||||
threadId: ThreadId.makeUnsafe("thread-archive"),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
(await system.run(engine.getReadModel())).threads.find(
|
||||
(thread) => thread.id === "thread-archive",
|
||||
)?.archivedAt,
|
||||
).not.toBeNull();
|
||||
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.unarchive",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-unarchive"),
|
||||
threadId: ThreadId.makeUnsafe("thread-archive"),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
(await system.run(engine.getReadModel())).threads.find(
|
||||
(thread) => thread.id === "thread-archive",
|
||||
)?.archivedAt,
|
||||
).toBeNull();
|
||||
|
||||
await system.dispose();
|
||||
});
|
||||
|
||||
it("replays append-only events from sequence", async () => {
|
||||
const system = await createOrchestrationSystem();
|
||||
const { engine } = system;
|
||||
@@ -126,7 +199,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-replay"),
|
||||
title: "Replay Project",
|
||||
workspaceRoot: "/tmp/project-replay",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -137,7 +213,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-replay"),
|
||||
projectId: asProjectId("project-replay"),
|
||||
title: "replay",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -178,7 +257,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-stream"),
|
||||
title: "Stream Project",
|
||||
workspaceRoot: "/tmp/project-stream",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -199,7 +281,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-stream"),
|
||||
projectId: asProjectId("project-stream"),
|
||||
title: "domain-stream",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -233,7 +318,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-turn-diff"),
|
||||
title: "Turn Diff Project",
|
||||
workspaceRoot: "/tmp/project-turn-diff",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -244,7 +332,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-turn-diff"),
|
||||
projectId: asProjectId("project-turn-diff"),
|
||||
title: "Turn diff thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -344,7 +435,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "Flaky Project",
|
||||
workspaceRoot: "/tmp/project-flaky",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -357,7 +451,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-flaky-fail"),
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "flaky-fail",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -374,7 +471,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-flaky-ok"),
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "flaky-ok",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -428,7 +528,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-atomic"),
|
||||
title: "Atomic Project",
|
||||
workspaceRoot: "/tmp/project-atomic",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -439,7 +542,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-atomic"),
|
||||
projectId: asProjectId("project-atomic"),
|
||||
title: "atomic",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -563,7 +669,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-sync"),
|
||||
title: "Sync Project",
|
||||
workspaceRoot: "/tmp/project-sync",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -574,7 +683,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-sync"),
|
||||
projectId: asProjectId("project-sync"),
|
||||
title: "sync-before",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -642,7 +754,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "Duplicate Project",
|
||||
workspaceRoot: "/tmp/project-duplicate",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -654,7 +769,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-duplicate"),
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "duplicate",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -671,7 +789,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-duplicate"),
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "duplicate",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
|
||||
@@ -24,25 +24,28 @@ describe("OrchestrationReactor", () => {
|
||||
Layer.effect(OrchestrationReactor, makeOrchestrationReactor).pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProviderRuntimeIngestionService, {
|
||||
start: Effect.sync(() => {
|
||||
start: () => {
|
||||
started.push("provider-runtime-ingestion");
|
||||
}),
|
||||
return Effect.void;
|
||||
},
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProviderCommandReactor, {
|
||||
start: Effect.sync(() => {
|
||||
start: () => {
|
||||
started.push("provider-command-reactor");
|
||||
}),
|
||||
return Effect.void;
|
||||
},
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(CheckpointReactor, {
|
||||
start: Effect.sync(() => {
|
||||
start: () => {
|
||||
started.push("checkpoint-reactor");
|
||||
}),
|
||||
return Effect.void;
|
||||
},
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
@@ -51,7 +54,7 @@ describe("OrchestrationReactor", () => {
|
||||
|
||||
const reactor = await runtime.runPromise(Effect.service(OrchestrationReactor));
|
||||
const scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reactor.start.pipe(Scope.provide(scope)));
|
||||
await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
|
||||
|
||||
expect(started).toEqual([
|
||||
"provider-runtime-ingestion",
|
||||
|
||||
@@ -13,10 +13,10 @@ export const makeOrchestrationReactor = Effect.gen(function* () {
|
||||
const providerCommandReactor = yield* ProviderCommandReactor;
|
||||
const checkpointReactor = yield* CheckpointReactor;
|
||||
|
||||
const start: OrchestrationReactorShape["start"] = Effect.gen(function* () {
|
||||
yield* providerRuntimeIngestion.start;
|
||||
yield* providerCommandReactor.start;
|
||||
yield* checkpointReactor.start;
|
||||
const start: OrchestrationReactorShape["start"] = Effect.fn("start")(function* () {
|
||||
yield* providerRuntimeIngestion.start();
|
||||
yield* providerCommandReactor.start();
|
||||
yield* checkpointReactor.start();
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -68,7 +68,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-1",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -89,7 +89,10 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Thread 1",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -337,7 +340,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-clear-attachments"),
|
||||
title: "Project Clear Attachments",
|
||||
workspaceRoot: "/tmp/project-clear-attachments",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -358,7 +361,10 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
threadId: ThreadId.makeUnsafe("thread-clear-attachments"),
|
||||
projectId: ProjectId.makeUnsafe("project-clear-attachments"),
|
||||
title: "Thread Clear Attachments",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -462,7 +468,7 @@ it.layer(
|
||||
projectId: ProjectId.makeUnsafe("project-overwrite"),
|
||||
title: "Project Overwrite",
|
||||
workspaceRoot: "/tmp/project-overwrite",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -483,7 +489,10 @@ it.layer(
|
||||
threadId: ThreadId.makeUnsafe("thread-overwrite"),
|
||||
projectId: ProjectId.makeUnsafe("project-overwrite"),
|
||||
title: "Thread Overwrite",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -607,7 +616,7 @@ it.layer(
|
||||
projectId: ProjectId.makeUnsafe("project-rollback"),
|
||||
title: "Project Rollback",
|
||||
workspaceRoot: "/tmp/project-rollback",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -628,7 +637,10 @@ it.layer(
|
||||
threadId: ThreadId.makeUnsafe("thread-rollback"),
|
||||
projectId: ProjectId.makeUnsafe("project-rollback"),
|
||||
title: "Thread Rollback",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -733,7 +745,7 @@ it.layer(
|
||||
projectId: ProjectId.makeUnsafe("project-revert-files"),
|
||||
title: "Project Revert Files",
|
||||
workspaceRoot: "/tmp/project-revert-files",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -754,7 +766,10 @@ it.layer(
|
||||
threadId,
|
||||
projectId: ProjectId.makeUnsafe("project-revert-files"),
|
||||
title: "Thread Revert Files",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -938,7 +953,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
|
||||
projectId: ProjectId.makeUnsafe("project-delete-files"),
|
||||
title: "Project Delete Files",
|
||||
workspaceRoot: "/tmp/project-delete-files",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -959,7 +974,10 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
|
||||
threadId,
|
||||
projectId: ProjectId.makeUnsafe("project-delete-files"),
|
||||
title: "Thread Delete Files",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -1098,7 +1116,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "Project A",
|
||||
workspaceRoot: "/tmp/project-a",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -1119,7 +1137,10 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
threadId: ThreadId.makeUnsafe("thread-a"),
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "Thread A",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -1222,7 +1243,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-empty"),
|
||||
title: "Project Empty",
|
||||
workspaceRoot: "/tmp/project-empty",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -1243,7 +1264,10 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
threadId: ThreadId.makeUnsafe("thread-empty"),
|
||||
projectId: ProjectId.makeUnsafe("project-empty"),
|
||||
title: "Thread Empty",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -1359,7 +1383,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-conflict"),
|
||||
title: "Project Conflict",
|
||||
workspaceRoot: "/tmp/project-conflict",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-02-26T13:00:00.000Z",
|
||||
updatedAt: "2026-02-26T13:00:00.000Z",
|
||||
@@ -1380,7 +1404,10 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
threadId: ThreadId.makeUnsafe("thread-conflict"),
|
||||
projectId: ProjectId.makeUnsafe("project-conflict"),
|
||||
title: "Thread Conflict",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -1500,7 +1527,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-revert"),
|
||||
title: "Project Revert",
|
||||
workspaceRoot: "/tmp/project-revert",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-02-26T12:00:00.000Z",
|
||||
updatedAt: "2026-02-26T12:00:00.000Z",
|
||||
@@ -1521,7 +1548,10 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
threadId: ThreadId.makeUnsafe("thread-revert"),
|
||||
projectId: ProjectId.makeUnsafe("project-revert"),
|
||||
title: "Thread Revert",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -1837,7 +1867,10 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-live"),
|
||||
title: "Live Project",
|
||||
workspaceRoot: "/tmp/project-live",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
|
||||
@@ -1872,7 +1905,10 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-scripts"),
|
||||
title: "Scripts Project",
|
||||
workspaceRoot: "/tmp/project-scripts",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
|
||||
@@ -1889,16 +1925,19 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
],
|
||||
defaultModel: "gpt-5",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5",
|
||||
},
|
||||
});
|
||||
|
||||
const projectRows = yield* sql<{
|
||||
readonly scriptsJson: string;
|
||||
readonly defaultModel: string;
|
||||
readonly defaultModelSelection: string;
|
||||
}>`
|
||||
SELECT
|
||||
scripts_json AS "scriptsJson",
|
||||
default_model AS "defaultModel"
|
||||
default_model_selection_json AS "defaultModelSelection"
|
||||
FROM projection_projects
|
||||
WHERE project_id = 'project-scripts'
|
||||
`;
|
||||
@@ -1906,7 +1945,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
||||
{
|
||||
scriptsJson:
|
||||
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
|
||||
defaultModel: "gpt-5",
|
||||
defaultModelSelection: '{"provider":"codex","model":"gpt-5"}',
|
||||
},
|
||||
]);
|
||||
}),
|
||||
|
||||
@@ -77,7 +77,7 @@ interface AttachmentSideEffects {
|
||||
readonly prunedThreadRelativePaths: Map<string, Set<string>>;
|
||||
}
|
||||
|
||||
const materializeAttachmentsForProjection = Effect.fn(
|
||||
const materializeAttachmentsForProjection = Effect.fn("materializeAttachmentsForProjection")(
|
||||
(input: { readonly attachments: ReadonlyArray<ChatAttachment> }) =>
|
||||
Effect.succeed(input.attachments.length === 0 ? [] : input.attachments),
|
||||
);
|
||||
@@ -238,131 +238,152 @@ function collectThreadAttachmentRelativePaths(
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
const runAttachmentSideEffects = Effect.fn(function* (sideEffects: AttachmentSideEffects) {
|
||||
const runAttachmentSideEffects = Effect.fn("runAttachmentSideEffects")(function* (
|
||||
sideEffects: AttachmentSideEffects,
|
||||
) {
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const fileSystem = yield* Effect.service(FileSystem.FileSystem);
|
||||
const path = yield* Effect.service(Path.Path);
|
||||
|
||||
const attachmentsRootDir = serverConfig.attachmentsDir;
|
||||
const readAttachmentRootEntries = fileSystem
|
||||
.readDirectory(attachmentsRootDir, { recursive: false })
|
||||
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
|
||||
|
||||
yield* Effect.forEach(
|
||||
sideEffects.deletedThreadIds,
|
||||
(threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||
if (!threadSegment) {
|
||||
yield* Effect.logWarning("skipping attachment cleanup for unsafe thread id", {
|
||||
threadId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const entries = yield* fileSystem
|
||||
.readDirectory(attachmentsRootDir, { recursive: false })
|
||||
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
|
||||
yield* Effect.forEach(
|
||||
entries,
|
||||
(entry) =>
|
||||
Effect.gen(function* () {
|
||||
const normalizedEntry = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
|
||||
if (normalizedEntry.length === 0 || normalizedEntry.includes("/")) {
|
||||
return;
|
||||
}
|
||||
const attachmentId = parseAttachmentIdFromRelativePath(normalizedEntry);
|
||||
if (!attachmentId) {
|
||||
return;
|
||||
}
|
||||
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
|
||||
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
|
||||
return;
|
||||
}
|
||||
yield* fileSystem.remove(path.join(attachmentsRootDir, normalizedEntry), {
|
||||
force: true,
|
||||
});
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
const removeDeletedThreadAttachmentEntry = Effect.fn("removeDeletedThreadAttachmentEntry")(
|
||||
function* (threadSegment: string, entry: string) {
|
||||
const normalizedEntry = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
|
||||
if (normalizedEntry.length === 0 || normalizedEntry.includes("/")) {
|
||||
return;
|
||||
}
|
||||
const attachmentId = parseAttachmentIdFromRelativePath(normalizedEntry);
|
||||
if (!attachmentId) {
|
||||
return;
|
||||
}
|
||||
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
|
||||
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
|
||||
return;
|
||||
}
|
||||
yield* fileSystem.remove(path.join(attachmentsRootDir, normalizedEntry), {
|
||||
force: true,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const deleteThreadAttachments = Effect.fn("deleteThreadAttachments")(function* (
|
||||
threadId: string,
|
||||
) {
|
||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||
if (!threadSegment) {
|
||||
yield* Effect.logWarning("skipping attachment cleanup for unsafe thread id", {
|
||||
threadId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const entries = yield* readAttachmentRootEntries;
|
||||
yield* Effect.forEach(
|
||||
entries,
|
||||
(entry) => removeDeletedThreadAttachmentEntry(threadSegment, entry),
|
||||
{
|
||||
concurrency: 1,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
const pruneThreadAttachmentEntry = Effect.fn("pruneThreadAttachmentEntry")(function* (
|
||||
threadSegment: string,
|
||||
keptThreadRelativePaths: Set<string>,
|
||||
entry: string,
|
||||
) {
|
||||
const relativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
|
||||
if (relativePath.length === 0 || relativePath.includes("/")) {
|
||||
return;
|
||||
}
|
||||
const attachmentId = parseAttachmentIdFromRelativePath(relativePath);
|
||||
if (!attachmentId) {
|
||||
return;
|
||||
}
|
||||
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
|
||||
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
|
||||
return;
|
||||
}
|
||||
|
||||
const absolutePath = path.join(attachmentsRootDir, relativePath);
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(absolutePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!keptThreadRelativePaths.has(relativePath)) {
|
||||
yield* fileSystem.remove(absolutePath, { force: true });
|
||||
}
|
||||
});
|
||||
|
||||
const pruneThreadAttachments = Effect.fn("pruneThreadAttachments")(function* (
|
||||
threadId: string,
|
||||
keptThreadRelativePaths: Set<string>,
|
||||
) {
|
||||
if (sideEffects.deletedThreadIds.has(threadId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||
if (!threadSegment) {
|
||||
yield* Effect.logWarning("skipping attachment prune for unsafe thread id", { threadId });
|
||||
return;
|
||||
}
|
||||
|
||||
const entries = yield* readAttachmentRootEntries;
|
||||
yield* Effect.forEach(
|
||||
entries,
|
||||
(entry) => pruneThreadAttachmentEntry(threadSegment, keptThreadRelativePaths, entry),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
});
|
||||
|
||||
yield* Effect.forEach(sideEffects.deletedThreadIds, deleteThreadAttachments, {
|
||||
concurrency: 1,
|
||||
});
|
||||
|
||||
yield* Effect.forEach(
|
||||
sideEffects.prunedThreadRelativePaths.entries(),
|
||||
([threadId, keptThreadRelativePaths]) => {
|
||||
if (sideEffects.deletedThreadIds.has(threadId)) {
|
||||
return Effect.void;
|
||||
}
|
||||
return Effect.gen(function* () {
|
||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||
if (!threadSegment) {
|
||||
yield* Effect.logWarning("skipping attachment prune for unsafe thread id", { threadId });
|
||||
return;
|
||||
}
|
||||
const entries = yield* fileSystem
|
||||
.readDirectory(attachmentsRootDir, { recursive: false })
|
||||
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
|
||||
yield* Effect.forEach(
|
||||
entries,
|
||||
(entry) =>
|
||||
Effect.gen(function* () {
|
||||
const relativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
|
||||
if (relativePath.length === 0 || relativePath.includes("/")) {
|
||||
return;
|
||||
}
|
||||
const attachmentId = parseAttachmentIdFromRelativePath(relativePath);
|
||||
if (!attachmentId) {
|
||||
return;
|
||||
}
|
||||
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
|
||||
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
|
||||
return;
|
||||
}
|
||||
|
||||
const absolutePath = path.join(attachmentsRootDir, relativePath);
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(absolutePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!keptThreadRelativePaths.has(relativePath)) {
|
||||
yield* fileSystem.remove(absolutePath, { force: true });
|
||||
}
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
});
|
||||
},
|
||||
([threadId, keptThreadRelativePaths]) =>
|
||||
pruneThreadAttachments(threadId, keptThreadRelativePaths),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
});
|
||||
|
||||
const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const projectionStateRepository = yield* ProjectionStateRepository;
|
||||
const projectionProjectRepository = yield* ProjectionProjectRepository;
|
||||
const projectionThreadRepository = yield* ProjectionThreadRepository;
|
||||
const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository;
|
||||
const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository;
|
||||
const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository;
|
||||
const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
|
||||
const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectionPipeline")(
|
||||
function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const projectionStateRepository = yield* ProjectionStateRepository;
|
||||
const projectionProjectRepository = yield* ProjectionProjectRepository;
|
||||
const projectionThreadRepository = yield* ProjectionThreadRepository;
|
||||
const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository;
|
||||
const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository;
|
||||
const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository;
|
||||
const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
|
||||
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
|
||||
const applyProjectsProjection: ProjectorDefinition["apply"] = (event, _attachmentSideEffects) =>
|
||||
Effect.gen(function* () {
|
||||
const applyProjectsProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyProjectsProjection",
|
||||
)(function* (event, _attachmentSideEffects) {
|
||||
switch (event.type) {
|
||||
case "project.created":
|
||||
yield* projectionProjectRepository.upsert({
|
||||
projectId: event.payload.projectId,
|
||||
title: event.payload.title,
|
||||
workspaceRoot: event.payload.workspaceRoot,
|
||||
defaultModel: event.payload.defaultModel,
|
||||
defaultModelSelection: event.payload.defaultModelSelection,
|
||||
scripts: event.payload.scripts,
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
@@ -383,8 +404,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
...(event.payload.workspaceRoot !== undefined
|
||||
? { workspaceRoot: event.payload.workspaceRoot }
|
||||
: {}),
|
||||
...(event.payload.defaultModel !== undefined
|
||||
? { defaultModel: event.payload.defaultModel }
|
||||
...(event.payload.defaultModelSelection !== undefined
|
||||
? { defaultModelSelection: event.payload.defaultModelSelection }
|
||||
: {}),
|
||||
...(event.payload.scripts !== undefined ? { scripts: event.payload.scripts } : {}),
|
||||
updatedAt: event.payload.updatedAt,
|
||||
@@ -412,15 +433,16 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadsProjection: ProjectorDefinition["apply"] = (event, attachmentSideEffects) =>
|
||||
Effect.gen(function* () {
|
||||
const applyThreadsProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyThreadsProjection",
|
||||
)(function* (event, attachmentSideEffects) {
|
||||
switch (event.type) {
|
||||
case "thread.created":
|
||||
yield* projectionThreadRepository.upsert({
|
||||
threadId: event.payload.threadId,
|
||||
projectId: event.payload.projectId,
|
||||
title: event.payload.title,
|
||||
model: event.payload.model,
|
||||
modelSelection: event.payload.modelSelection,
|
||||
runtimeMode: event.payload.runtimeMode,
|
||||
interactionMode: event.payload.interactionMode,
|
||||
branch: event.payload.branch,
|
||||
@@ -428,10 +450,41 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
latestTurnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
});
|
||||
return;
|
||||
|
||||
case "thread.archived": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
archivedAt: event.payload.archivedAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.unarchived": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
archivedAt: null,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.meta-updated": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
@@ -442,7 +495,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
|
||||
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
|
||||
...(event.payload.modelSelection !== undefined
|
||||
? { modelSelection: event.payload.modelSelection }
|
||||
: {}),
|
||||
...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),
|
||||
...(event.payload.worktreePath !== undefined
|
||||
? { worktreePath: event.payload.worktreePath }
|
||||
@@ -564,11 +619,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadMessagesProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const applyThreadMessagesProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyThreadMessagesProjection",
|
||||
)(function* (event, attachmentSideEffects) {
|
||||
switch (event.type) {
|
||||
case "thread.message-sent": {
|
||||
const existingRows = yield* projectionThreadMessageRepository.listByThreadId({
|
||||
@@ -641,11 +694,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadProposedPlansProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const applyThreadProposedPlansProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyThreadProposedPlansProjection",
|
||||
)(function* (event, _attachmentSideEffects) {
|
||||
switch (event.type) {
|
||||
case "thread.proposed-plan-upserted":
|
||||
yield* projectionThreadProposedPlanRepository.upsert({
|
||||
@@ -694,11 +745,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyThreadActivitiesProjection",
|
||||
)(function* (event, _attachmentSideEffects) {
|
||||
switch (event.type) {
|
||||
case "thread.activity-appended":
|
||||
yield* projectionThreadActivityRepository.upsert({
|
||||
@@ -748,11 +797,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyThreadSessionsProjection",
|
||||
)(function* (event, _attachmentSideEffects) {
|
||||
if (event.type !== "thread.session-set") {
|
||||
return;
|
||||
}
|
||||
@@ -767,11 +814,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyThreadTurnsProjection",
|
||||
)(function* (event, _attachmentSideEffects) {
|
||||
switch (event.type) {
|
||||
case "thread.turn-start-requested": {
|
||||
yield* projectionTurnRepository.replacePendingTurnStart({
|
||||
@@ -1025,13 +1070,11 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void;
|
||||
const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void;
|
||||
|
||||
const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyPendingApprovalsProjection",
|
||||
)(function* (event, _attachmentSideEffects) {
|
||||
switch (event.type) {
|
||||
case "thread.activity-appended": {
|
||||
const requestId =
|
||||
@@ -1117,47 +1160,49 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const projectors: ReadonlyArray<ProjectorDefinition> = [
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.projects,
|
||||
apply: applyProjectsProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
|
||||
apply: applyThreadMessagesProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,
|
||||
apply: applyThreadProposedPlansProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
|
||||
apply: applyThreadActivitiesProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
|
||||
apply: applyThreadSessionsProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadTurns,
|
||||
apply: applyThreadTurnsProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.checkpoints,
|
||||
apply: applyCheckpointsProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.pendingApprovals,
|
||||
apply: applyPendingApprovalsProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threads,
|
||||
apply: applyThreadsProjection,
|
||||
},
|
||||
];
|
||||
const projectors: ReadonlyArray<ProjectorDefinition> = [
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.projects,
|
||||
apply: applyProjectsProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
|
||||
apply: applyThreadMessagesProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,
|
||||
apply: applyThreadProposedPlansProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
|
||||
apply: applyThreadActivitiesProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
|
||||
apply: applyThreadSessionsProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadTurns,
|
||||
apply: applyThreadTurnsProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.checkpoints,
|
||||
apply: applyCheckpointsProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.pendingApprovals,
|
||||
apply: applyPendingApprovalsProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threads,
|
||||
apply: applyThreadsProjection,
|
||||
},
|
||||
];
|
||||
|
||||
const runProjectorForEvent = (projector: ProjectorDefinition, event: OrchestrationEvent) =>
|
||||
Effect.gen(function* () {
|
||||
const runProjectorForEvent = Effect.fn("runProjectorForEvent")(function* (
|
||||
projector: ProjectorDefinition,
|
||||
event: OrchestrationEvent,
|
||||
) {
|
||||
const attachmentSideEffects: AttachmentSideEffects = {
|
||||
deletedThreadIds: new Set<string>(),
|
||||
prunedThreadRelativePaths: new Map<string, Set<string>>(),
|
||||
@@ -1187,63 +1232,64 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
);
|
||||
});
|
||||
|
||||
const bootstrapProjector = (projector: ProjectorDefinition) =>
|
||||
projectionStateRepository
|
||||
.getByProjector({
|
||||
projector: projector.name,
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap((stateRow) =>
|
||||
Stream.runForEach(
|
||||
eventStore.readFromSequence(
|
||||
Option.isSome(stateRow) ? stateRow.value.lastAppliedSequence : 0,
|
||||
const bootstrapProjector = (projector: ProjectorDefinition) =>
|
||||
projectionStateRepository
|
||||
.getByProjector({
|
||||
projector: projector.name,
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap((stateRow) =>
|
||||
Stream.runForEach(
|
||||
eventStore.readFromSequence(
|
||||
Option.isSome(stateRow) ? stateRow.value.lastAppliedSequence : 0,
|
||||
),
|
||||
(event) => runProjectorForEvent(projector, event),
|
||||
),
|
||||
(event) => runProjectorForEvent(projector, event),
|
||||
),
|
||||
);
|
||||
|
||||
const projectEvent: OrchestrationProjectionPipelineShape["projectEvent"] = (event) =>
|
||||
Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), {
|
||||
concurrency: 1,
|
||||
}).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.provideService(ServerConfig, serverConfig),
|
||||
Effect.asVoid,
|
||||
Effect.catchTag("SqlError", (sqlError) =>
|
||||
Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)),
|
||||
),
|
||||
);
|
||||
|
||||
const projectEvent: OrchestrationProjectionPipelineShape["projectEvent"] = (event) =>
|
||||
Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), {
|
||||
concurrency: 1,
|
||||
}).pipe(
|
||||
const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.forEach(
|
||||
projectors,
|
||||
bootstrapProjector,
|
||||
{ concurrency: 1 },
|
||||
).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.provideService(ServerConfig, serverConfig),
|
||||
Effect.asVoid,
|
||||
Effect.tap(() =>
|
||||
Effect.log("orchestration projection pipeline bootstrapped").pipe(
|
||||
Effect.annotateLogs({ projectors: projectors.length }),
|
||||
),
|
||||
),
|
||||
Effect.catchTag("SqlError", (sqlError) =>
|
||||
Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)),
|
||||
Effect.fail(toPersistenceSqlError("ProjectionPipeline.bootstrap:query")(sqlError)),
|
||||
),
|
||||
);
|
||||
|
||||
const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.forEach(
|
||||
projectors,
|
||||
bootstrapProjector,
|
||||
{ concurrency: 1 },
|
||||
).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.provideService(ServerConfig, serverConfig),
|
||||
Effect.asVoid,
|
||||
Effect.tap(() =>
|
||||
Effect.log("orchestration projection pipeline bootstrapped").pipe(
|
||||
Effect.annotateLogs({ projectors: projectors.length }),
|
||||
),
|
||||
),
|
||||
Effect.catchTag("SqlError", (sqlError) =>
|
||||
Effect.fail(toPersistenceSqlError("ProjectionPipeline.bootstrap:query")(sqlError)),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
bootstrap,
|
||||
projectEvent,
|
||||
} satisfies OrchestrationProjectionPipelineShape;
|
||||
});
|
||||
return {
|
||||
bootstrap,
|
||||
projectEvent,
|
||||
} satisfies OrchestrationProjectionPipelineShape;
|
||||
},
|
||||
);
|
||||
|
||||
export const OrchestrationProjectionPipelineLive = Layer.effect(
|
||||
OrchestrationProjectionPipeline,
|
||||
makeOrchestrationProjectionPipeline,
|
||||
makeOrchestrationProjectionPipeline(),
|
||||
).pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(ProjectionProjectRepositoryLive),
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { CheckpointRef, EventId, MessageId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
@@ -23,6 +27,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const workspaceRoot = fs.mkdtempSync(path.join(os.tmpdir(), "projection-snapshot-"));
|
||||
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
yield* sql`DELETE FROM projection_state`;
|
||||
@@ -34,7 +39,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
@@ -43,8 +48,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
VALUES (
|
||||
'project-1',
|
||||
'Project 1',
|
||||
'/tmp/project-1',
|
||||
'gpt-5-codex',
|
||||
${workspaceRoot},
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
|
||||
'2026-02-24T00:00:00.000Z',
|
||||
'2026-02-24T00:00:01.000Z',
|
||||
@@ -57,7 +62,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model,
|
||||
model_selection_json,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
@@ -69,7 +74,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'thread-1',
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'gpt-5-codex',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-1',
|
||||
@@ -233,8 +238,12 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
{
|
||||
id: asProjectId("project-1"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-1",
|
||||
defaultModel: "gpt-5-codex",
|
||||
workspaceRoot,
|
||||
workspaceState: "available",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
scripts: [
|
||||
{
|
||||
id: "script-1",
|
||||
@@ -254,11 +263,17 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread 1",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
effectiveCwd: workspaceRoot,
|
||||
effectiveCwdSource: "project",
|
||||
effectiveCwdState: "available",
|
||||
latestTurn: {
|
||||
turnId: asTurnId("turn-1"),
|
||||
state: "completed",
|
||||
@@ -273,6 +288,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
},
|
||||
createdAt: "2026-02-24T00:00:02.000Z",
|
||||
updatedAt: "2026-02-24T00:00:03.000Z",
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [
|
||||
{
|
||||
|
||||
@@ -17,6 +17,8 @@ import {
|
||||
type OrchestrationSession,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
ModelSelection,
|
||||
type WorkspaceAvailabilityState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
@@ -41,10 +43,12 @@ import {
|
||||
ProjectionSnapshotQuery,
|
||||
type ProjectionSnapshotQueryShape,
|
||||
} from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import { inspectWorkspacePathState } from "../../workspacePaths.ts";
|
||||
|
||||
const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
|
||||
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
|
||||
Struct.assign({
|
||||
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
|
||||
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
||||
}),
|
||||
);
|
||||
@@ -55,7 +59,11 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
|
||||
const ProjectionThreadDbRowSchema = ProjectionThread;
|
||||
const ProjectionThreadDbRowSchema = ProjectionThread.mapFields(
|
||||
Struct.assign({
|
||||
modelSelection: Schema.fromJsonString(ModelSelection),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||
Struct.assign({
|
||||
payload: Schema.fromJsonString(Schema.Unknown),
|
||||
@@ -129,6 +137,12 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st
|
||||
: toPersistenceSqlError(sqlOperation)(cause);
|
||||
}
|
||||
|
||||
type EffectiveWorkspaceMetadata = {
|
||||
readonly effectiveCwd: string | null;
|
||||
readonly effectiveCwdSource: "project" | "worktree" | null;
|
||||
readonly effectiveCwdState: WorkspaceAvailabilityState;
|
||||
};
|
||||
|
||||
const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
@@ -141,7 +155,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_model AS "defaultModel",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -160,7 +174,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
model,
|
||||
model_selection_json AS "modelSelection",
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
@@ -168,6 +182,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
latest_turn_id AS "latestTurnId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
ORDER BY created_at ASC, thread_id ASC
|
||||
@@ -531,36 +546,84 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const projects: Array<OrchestrationProject> = projectRows.map((row) => ({
|
||||
const workspaceRoots = new Set(projectRows.map((row) => row.workspaceRoot));
|
||||
const worktreePaths = new Set(
|
||||
threadRows.flatMap((row) => (row.worktreePath ? [row.worktreePath] : [])),
|
||||
);
|
||||
const workspaceStateEntries = yield* Effect.promise(() =>
|
||||
Promise.all(
|
||||
[...new Set([...workspaceRoots, ...worktreePaths])].map(async (workspacePath) => {
|
||||
const workspaceState = await inspectWorkspacePathState(workspacePath);
|
||||
return [workspacePath, workspaceState] as const;
|
||||
}),
|
||||
),
|
||||
);
|
||||
const workspaceStates = new Map(workspaceStateEntries);
|
||||
const projectRowsById = new Map(projectRows.map((row) => [row.projectId, row] as const));
|
||||
const projectWorkspaceStateById = new Map(
|
||||
projectRows.map((row) => [
|
||||
row.projectId,
|
||||
workspaceStates.get(row.workspaceRoot) ??
|
||||
("inaccessible" satisfies WorkspaceAvailabilityState),
|
||||
]),
|
||||
);
|
||||
|
||||
const projects: ReadonlyArray<OrchestrationProject> = projectRows.map((row) => ({
|
||||
id: row.projectId,
|
||||
title: row.title,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
defaultModel: row.defaultModel,
|
||||
workspaceState:
|
||||
projectWorkspaceStateById.get(row.projectId) ??
|
||||
("inaccessible" satisfies WorkspaceAvailabilityState),
|
||||
defaultModelSelection: row.defaultModelSelection,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
}));
|
||||
|
||||
const threads: Array<OrchestrationThread> = threadRows.map((row) => ({
|
||||
id: row.threadId,
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
model: row.model,
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: messagesByThread.get(row.threadId) ?? [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
activities: activitiesByThread.get(row.threadId) ?? [],
|
||||
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
|
||||
session: sessionsByThread.get(row.threadId) ?? null,
|
||||
}));
|
||||
const threads: ReadonlyArray<OrchestrationThread> = threadRows.map((row) => {
|
||||
const effectiveWorkspace: EffectiveWorkspaceMetadata =
|
||||
row.worktreePath !== null
|
||||
? {
|
||||
effectiveCwd: row.worktreePath,
|
||||
effectiveCwdSource: "worktree",
|
||||
effectiveCwdState:
|
||||
workspaceStates.get(row.worktreePath) ??
|
||||
("inaccessible" satisfies WorkspaceAvailabilityState),
|
||||
}
|
||||
: {
|
||||
effectiveCwd: projectRowsById.get(row.projectId)?.workspaceRoot ?? null,
|
||||
effectiveCwdSource: projectRowsById.has(row.projectId) ? "project" : null,
|
||||
effectiveCwdState:
|
||||
projectWorkspaceStateById.get(row.projectId) ??
|
||||
("inaccessible" satisfies WorkspaceAvailabilityState),
|
||||
};
|
||||
|
||||
return {
|
||||
id: row.threadId,
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
modelSelection: row.modelSelection,
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
effectiveCwd: effectiveWorkspace.effectiveCwd,
|
||||
effectiveCwdSource: effectiveWorkspace.effectiveCwdSource,
|
||||
effectiveCwdState: effectiveWorkspace.effectiveCwdState,
|
||||
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) ?? [],
|
||||
activities: activitiesByThread.get(row.threadId) ?? [],
|
||||
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
|
||||
session: sessionsByThread.get(row.threadId) ?? null,
|
||||
};
|
||||
});
|
||||
|
||||
const snapshot = {
|
||||
snapshotSequence: computeSnapshotSequence(stateRows),
|
||||
|
||||
@@ -2,7 +2,7 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import type { ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import type { ModelSelection, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
@@ -34,6 +34,7 @@ import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asApprovalRequestId = (value: string): ApprovalRequestId =>
|
||||
@@ -44,6 +45,8 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
const deriveServerPathsSync = (baseDir: string, devUrl: URL | undefined) =>
|
||||
Effect.runSync(deriveServerPaths(baseDir, devUrl).pipe(Effect.provide(NodeServices.layer)));
|
||||
|
||||
fs.mkdirSync("/tmp/provider-project", { recursive: true });
|
||||
|
||||
async function waitFor(
|
||||
predicate: () => boolean | Promise<boolean>,
|
||||
timeoutMs = 2000,
|
||||
@@ -93,37 +96,27 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
async function createHarness(input?: {
|
||||
readonly baseDir?: string;
|
||||
readonly threadModel?: string;
|
||||
readonly threadModelSelection?: ModelSelection;
|
||||
readonly sessionModelSwitch?: "unsupported" | "in-session";
|
||||
}) {
|
||||
const now = new Date().toISOString();
|
||||
const baseDir = input?.baseDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
|
||||
createdBaseDirs.add(baseDir);
|
||||
const { stateDir } = deriveServerPathsSync(baseDir, undefined);
|
||||
createdStateDirs.add(stateDir);
|
||||
const threadModel = input?.threadModel ?? "gpt-5-codex";
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
let nextSessionIndex = 1;
|
||||
const runtimeSessions: Array<ProviderSession> = [];
|
||||
const modelSelection = input?.threadModelSelection ?? {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
};
|
||||
const startSession = vi.fn((_: unknown, input: unknown) => {
|
||||
const sessionIndex = nextSessionIndex++;
|
||||
const provider =
|
||||
typeof input === "object" &&
|
||||
input !== null &&
|
||||
"provider" in input &&
|
||||
(input.provider === "codex" || input.provider === "claudeAgent")
|
||||
? input.provider
|
||||
: "codex";
|
||||
const resumeCursor =
|
||||
typeof input === "object" && input !== null && "resumeCursor" in input
|
||||
? input.resumeCursor
|
||||
: undefined;
|
||||
const model =
|
||||
typeof input === "object" &&
|
||||
input !== null &&
|
||||
"model" in input &&
|
||||
typeof input.model === "string"
|
||||
? input.model
|
||||
: undefined;
|
||||
const threadId =
|
||||
typeof input === "object" &&
|
||||
input !== null &&
|
||||
@@ -132,7 +125,7 @@ describe("ProviderCommandReactor", () => {
|
||||
? ThreadId.makeUnsafe(input.threadId)
|
||||
: ThreadId.makeUnsafe(`thread-${sessionIndex}`);
|
||||
const session: ProviderSession = {
|
||||
provider,
|
||||
provider: modelSelection.provider,
|
||||
status: "ready" as const,
|
||||
runtimeMode:
|
||||
typeof input === "object" &&
|
||||
@@ -141,7 +134,7 @@ describe("ProviderCommandReactor", () => {
|
||||
(input.runtimeMode === "approval-required" || input.runtimeMode === "full-access")
|
||||
? input.runtimeMode
|
||||
: "full-access",
|
||||
...(model !== undefined ? { model } : {}),
|
||||
...(modelSelection.model !== undefined ? { model: modelSelection.model } : {}),
|
||||
threadId,
|
||||
resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` },
|
||||
createdAt: now,
|
||||
@@ -185,7 +178,7 @@ describe("ProviderCommandReactor", () => {
|
||||
: "renamed-branch",
|
||||
}),
|
||||
);
|
||||
const generateBranchName = vi.fn(() =>
|
||||
const generateBranchName = vi.fn<TextGenerationShape["generateBranchName"]>((_) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation: "generateBranchName",
|
||||
@@ -193,6 +186,14 @@ describe("ProviderCommandReactor", () => {
|
||||
}),
|
||||
),
|
||||
);
|
||||
const generateThreadTitle = vi.fn<TextGenerationShape["generateThreadTitle"]>((_) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation: "generateThreadTitle",
|
||||
detail: "disabled in test harness",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
|
||||
const service: ProviderServiceShape = {
|
||||
@@ -203,9 +204,9 @@ describe("ProviderCommandReactor", () => {
|
||||
respondToUserInput: respondToUserInput as ProviderServiceShape["respondToUserInput"],
|
||||
stopSession: stopSession as ProviderServiceShape["stopSession"],
|
||||
listSessions: () => Effect.succeed(runtimeSessions),
|
||||
getCapabilities: (provider) =>
|
||||
getCapabilities: (_provider) =>
|
||||
Effect.succeed({
|
||||
sessionModelSwitch: provider === "codex" ? "in-session" : "in-session",
|
||||
sessionModelSwitch: input?.sessionModelSwitch ?? "in-session",
|
||||
}),
|
||||
rollbackConversation: () => unsupported(),
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
@@ -222,8 +223,12 @@ describe("ProviderCommandReactor", () => {
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, service)),
|
||||
Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(TextGeneration, { generateBranchName } as unknown as TextGenerationShape),
|
||||
Layer.mock(TextGeneration, {
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
@@ -232,7 +237,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(
|
||||
@@ -242,7 +247,7 @@ describe("ProviderCommandReactor", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Provider Project",
|
||||
workspaceRoot: "/tmp/provider-project",
|
||||
defaultModel: threadModel,
|
||||
defaultModelSelection: modelSelection,
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
@@ -253,7 +258,7 @@ describe("ProviderCommandReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: threadModel,
|
||||
modelSelection: modelSelection,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -272,6 +277,7 @@ describe("ProviderCommandReactor", () => {
|
||||
stopSession,
|
||||
renameBranch,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
stateDir,
|
||||
drain,
|
||||
};
|
||||
@@ -303,7 +309,10 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(harness.startSession.mock.calls[0]?.[0]).toEqual(ThreadId.makeUnsafe("thread-1"));
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
cwd: "/tmp/provider-project",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
|
||||
@@ -313,6 +322,199 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
|
||||
it("generates a thread title on the first turn", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
const seededTitle = "Please investigate reconnect failures after restar...";
|
||||
harness.generateThreadTitle.mockReturnValue(Effect.succeed({ title: "Generated title" }));
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-title-seed"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
title: seededTitle,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-title"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-title"),
|
||||
role: "user",
|
||||
text: "Please investigate reconnect failures after restarting the session.",
|
||||
attachments: [],
|
||||
},
|
||||
titleSeed: seededTitle,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1);
|
||||
expect(harness.generateThreadTitle.mock.calls[0]?.[0]).toMatchObject({
|
||||
message: "Please investigate reconnect failures after restarting the session.",
|
||||
});
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
return (
|
||||
readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"))?.title ===
|
||||
"Generated title"
|
||||
);
|
||||
});
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.title).toBe("Generated title");
|
||||
});
|
||||
|
||||
it("does not overwrite an existing custom thread title on the first turn", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
const seededTitle = "Please investigate reconnect failures after restar...";
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-title-custom"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
title: "Keep this custom title",
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-title-preserve"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-title-preserve"),
|
||||
role: "user",
|
||||
text: "Please investigate reconnect failures after restarting the session.",
|
||||
attachments: [],
|
||||
},
|
||||
titleSeed: seededTitle,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
expect(harness.generateThreadTitle).not.toHaveBeenCalled();
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.title).toBe("Keep this custom title");
|
||||
});
|
||||
|
||||
it("matches the client-seeded title even when the outgoing prompt is reformatted", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
const seededTitle = "Fix reconnect spinner on resume";
|
||||
harness.generateThreadTitle.mockReturnValue(
|
||||
Effect.succeed({
|
||||
title: "Reconnect spinner resume bug",
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-title-formatted-seed"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
title: seededTitle,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-title-formatted"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-title-formatted"),
|
||||
role: "user",
|
||||
text: "[effort:high]\\n\\nFix reconnect spinner on resume",
|
||||
attachments: [],
|
||||
},
|
||||
titleSeed: seededTitle,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1);
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
return (
|
||||
readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"))?.title ===
|
||||
"Reconnect spinner resume bug"
|
||||
);
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.title).toBe("Reconnect spinner resume bug");
|
||||
});
|
||||
|
||||
it("generates a worktree branch name for the first turn", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-branch"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
branch: "t3code/1234abcd",
|
||||
worktreePath: "/tmp/provider-project-worktree",
|
||||
}),
|
||||
);
|
||||
|
||||
harness.generateBranchName.mockImplementation((input: unknown) =>
|
||||
Effect.succeed({
|
||||
branch:
|
||||
typeof input === "object" &&
|
||||
input !== null &&
|
||||
"modelSelection" in input &&
|
||||
typeof input.modelSelection === "object" &&
|
||||
input.modelSelection !== null &&
|
||||
"model" in input.modelSelection &&
|
||||
typeof input.modelSelection.model === "string"
|
||||
? `feature/${input.modelSelection.model}`
|
||||
: "feature/generated",
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-branch-model"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-branch-model"),
|
||||
role: "user",
|
||||
text: "Add a safer reconnect backoff.",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||
expect(harness.generateBranchName.mock.calls[0]?.[0]).toMatchObject({
|
||||
message: "Add a safer reconnect backoff.",
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards codex model options through session start and turn send", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -328,10 +530,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "hello fast mode",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -345,9 +547,10 @@ describe("ProviderCommandReactor", () => {
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -355,9 +558,10 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -366,7 +570,9 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
|
||||
it("forwards claude effort options through session start and turn send", async () => {
|
||||
const harness = await createHarness({ threadModel: "claude-sonnet-4-6" });
|
||||
const harness = await createHarness({
|
||||
threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
|
||||
});
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
@@ -380,10 +586,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "hello with effort",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
@@ -396,19 +602,20 @@ describe("ProviderCommandReactor", () => {
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
@@ -416,7 +623,9 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
|
||||
it("forwards claude fast mode options through session start and turn send", async () => {
|
||||
const harness = await createHarness({ threadModel: "claude-opus-4-6" });
|
||||
const harness = await createHarness({
|
||||
threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
|
||||
});
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
@@ -430,10 +639,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "hello with fast mode",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
@@ -446,19 +655,20 @@ describe("ProviderCommandReactor", () => {
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
model: "claude-opus-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
@@ -504,7 +714,9 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
|
||||
it("rejects a first turn when requested provider conflicts with the thread model", async () => {
|
||||
const harness = await createHarness();
|
||||
const harness = await createHarness({
|
||||
threadModelSelection: { provider: "codex", model: "gpt-5-codex" },
|
||||
});
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
@@ -518,7 +730,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "hello claude",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
@@ -552,49 +767,53 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a turn when the requested model belongs to a different provider", async () => {
|
||||
const harness = await createHarness();
|
||||
it("preserves the active session model when in-session model switching is unsupported", async () => {
|
||||
const harness = await createHarness({ sessionModelSwitch: "unsupported" });
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-model-provider-mismatch"),
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-model-provider-mismatch"),
|
||||
messageId: asMessageId("user-message-unsupported-1"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
model: "claude-sonnet-4-6",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
false
|
||||
);
|
||||
});
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
expect(harness.startSession).not.toHaveBeenCalled();
|
||||
expect(harness.sendTurn).not.toHaveBeenCalled();
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-unsupported-2"),
|
||||
role: "user",
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(
|
||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
).toMatchObject({
|
||||
payload: {
|
||||
detail: expect.stringContaining("does not belong to provider 'codex'"),
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||
|
||||
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -646,7 +865,9 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
|
||||
it("restarts claude sessions when claude effort changes", async () => {
|
||||
const harness = await createHarness({ threadModel: "claude-sonnet-4-6" });
|
||||
const harness = await createHarness({
|
||||
threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
|
||||
});
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
@@ -660,10 +881,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "first claude turn",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "medium",
|
||||
},
|
||||
},
|
||||
@@ -687,10 +908,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "second claude turn",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
@@ -703,10 +924,11 @@ describe("ProviderCommandReactor", () => {
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 2);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
|
||||
provider: "claudeAgent",
|
||||
resumeCursor: { opaque: "resume-1" },
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
@@ -800,6 +1022,51 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
|
||||
it("does not inject derived model options when restarting claude on runtime mode changes", async () => {
|
||||
const harness = await createHarness({
|
||||
threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
|
||||
});
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-runtime-mode-claude"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-claude-no-options"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects provider changes after a thread is already bound to a session provider", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -835,7 +1102,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
|
||||
@@ -1,19 +1,17 @@
|
||||
import {
|
||||
type ChatAttachment,
|
||||
CommandId,
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
EventId,
|
||||
type ModelSelection,
|
||||
type OrchestrationEvent,
|
||||
type ProviderModelOptions,
|
||||
ProviderKind,
|
||||
type ProviderStartOptions,
|
||||
type OrchestrationSession,
|
||||
ThreadId,
|
||||
type ProviderSession,
|
||||
type RuntimeMode,
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cache, Cause, Duration, Effect, Layer, Option, Schema, Stream } from "effect";
|
||||
import { Cache, Cause, Duration, Effect, Equal, Layer, Option, Schema, Stream } from "effect";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
|
||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
@@ -26,7 +24,8 @@ import {
|
||||
ProviderCommandReactor,
|
||||
type ProviderCommandReactorShape,
|
||||
} from "../Services/ProviderCommandReactor.ts";
|
||||
import { inferProviderForModel } from "@t3tools/shared/model";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { assertWorkspaceDirectory } from "../../workspacePaths.ts";
|
||||
|
||||
type ProviderIntentEvent = Extract<
|
||||
OrchestrationEvent,
|
||||
@@ -75,11 +74,19 @@ const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
|
||||
const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
|
||||
const DEFAULT_THREAD_TITLE = "New thread";
|
||||
|
||||
const sameModelOptions = (
|
||||
left: ProviderModelOptions | undefined,
|
||||
right: ProviderModelOptions | undefined,
|
||||
): boolean => JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
|
||||
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);
|
||||
@@ -144,6 +151,7 @@ const make = Effect.gen(function* () {
|
||||
const providerService = yield* ProviderService;
|
||||
const git = yield* GitCore;
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
const handledTurnStartKeys = yield* Cache.make<string, true>({
|
||||
capacity: HANDLED_TURN_START_KEY_MAX,
|
||||
timeToLive: HANDLED_TURN_START_KEY_TTL,
|
||||
@@ -157,8 +165,7 @@ const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const threadProviderOptions = new Map<string, ProviderStartOptions>();
|
||||
const threadModelOptions = new Map<string, ProviderModelOptions>();
|
||||
const threadModelSelections = new Map<string, ModelSelection>();
|
||||
|
||||
const appendProviderFailureActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
@@ -215,10 +222,7 @@ const make = Effect.gen(function* () {
|
||||
threadId: ThreadId,
|
||||
createdAt: string,
|
||||
options?: {
|
||||
readonly provider?: ProviderKind;
|
||||
readonly model?: string;
|
||||
readonly modelOptions?: ProviderModelOptions;
|
||||
readonly providerOptions?: ProviderStartOptions;
|
||||
readonly modelSelection?: ModelSelection;
|
||||
},
|
||||
) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
@@ -233,30 +237,30 @@ const make = Effect.gen(function* () {
|
||||
)
|
||||
? thread.session.providerName
|
||||
: undefined;
|
||||
const threadProvider: ProviderKind = currentProvider ?? inferProviderForModel(thread.model);
|
||||
if (options?.provider !== undefined && options.provider !== threadProvider) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: threadProvider,
|
||||
method: "thread.turn.start",
|
||||
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${options.provider}'.`,
|
||||
});
|
||||
}
|
||||
const requestedModelSelection = options?.modelSelection;
|
||||
const threadProvider: ProviderKind = currentProvider ?? thread.modelSelection.provider;
|
||||
if (
|
||||
options?.model !== undefined &&
|
||||
inferProviderForModel(options.model, threadProvider) !== threadProvider
|
||||
requestedModelSelection !== undefined &&
|
||||
requestedModelSelection.provider !== threadProvider
|
||||
) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: threadProvider,
|
||||
method: "thread.turn.start",
|
||||
detail: `Model '${options.model}' does not belong to provider '${threadProvider}' for thread '${threadId}'.`,
|
||||
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${requestedModelSelection.provider}'.`,
|
||||
});
|
||||
}
|
||||
const preferredProvider: ProviderKind = currentProvider ?? threadProvider;
|
||||
const desiredModel = options?.model ?? thread.model;
|
||||
const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
|
||||
const effectiveCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: readModel.projects,
|
||||
});
|
||||
if (effectiveCwd) {
|
||||
yield* assertWorkspaceDirectory(
|
||||
effectiveCwd,
|
||||
"ProviderCommandReactor.ensureSessionForThread",
|
||||
);
|
||||
}
|
||||
|
||||
const resolveActiveSession = (threadId: ThreadId) =>
|
||||
providerService
|
||||
@@ -269,15 +273,9 @@ const make = Effect.gen(function* () {
|
||||
}) =>
|
||||
providerService.startSession(threadId, {
|
||||
threadId,
|
||||
...((input?.provider ?? preferredProvider)
|
||||
? { provider: input?.provider ?? preferredProvider }
|
||||
: {}),
|
||||
...(preferredProvider ? { provider: preferredProvider } : {}),
|
||||
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
||||
...(desiredModel ? { model: desiredModel } : {}),
|
||||
...(options?.modelOptions !== undefined ? { modelOptions: options.modelOptions } : {}),
|
||||
...(options?.providerOptions !== undefined
|
||||
? { providerOptions: options.providerOptions }
|
||||
: {}),
|
||||
modelSelection: desiredModelSelection,
|
||||
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
|
||||
runtimeMode: desiredRuntimeMode,
|
||||
});
|
||||
@@ -303,25 +301,28 @@ const make = Effect.gen(function* () {
|
||||
if (existingSessionThreadId) {
|
||||
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
|
||||
const providerChanged =
|
||||
options?.provider !== undefined && options.provider !== currentProvider;
|
||||
requestedModelSelection !== undefined &&
|
||||
requestedModelSelection.provider !== currentProvider;
|
||||
const activeSession = yield* resolveActiveSession(existingSessionThreadId);
|
||||
const sessionModelSwitch =
|
||||
currentProvider === undefined
|
||||
? "in-session"
|
||||
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
|
||||
const modelChanged = options?.model !== undefined && options.model !== activeSession?.model;
|
||||
const modelChanged =
|
||||
requestedModelSelection !== undefined &&
|
||||
requestedModelSelection.model !== activeSession?.model;
|
||||
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
|
||||
const previousModelOptions = threadModelOptions.get(threadId);
|
||||
const shouldRestartForModelOptionsChange =
|
||||
const previousModelSelection = threadModelSelections.get(threadId);
|
||||
const shouldRestartForModelSelectionChange =
|
||||
currentProvider === "claudeAgent" &&
|
||||
options?.modelOptions !== undefined &&
|
||||
!sameModelOptions(previousModelOptions, options.modelOptions);
|
||||
requestedModelSelection !== undefined &&
|
||||
!Equal.equals(previousModelSelection, requestedModelSelection);
|
||||
|
||||
if (
|
||||
!runtimeModeChanged &&
|
||||
!providerChanged &&
|
||||
!shouldRestartForModelChange &&
|
||||
!shouldRestartForModelOptionsChange
|
||||
!shouldRestartForModelSelectionChange
|
||||
) {
|
||||
return existingSessionThreadId;
|
||||
}
|
||||
@@ -334,20 +335,19 @@ const make = Effect.gen(function* () {
|
||||
threadId,
|
||||
existingSessionThreadId,
|
||||
currentProvider,
|
||||
desiredProvider: options?.provider ?? currentProvider,
|
||||
desiredProvider: desiredModelSelection.provider,
|
||||
currentRuntimeMode: thread.session?.runtimeMode,
|
||||
desiredRuntimeMode: thread.runtimeMode,
|
||||
runtimeModeChanged,
|
||||
providerChanged,
|
||||
modelChanged,
|
||||
shouldRestartForModelChange,
|
||||
shouldRestartForModelOptionsChange,
|
||||
shouldRestartForModelSelectionChange,
|
||||
hasResumeCursor: resumeCursor !== undefined,
|
||||
});
|
||||
const restartedSession = yield* startProviderSession({
|
||||
...(resumeCursor !== undefined ? { resumeCursor } : {}),
|
||||
...(options?.provider !== undefined ? { provider: options.provider } : {}),
|
||||
});
|
||||
const restartedSession = yield* startProviderSession(
|
||||
resumeCursor !== undefined ? { resumeCursor } : undefined,
|
||||
);
|
||||
yield* Effect.logInfo("provider command reactor restarted provider session", {
|
||||
threadId,
|
||||
previousSessionId: existingSessionThreadId,
|
||||
@@ -359,9 +359,7 @@ const make = Effect.gen(function* () {
|
||||
return restartedSession.threadId;
|
||||
}
|
||||
|
||||
const startedSession = yield* startProviderSession(
|
||||
options?.provider !== undefined ? { provider: options.provider } : undefined,
|
||||
);
|
||||
const startedSession = yield* startProviderSession(undefined);
|
||||
yield* bindSessionToThread(startedSession);
|
||||
return startedSession.threadId;
|
||||
});
|
||||
@@ -370,10 +368,7 @@ const make = Effect.gen(function* () {
|
||||
readonly threadId: ThreadId;
|
||||
readonly messageText: string;
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||
readonly provider?: ProviderKind;
|
||||
readonly model?: string;
|
||||
readonly modelOptions?: ProviderModelOptions;
|
||||
readonly providerOptions?: ProviderStartOptions;
|
||||
readonly modelSelection?: ModelSelection;
|
||||
readonly interactionMode?: "default" | "plan";
|
||||
readonly createdAt: string;
|
||||
}) {
|
||||
@@ -381,17 +376,13 @@ const make = Effect.gen(function* () {
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
yield* ensureSessionForThread(input.threadId, input.createdAt, {
|
||||
...(input.provider !== undefined ? { provider: input.provider } : {}),
|
||||
...(input.model !== undefined ? { model: input.model } : {}),
|
||||
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
|
||||
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
|
||||
});
|
||||
if (input.providerOptions !== undefined) {
|
||||
threadProviderOptions.set(input.threadId, input.providerOptions);
|
||||
}
|
||||
if (input.modelOptions !== undefined) {
|
||||
threadModelOptions.set(input.threadId, input.modelOptions);
|
||||
yield* ensureSessionForThread(
|
||||
input.threadId,
|
||||
input.createdAt,
|
||||
input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {},
|
||||
);
|
||||
if (input.modelSelection !== undefined) {
|
||||
threadModelSelections.set(input.threadId, input.modelSelection);
|
||||
}
|
||||
const normalizedInput = toNonEmptyProviderInput(input.messageText);
|
||||
const normalizedAttachments = input.attachments ?? [];
|
||||
@@ -404,14 +395,23 @@ const make = Effect.gen(function* () {
|
||||
activeSession === undefined
|
||||
? "in-session"
|
||||
: (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
|
||||
const modelForTurn = sessionModelSwitch === "unsupported" ? activeSession?.model : input.model;
|
||||
const requestedModelSelection =
|
||||
input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;
|
||||
const modelForTurn =
|
||||
sessionModelSwitch === "unsupported"
|
||||
? activeSession?.model !== undefined
|
||||
? {
|
||||
...requestedModelSelection,
|
||||
model: activeSession.model,
|
||||
}
|
||||
: requestedModelSelection
|
||||
: input.modelSelection;
|
||||
|
||||
yield* providerService.sendTurn({
|
||||
threadId: input.threadId,
|
||||
...(normalizedInput ? { input: normalizedInput } : {}),
|
||||
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
|
||||
...(modelForTurn !== undefined ? { model: modelForTurn } : {}),
|
||||
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
|
||||
...(modelForTurn !== undefined ? { modelSelection: modelForTurn } : {}),
|
||||
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
|
||||
});
|
||||
});
|
||||
@@ -420,7 +420,6 @@ const make = Effect.gen(function* () {
|
||||
readonly threadId: ThreadId;
|
||||
readonly branch: string | null;
|
||||
readonly worktreePath: string | null;
|
||||
readonly messageId: string;
|
||||
readonly messageText: string;
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||
}) {
|
||||
@@ -431,58 +430,85 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const thread = yield* resolveThread(input.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
const userMessages = thread.messages.filter((message) => message.role === "user");
|
||||
if (userMessages.length !== 1 || userMessages[0]?.id !== input.messageId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const oldBranch = input.branch;
|
||||
const cwd = input.worktreePath;
|
||||
const attachments = input.attachments ?? [];
|
||||
yield* textGeneration
|
||||
.generateBranchName({
|
||||
yield* Effect.gen(function* () {
|
||||
const { textGenerationModelSelection: modelSelection } =
|
||||
yield* serverSettingsService.getSettings;
|
||||
|
||||
const generated = yield* textGeneration.generateBranchName({
|
||||
cwd,
|
||||
message: input.messageText,
|
||||
...(attachments.length > 0 ? { attachments } : {}),
|
||||
model: DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
})
|
||||
.pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning(
|
||||
"provider command reactor failed to generate worktree branch name; skipping rename",
|
||||
{ threadId: input.threadId, cwd, oldBranch, reason: error.message },
|
||||
),
|
||||
),
|
||||
Effect.flatMap((generated) => {
|
||||
if (!generated) return Effect.void;
|
||||
modelSelection,
|
||||
});
|
||||
if (!generated) return;
|
||||
|
||||
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
|
||||
if (targetBranch === oldBranch) return Effect.void;
|
||||
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
|
||||
if (targetBranch === oldBranch) return;
|
||||
|
||||
return Effect.flatMap(
|
||||
git.renameBranch({ cwd, oldBranch, newBranch: targetBranch }),
|
||||
(renamed) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: serverCommandId("worktree-branch-rename"),
|
||||
threadId: input.threadId,
|
||||
branch: renamed.branch,
|
||||
worktreePath: cwd,
|
||||
}),
|
||||
);
|
||||
const renamed = yield* git.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: serverCommandId("worktree-branch-rename"),
|
||||
threadId: input.threadId,
|
||||
branch: renamed.branch,
|
||||
worktreePath: cwd,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("provider command reactor failed to generate or rename worktree branch", {
|
||||
threadId: input.threadId,
|
||||
cwd,
|
||||
oldBranch,
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning(
|
||||
"provider command reactor failed to generate or rename worktree branch",
|
||||
{ threadId: input.threadId, cwd, oldBranch, cause: Cause.pretty(cause) },
|
||||
),
|
||||
),
|
||||
);
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const maybeGenerateThreadTitleForFirstTurn = Effect.fnUntraced(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly cwd: string;
|
||||
readonly messageText: string;
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||
readonly titleSeed?: string;
|
||||
}) {
|
||||
const attachments = input.attachments ?? [];
|
||||
yield* Effect.gen(function* () {
|
||||
const { textGenerationModelSelection: modelSelection } =
|
||||
yield* serverSettingsService.getSettings;
|
||||
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: input.cwd,
|
||||
message: input.messageText,
|
||||
...(attachments.length > 0 ? { attachments } : {}),
|
||||
modelSelection,
|
||||
});
|
||||
if (!generated) return;
|
||||
|
||||
const thread = yield* resolveThread(input.threadId);
|
||||
if (!thread) return;
|
||||
if (!canReplaceThreadTitle(thread.title, input.titleSeed)) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: serverCommandId("thread-title-rename"),
|
||||
threadId: input.threadId,
|
||||
title: generated.title,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("provider command reactor failed to generate or rename thread title", {
|
||||
threadId: input.threadId,
|
||||
cwd: input.cwd,
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const processTurnStartRequested = Effect.fnUntraced(function* (
|
||||
@@ -511,26 +537,42 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* maybeGenerateAndRenameWorktreeBranchForFirstTurn({
|
||||
threadId: event.payload.threadId,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
messageId: message.id,
|
||||
messageText: message.text,
|
||||
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
||||
}).pipe(Effect.forkScoped);
|
||||
const isFirstUserMessageTurn =
|
||||
thread.messages.filter((entry) => entry.role === "user").length === 1;
|
||||
if (isFirstUserMessageTurn) {
|
||||
const generationCwd =
|
||||
resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: (yield* orchestrationEngine.getReadModel()).projects,
|
||||
}) ?? process.cwd();
|
||||
const generationInput = {
|
||||
messageText: message.text,
|
||||
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
||||
...(event.payload.titleSeed !== undefined ? { titleSeed: event.payload.titleSeed } : {}),
|
||||
};
|
||||
|
||||
yield* maybeGenerateAndRenameWorktreeBranchForFirstTurn({
|
||||
threadId: event.payload.threadId,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
...generationInput,
|
||||
}).pipe(Effect.forkScoped);
|
||||
|
||||
if (canReplaceThreadTitle(thread.title, event.payload.titleSeed)) {
|
||||
yield* maybeGenerateThreadTitleForFirstTurn({
|
||||
threadId: event.payload.threadId,
|
||||
cwd: generationCwd,
|
||||
...generationInput,
|
||||
}).pipe(Effect.forkScoped);
|
||||
}
|
||||
}
|
||||
|
||||
yield* sendTurnForThread({
|
||||
threadId: event.payload.threadId,
|
||||
messageText: message.text,
|
||||
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
||||
...(event.payload.provider !== undefined ? { provider: event.payload.provider } : {}),
|
||||
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
|
||||
...(event.payload.modelOptions !== undefined
|
||||
? { modelOptions: event.payload.modelOptions }
|
||||
: {}),
|
||||
...(event.payload.providerOptions !== undefined
|
||||
? { providerOptions: event.payload.providerOptions }
|
||||
...(event.payload.modelSelection !== undefined
|
||||
? { modelSelection: event.payload.modelSelection }
|
||||
: {}),
|
||||
interactionMode: event.payload.interactionMode,
|
||||
createdAt: event.payload.createdAt,
|
||||
@@ -697,14 +739,12 @@ const make = Effect.gen(function* () {
|
||||
if (!thread?.session || thread.session.status === "stopped") {
|
||||
return;
|
||||
}
|
||||
const cachedProviderOptions = threadProviderOptions.get(event.payload.threadId);
|
||||
const cachedModelOptions = threadModelOptions.get(event.payload.threadId);
|
||||
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt, {
|
||||
...(cachedProviderOptions !== undefined
|
||||
? { providerOptions: cachedProviderOptions }
|
||||
: {}),
|
||||
...(cachedModelOptions !== undefined ? { modelOptions: cachedModelOptions } : {}),
|
||||
});
|
||||
const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
|
||||
yield* ensureSessionForThread(
|
||||
event.payload.threadId,
|
||||
event.occurredAt,
|
||||
cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {},
|
||||
);
|
||||
return;
|
||||
}
|
||||
case "thread.turn-start-requested":
|
||||
@@ -740,22 +780,24 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const worker = yield* makeDrainableWorker(processDomainEventSafely);
|
||||
|
||||
const start: ProviderCommandReactorShape["start"] = Effect.forkScoped(
|
||||
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
|
||||
const start: ProviderCommandReactorShape["start"] = Effect.fn("start")(function* () {
|
||||
const processEvent = Effect.fn("processEvent")(function* (event: OrchestrationEvent) {
|
||||
if (
|
||||
event.type !== "thread.runtime-mode-set" &&
|
||||
event.type !== "thread.turn-start-requested" &&
|
||||
event.type !== "thread.turn-interrupt-requested" &&
|
||||
event.type !== "thread.approval-response-requested" &&
|
||||
event.type !== "thread.user-input-response-requested" &&
|
||||
event.type !== "thread.session-stop-requested"
|
||||
event.type === "thread.runtime-mode-set" ||
|
||||
event.type === "thread.turn-start-requested" ||
|
||||
event.type === "thread.turn-interrupt-requested" ||
|
||||
event.type === "thread.approval-response-requested" ||
|
||||
event.type === "thread.user-input-response-requested" ||
|
||||
event.type === "thread.session-stop-requested"
|
||||
) {
|
||||
return Effect.void;
|
||||
return yield* worker.enqueue(event);
|
||||
}
|
||||
});
|
||||
|
||||
return worker.enqueue(event);
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(orchestrationEngine.streamDomainEvents, processEvent),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
start,
|
||||
|
||||
@@ -4,7 +4,6 @@ import path from "node:path";
|
||||
|
||||
import type {
|
||||
OrchestrationReadModel,
|
||||
ProviderKind,
|
||||
ProviderRuntimeEvent,
|
||||
ProviderSession,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -16,6 +15,7 @@ import {
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderItemId,
|
||||
type ServerSettings,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -38,8 +38,13 @@ import {
|
||||
} from "../Services/OrchestrationEngine.ts";
|
||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
function makeTestServerSettingsLayer(overrides: Partial<ServerSettings> = {}) {
|
||||
return ServerSettingsService.layerTest(overrides);
|
||||
}
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
@@ -50,7 +55,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: ProviderKind;
|
||||
readonly provider: ProviderRuntimeEvent["provider"];
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -60,6 +65,23 @@ type LegacyProviderRuntimeEvent = {
|
||||
readonly [key: string]: unknown;
|
||||
};
|
||||
|
||||
type LegacyTurnCompletedEvent = LegacyProviderRuntimeEvent & {
|
||||
readonly type: "turn.completed";
|
||||
readonly payload?: undefined;
|
||||
readonly status: "completed" | "failed" | "interrupted" | "cancelled";
|
||||
readonly errorMessage?: string | undefined;
|
||||
};
|
||||
|
||||
function isLegacyTurnCompletedEvent(
|
||||
event: LegacyProviderRuntimeEvent,
|
||||
): event is LegacyTurnCompletedEvent {
|
||||
return (
|
||||
event.type === "turn.completed" &&
|
||||
event.payload === undefined &&
|
||||
typeof event.status === "string"
|
||||
);
|
||||
}
|
||||
|
||||
function createProviderServiceHarness() {
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
const runtimeSessions: ProviderSession[] = [];
|
||||
@@ -87,8 +109,23 @@ function createProviderServiceHarness() {
|
||||
runtimeSessions.push(session);
|
||||
};
|
||||
|
||||
const normalizeLegacyEvent = (event: LegacyProviderRuntimeEvent): ProviderRuntimeEvent => {
|
||||
if (isLegacyTurnCompletedEvent(event)) {
|
||||
const normalized: Extract<ProviderRuntimeEvent, { type: "turn.completed" }> = {
|
||||
...(event as Omit<Extract<ProviderRuntimeEvent, { type: "turn.completed" }>, "payload">),
|
||||
payload: {
|
||||
state: event.status,
|
||||
...(typeof event.errorMessage === "string" ? { errorMessage: event.errorMessage } : {}),
|
||||
},
|
||||
};
|
||||
return normalized;
|
||||
}
|
||||
|
||||
return event as ProviderRuntimeEvent;
|
||||
};
|
||||
|
||||
const emit = (event: LegacyProviderRuntimeEvent): void => {
|
||||
Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent));
|
||||
Effect.runSync(PubSub.publish(runtimeEventPubSub, normalizeLegacyEvent(event)));
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -155,7 +192,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
}
|
||||
});
|
||||
|
||||
async function createHarness() {
|
||||
async function createHarness(options?: { serverSettings?: Partial<ServerSettings> }) {
|
||||
const workspaceRoot = makeTempDir("t3-provider-project-");
|
||||
fs.mkdirSync(path.join(workspaceRoot, ".git"));
|
||||
const provider = createProviderServiceHarness();
|
||||
@@ -169,6 +206,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
@@ -176,7 +214,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const ingestion = await runtime.runPromise(Effect.service(ProviderRuntimeIngestionService));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(ingestion.start.pipe(Scope.provide(scope)));
|
||||
await Effect.runPromise(ingestion.start().pipe(Scope.provide(scope)));
|
||||
const drain = () => Effect.runPromise(ingestion.drain);
|
||||
|
||||
const createdAt = new Date().toISOString();
|
||||
@@ -187,7 +225,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Provider Project",
|
||||
workspaceRoot,
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -198,7 +239,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -724,7 +768,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
threadId: sourceThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "plan",
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -756,7 +803,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
threadId: targetThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Target",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -905,7 +955,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
threadId: sourceThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "plan",
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -1055,7 +1108,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
threadId: sourceThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "plan",
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -1087,7 +1143,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
threadId: targetThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Target",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -1336,7 +1395,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
it("streams assistant deltas when thread.turn.start requests streaming mode", async () => {
|
||||
const harness = await createHarness();
|
||||
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
@@ -1350,7 +1409,6 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
text: "stream please",
|
||||
attachments: [],
|
||||
},
|
||||
assistantDeliveryMode: "streaming",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
@@ -1668,6 +1726,37 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(thread.session?.lastError).toBe("runtime exploded");
|
||||
});
|
||||
|
||||
it("records runtime.error activities from the typed payload message", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "runtime.error",
|
||||
eventId: asEventId("evt-runtime-error-activity"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-runtime-error-activity"),
|
||||
payload: {
|
||||
message: "runtime activity exploded",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some((activity) => activity.id === "evt-runtime-error-activity"),
|
||||
);
|
||||
const activity = thread.activities.find(
|
||||
(entry: ProviderRuntimeTestActivity) => entry.id === "evt-runtime-error-activity",
|
||||
);
|
||||
const activityPayload =
|
||||
activity?.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: undefined;
|
||||
|
||||
expect(activity?.kind).toBe("runtime.error");
|
||||
expect(activityPayload?.message).toBe("runtime activity exploded");
|
||||
});
|
||||
|
||||
it("keeps the session running when a runtime.warning arrives during an active turn", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -1898,6 +1987,185 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(checkpoint?.checkpointRef).toBe("provider-diff:evt-turn-diff-updated");
|
||||
});
|
||||
|
||||
it("projects context window updates into normalized thread activities", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "thread.token-usage.updated",
|
||||
eventId: asEventId("evt-thread-token-usage-updated"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
usage: {
|
||||
usedTokens: 1075,
|
||||
totalProcessedTokens: 10_200,
|
||||
maxTokens: 128_000,
|
||||
inputTokens: 1000,
|
||||
cachedInputTokens: 500,
|
||||
outputTokens: 50,
|
||||
reasoningOutputTokens: 25,
|
||||
lastUsedTokens: 1075,
|
||||
lastInputTokens: 1000,
|
||||
lastCachedInputTokens: 500,
|
||||
lastOutputTokens: 50,
|
||||
lastReasoningOutputTokens: 25,
|
||||
compactsAutomatically: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
),
|
||||
);
|
||||
|
||||
const usageActivity = thread.activities.find(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
);
|
||||
expect(usageActivity).toBeDefined();
|
||||
expect(usageActivity?.payload).toMatchObject({
|
||||
usedTokens: 1075,
|
||||
totalProcessedTokens: 10_200,
|
||||
maxTokens: 128_000,
|
||||
inputTokens: 1000,
|
||||
cachedInputTokens: 500,
|
||||
outputTokens: 50,
|
||||
reasoningOutputTokens: 25,
|
||||
lastUsedTokens: 1075,
|
||||
compactsAutomatically: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("projects Codex camelCase token usage payloads into normalized thread activities", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "thread.token-usage.updated",
|
||||
eventId: asEventId("evt-thread-token-usage-updated-camel"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
usage: {
|
||||
usedTokens: 126,
|
||||
totalProcessedTokens: 11_839,
|
||||
maxTokens: 258_400,
|
||||
inputTokens: 120,
|
||||
cachedInputTokens: 0,
|
||||
outputTokens: 6,
|
||||
reasoningOutputTokens: 0,
|
||||
lastUsedTokens: 126,
|
||||
lastInputTokens: 120,
|
||||
lastCachedInputTokens: 0,
|
||||
lastOutputTokens: 6,
|
||||
lastReasoningOutputTokens: 0,
|
||||
compactsAutomatically: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
),
|
||||
);
|
||||
|
||||
const usageActivity = thread.activities.find(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
);
|
||||
expect(usageActivity?.payload).toMatchObject({
|
||||
usedTokens: 126,
|
||||
totalProcessedTokens: 11_839,
|
||||
maxTokens: 258_400,
|
||||
inputTokens: 120,
|
||||
cachedInputTokens: 0,
|
||||
outputTokens: 6,
|
||||
reasoningOutputTokens: 0,
|
||||
lastUsedTokens: 126,
|
||||
lastInputTokens: 120,
|
||||
lastOutputTokens: 6,
|
||||
compactsAutomatically: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("projects Claude usage snapshots with context window into normalized thread activities", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "thread.token-usage.updated",
|
||||
eventId: asEventId("evt-thread-token-usage-updated-claude-window"),
|
||||
provider: "claudeAgent",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
usage: {
|
||||
usedTokens: 31_251,
|
||||
lastUsedTokens: 31_251,
|
||||
maxTokens: 200_000,
|
||||
toolUses: 25,
|
||||
durationMs: 43_567,
|
||||
},
|
||||
},
|
||||
raw: {
|
||||
source: "claude.sdk.message",
|
||||
method: "claude/result/success",
|
||||
payload: {},
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
),
|
||||
);
|
||||
|
||||
const usageActivity = thread.activities.find(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
);
|
||||
expect(usageActivity?.payload).toMatchObject({
|
||||
usedTokens: 31_251,
|
||||
lastUsedTokens: 31_251,
|
||||
maxTokens: 200_000,
|
||||
toolUses: 25,
|
||||
durationMs: 43_567,
|
||||
});
|
||||
});
|
||||
|
||||
it("projects compacted thread state into context compaction activities", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "thread.state.changed",
|
||||
eventId: asEventId("evt-thread-compacted"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
payload: {
|
||||
state: "compacted",
|
||||
detail: { source: "provider" },
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-compaction",
|
||||
),
|
||||
);
|
||||
|
||||
const activity = thread.activities.find(
|
||||
(candidate: ProviderRuntimeTestActivity) => candidate.kind === "context-compaction",
|
||||
);
|
||||
expect(activity?.summary).toBe("Context compacted");
|
||||
expect(activity?.tone).toBe("info");
|
||||
});
|
||||
|
||||
it("projects Codex task lifecycle chunks into thread activities", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,10 +3,12 @@ import {
|
||||
ProjectMetaUpdatedPayload as ContractsProjectMetaUpdatedPayloadSchema,
|
||||
ProjectDeletedPayload as ContractsProjectDeletedPayloadSchema,
|
||||
ThreadCreatedPayload as ContractsThreadCreatedPayloadSchema,
|
||||
ThreadArchivedPayload as ContractsThreadArchivedPayloadSchema,
|
||||
ThreadMetaUpdatedPayload as ContractsThreadMetaUpdatedPayloadSchema,
|
||||
ThreadRuntimeModeSetPayload as ContractsThreadRuntimeModeSetPayloadSchema,
|
||||
ThreadInteractionModeSetPayload as ContractsThreadInteractionModeSetPayloadSchema,
|
||||
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
|
||||
ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema,
|
||||
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
|
||||
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
|
||||
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
|
||||
@@ -26,10 +28,12 @@ export const ProjectMetaUpdatedPayload = ContractsProjectMetaUpdatedPayloadSchem
|
||||
export const ProjectDeletedPayload = ContractsProjectDeletedPayloadSchema;
|
||||
|
||||
export const ThreadCreatedPayload = ContractsThreadCreatedPayloadSchema;
|
||||
export const ThreadArchivedPayload = ContractsThreadArchivedPayloadSchema;
|
||||
export const ThreadMetaUpdatedPayload = ContractsThreadMetaUpdatedPayloadSchema;
|
||||
export const ThreadRuntimeModeSetPayload = ContractsThreadRuntimeModeSetPayloadSchema;
|
||||
export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSetPayloadSchema;
|
||||
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
|
||||
export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
|
||||
|
||||
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
|
||||
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
|
||||
|
||||
@@ -22,7 +22,7 @@ export interface CheckpointReactorShape {
|
||||
* Consumes both orchestration-domain and provider-runtime events via an
|
||||
* internal queue.
|
||||
*/
|
||||
readonly start: Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
||||
|
||||
/**
|
||||
* Resolves when the internal processing queue is empty and idle.
|
||||
|
||||
@@ -19,7 +19,7 @@ export interface OrchestrationReactorShape {
|
||||
* The returned effect must be run in a scope so all worker fibers can be
|
||||
* finalized on shutdown.
|
||||
*/
|
||||
readonly start: Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -22,7 +22,7 @@ export interface ProviderCommandReactorShape {
|
||||
* Filters orchestration domain events to provider-intent types before
|
||||
* processing.
|
||||
*/
|
||||
readonly start: Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
||||
|
||||
/**
|
||||
* Resolves when the internal processing queue is empty and idle.
|
||||
|
||||
@@ -22,7 +22,7 @@ export interface ProviderRuntimeIngestionShape {
|
||||
* Uses an internal queue and continues after non-interrupt failures by
|
||||
* logging warnings.
|
||||
*/
|
||||
readonly start: Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
||||
|
||||
/**
|
||||
* Resolves when the internal processing queue is empty and idle.
|
||||
|
||||
@@ -28,7 +28,11 @@ const readModel: OrchestrationReadModel = {
|
||||
id: ProjectId.makeUnsafe("project-a"),
|
||||
title: "Project A",
|
||||
workspaceRoot: "/tmp/project-a",
|
||||
defaultModel: "gpt-5-codex",
|
||||
workspaceState: "available",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -38,7 +42,11 @@ const readModel: OrchestrationReadModel = {
|
||||
id: ProjectId.makeUnsafe("project-b"),
|
||||
title: "Project B",
|
||||
workspaceRoot: "/tmp/project-b",
|
||||
defaultModel: "gpt-5-codex",
|
||||
workspaceState: "available",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -50,13 +58,20 @@ const readModel: OrchestrationReadModel = {
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "Thread A",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
effectiveCwd: "/tmp/project-a",
|
||||
effectiveCwdSource: "project",
|
||||
effectiveCwdState: "available",
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: null,
|
||||
@@ -69,13 +84,20 @@ const readModel: OrchestrationReadModel = {
|
||||
id: ThreadId.makeUnsafe("thread-2"),
|
||||
projectId: ProjectId.makeUnsafe("project-b"),
|
||||
title: "Thread B",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
effectiveCwd: "/tmp/project-b",
|
||||
effectiveCwdSource: "project",
|
||||
effectiveCwdState: "available",
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: null,
|
||||
@@ -144,7 +166,10 @@ describe("commandInvariants", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-3"),
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "new",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
@@ -165,7 +190,10 @@ describe("commandInvariants", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "dup",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
|
||||
@@ -88,6 +88,44 @@ export function requireThread(input: {
|
||||
);
|
||||
}
|
||||
|
||||
export function requireThreadArchived(input: {
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly threadId: ThreadId;
|
||||
}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {
|
||||
return requireThread(input).pipe(
|
||||
Effect.flatMap((thread) =>
|
||||
thread.archivedAt !== null
|
||||
? Effect.succeed(thread)
|
||||
: Effect.fail(
|
||||
invariantError(
|
||||
input.command.type,
|
||||
`Thread '${input.threadId}' is not archived for command '${input.command.type}'.`,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function requireThreadNotArchived(input: {
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly threadId: ThreadId;
|
||||
}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {
|
||||
return requireThread(input).pipe(
|
||||
Effect.flatMap((thread) =>
|
||||
thread.archivedAt === null
|
||||
? Effect.succeed(thread)
|
||||
: Effect.fail(
|
||||
invariantError(
|
||||
input.command.type,
|
||||
`Thread '${input.threadId}' is already archived and cannot handle command '${input.command.type}'.`,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function requireThreadAbsent(input: {
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
|
||||
@@ -59,7 +59,7 @@ describe("decider project scripts", () => {
|
||||
projectId: asProjectId("project-scripts"),
|
||||
title: "Scripts",
|
||||
workspaceRoot: "/tmp/scripts",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -113,7 +113,7 @@ describe("decider project scripts", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -136,7 +136,10 @@ describe("decider project scripts", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -159,10 +162,10 @@ describe("decider project scripts", () => {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -185,14 +188,13 @@ describe("decider project scripts", () => {
|
||||
if (turnStartEvent?.type !== "thread.turn-start-requested") {
|
||||
return;
|
||||
}
|
||||
expect(turnStartEvent.payload.assistantDeliveryMode).toBe("buffered");
|
||||
expect(turnStartEvent.payload).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
messageId: asMessageId("message-user-1"),
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -220,7 +222,7 @@ describe("decider project scripts", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -243,7 +245,10 @@ describe("decider project scripts", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
@@ -299,7 +304,7 @@ describe("decider project scripts", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -322,7 +327,10 @@ describe("decider project scripts", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
|
||||
@@ -10,12 +10,12 @@ import {
|
||||
requireProject,
|
||||
requireProjectAbsent,
|
||||
requireThread,
|
||||
requireThreadArchived,
|
||||
requireThreadAbsent,
|
||||
requireThreadNotArchived,
|
||||
} from "./commandInvariants.ts";
|
||||
|
||||
const nowIso = () => new Date().toISOString();
|
||||
const DEFAULT_ASSISTANT_DELIVERY_MODE = "buffered" as const;
|
||||
|
||||
const defaultMetadata: Omit<OrchestrationEvent, "sequence" | "type" | "payload"> = {
|
||||
eventId: crypto.randomUUID() as OrchestrationEvent["eventId"],
|
||||
aggregateKind: "thread",
|
||||
@@ -77,7 +77,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
projectId: command.projectId,
|
||||
title: command.title,
|
||||
workspaceRoot: command.workspaceRoot,
|
||||
defaultModel: command.defaultModel ?? null,
|
||||
defaultModelSelection: command.defaultModelSelection ?? null,
|
||||
scripts: [],
|
||||
createdAt: command.createdAt,
|
||||
updatedAt: command.createdAt,
|
||||
@@ -104,7 +104,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
projectId: command.projectId,
|
||||
...(command.title !== undefined ? { title: command.title } : {}),
|
||||
...(command.workspaceRoot !== undefined ? { workspaceRoot: command.workspaceRoot } : {}),
|
||||
...(command.defaultModel !== undefined ? { defaultModel: command.defaultModel } : {}),
|
||||
...(command.defaultModelSelection !== undefined
|
||||
? { defaultModelSelection: command.defaultModelSelection }
|
||||
: {}),
|
||||
...(command.scripts !== undefined ? { scripts: command.scripts } : {}),
|
||||
updatedAt: occurredAt,
|
||||
},
|
||||
@@ -156,7 +158,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
projectId: command.projectId,
|
||||
title: command.title,
|
||||
model: command.model,
|
||||
modelSelection: command.modelSelection,
|
||||
runtimeMode: command.runtimeMode,
|
||||
interactionMode: command.interactionMode,
|
||||
branch: command.branch,
|
||||
@@ -189,6 +191,51 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.archive": {
|
||||
yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const occurredAt = nowIso();
|
||||
return {
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
type: "thread.archived",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
archivedAt: occurredAt,
|
||||
updatedAt: occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.unarchive": {
|
||||
yield* requireThreadArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const occurredAt = nowIso();
|
||||
return {
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
type: "thread.unarchived",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
updatedAt: occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.meta.update": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
@@ -207,7 +254,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
...(command.title !== undefined ? { title: command.title } : {}),
|
||||
...(command.model !== undefined ? { model: command.model } : {}),
|
||||
...(command.modelSelection !== undefined
|
||||
? { modelSelection: command.modelSelection }
|
||||
: {}),
|
||||
...(command.branch !== undefined ? { branch: command.branch } : {}),
|
||||
...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
|
||||
updatedAt: occurredAt,
|
||||
@@ -323,13 +372,10 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
messageId: command.message.messageId,
|
||||
...(command.provider !== undefined ? { provider: command.provider } : {}),
|
||||
...(command.model !== undefined ? { model: command.model } : {}),
|
||||
...(command.modelOptions !== undefined ? { modelOptions: command.modelOptions } : {}),
|
||||
...(command.providerOptions !== undefined
|
||||
? { providerOptions: command.providerOptions }
|
||||
...(command.modelSelection !== undefined
|
||||
? { modelSelection: command.modelSelection }
|
||||
: {}),
|
||||
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
|
||||
...(command.titleSeed !== undefined ? { titleSeed: command.titleSeed } : {}),
|
||||
runtimeMode: targetThread.runtimeMode,
|
||||
interactionMode: targetThread.interactionMode,
|
||||
...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
|
||||
|
||||
@@ -56,7 +56,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -73,7 +76,10 @@ describe("orchestration projector", () => {
|
||||
id: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
@@ -81,6 +87,7 @@ describe("orchestration projector", () => {
|
||||
latestTurn: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
@@ -110,7 +117,10 @@ describe("orchestration projector", () => {
|
||||
// missing required threadId
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -122,6 +132,78 @@ describe("orchestration projector", () => {
|
||||
).rejects.toBeDefined();
|
||||
});
|
||||
|
||||
it("applies thread.archived and thread.unarchived events", async () => {
|
||||
const now = new Date().toISOString();
|
||||
const later = new Date(Date.parse(now) + 1_000).toISOString();
|
||||
const created = await Effect.runPromise(
|
||||
projectEvent(
|
||||
createEmptyReadModel(now),
|
||||
makeEvent({
|
||||
sequence: 1,
|
||||
type: "thread.created",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: now,
|
||||
commandId: "cmd-thread-create",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const archived = await Effect.runPromise(
|
||||
projectEvent(
|
||||
created,
|
||||
makeEvent({
|
||||
sequence: 2,
|
||||
type: "thread.archived",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: later,
|
||||
commandId: "cmd-thread-archive",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
archivedAt: later,
|
||||
updatedAt: later,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(archived.threads[0]?.archivedAt).toBe(later);
|
||||
|
||||
const unarchived = await Effect.runPromise(
|
||||
projectEvent(
|
||||
archived,
|
||||
makeEvent({
|
||||
sequence: 3,
|
||||
type: "thread.unarchived",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: later,
|
||||
commandId: "cmd-thread-unarchive",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
updatedAt: later,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(unarchived.threads[0]?.archivedAt).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps projector forward-compatible for unhandled event types", async () => {
|
||||
const now = new Date().toISOString();
|
||||
const model = createEmptyReadModel(now);
|
||||
@@ -170,7 +252,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -233,7 +318,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -287,7 +375,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -371,7 +462,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -583,7 +677,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-revert",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -733,7 +830,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-capped",
|
||||
projectId: "project-1",
|
||||
title: "capped",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
|
||||
@@ -14,12 +14,14 @@ import {
|
||||
ProjectDeletedPayload,
|
||||
ProjectMetaUpdatedPayload,
|
||||
ThreadActivityAppendedPayload,
|
||||
ThreadArchivedPayload,
|
||||
ThreadCreatedPayload,
|
||||
ThreadDeletedPayload,
|
||||
ThreadInteractionModeSetPayload,
|
||||
ThreadMetaUpdatedPayload,
|
||||
ThreadProposedPlanUpsertedPayload,
|
||||
ThreadRuntimeModeSetPayload,
|
||||
ThreadUnarchivedPayload,
|
||||
ThreadRevertedPayload,
|
||||
ThreadSessionSetPayload,
|
||||
ThreadTurnDiffCompletedPayload,
|
||||
@@ -181,7 +183,8 @@ export function projectEvent(
|
||||
id: payload.projectId,
|
||||
title: payload.title,
|
||||
workspaceRoot: payload.workspaceRoot,
|
||||
defaultModel: payload.defaultModel,
|
||||
workspaceState: "available" as const,
|
||||
defaultModelSelection: payload.defaultModelSelection,
|
||||
scripts: payload.scripts,
|
||||
createdAt: payload.createdAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
@@ -211,8 +214,8 @@ export function projectEvent(
|
||||
...(payload.workspaceRoot !== undefined
|
||||
? { workspaceRoot: payload.workspaceRoot }
|
||||
: {}),
|
||||
...(payload.defaultModel !== undefined
|
||||
? { defaultModel: payload.defaultModel }
|
||||
...(payload.defaultModelSelection !== undefined
|
||||
? { defaultModelSelection: payload.defaultModelSelection }
|
||||
: {}),
|
||||
...(payload.scripts !== undefined ? { scripts: payload.scripts } : {}),
|
||||
updatedAt: payload.updatedAt,
|
||||
@@ -252,7 +255,7 @@ export function projectEvent(
|
||||
id: payload.threadId,
|
||||
projectId: payload.projectId,
|
||||
title: payload.title,
|
||||
model: payload.model,
|
||||
modelSelection: payload.modelSelection,
|
||||
runtimeMode: payload.runtimeMode,
|
||||
interactionMode: payload.interactionMode,
|
||||
branch: payload.branch,
|
||||
@@ -260,6 +263,7 @@ export function projectEvent(
|
||||
latestTurn: null,
|
||||
createdAt: payload.createdAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
@@ -289,13 +293,37 @@ 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) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
...(payload.title !== undefined ? { title: payload.title } : {}),
|
||||
...(payload.model !== undefined ? { model: payload.model } : {}),
|
||||
...(payload.modelSelection !== undefined
|
||||
? { modelSelection: payload.modelSelection }
|
||||
: {}),
|
||||
...(payload.branch !== undefined ? { branch: payload.branch } : {}),
|
||||
...(payload.worktreePath !== undefined ? { worktreePath: payload.worktreePath } : {}),
|
||||
updatedAt: payload.updatedAt,
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { fixPath } from "./os-jank";
|
||||
|
||||
describe("fixPath", () => {
|
||||
it("hydrates PATH on linux using the resolved login shell", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
const readPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin");
|
||||
|
||||
fixPath({
|
||||
env,
|
||||
platform: "linux",
|
||||
readPath,
|
||||
});
|
||||
|
||||
expect(readPath).toHaveBeenCalledWith("/bin/zsh");
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
});
|
||||
|
||||
it("does nothing outside macOS and linux even when SHELL is set", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "C:/Program Files/Git/bin/bash.exe",
|
||||
PATH: "C:\\Windows\\System32",
|
||||
};
|
||||
const readPath = vi.fn(() => "/usr/local/bin:/usr/bin");
|
||||
|
||||
fixPath({
|
||||
env,
|
||||
platform: "win32",
|
||||
readPath,
|
||||
});
|
||||
|
||||
expect(readPath).not.toHaveBeenCalled();
|
||||
expect(env.PATH).toBe("C:\\Windows\\System32");
|
||||
});
|
||||
});
|
||||
@@ -1,15 +1,25 @@
|
||||
import * as OS from "node:os";
|
||||
import { Effect, Path } from "effect";
|
||||
import { readPathFromLoginShell } from "@t3tools/shared/shell";
|
||||
import { readPathFromLoginShell, resolveLoginShell } from "@t3tools/shared/shell";
|
||||
|
||||
export function fixPath(): void {
|
||||
if (process.platform !== "darwin") return;
|
||||
export function fixPath(
|
||||
options: {
|
||||
env?: NodeJS.ProcessEnv;
|
||||
platform?: NodeJS.Platform;
|
||||
readPath?: typeof readPathFromLoginShell;
|
||||
} = {},
|
||||
): void {
|
||||
const platform = options.platform ?? process.platform;
|
||||
if (platform !== "darwin" && platform !== "linux") return;
|
||||
|
||||
const env = options.env ?? process.env;
|
||||
|
||||
try {
|
||||
const shell = process.env.SHELL ?? "/bin/zsh";
|
||||
const result = readPathFromLoginShell(shell);
|
||||
const shell = resolveLoginShell(platform, env.SHELL);
|
||||
if (!shell) return;
|
||||
const result = (options.readPath ?? readPathFromLoginShell)(shell);
|
||||
if (result) {
|
||||
process.env.PATH = result;
|
||||
env.PATH = result;
|
||||
}
|
||||
} catch {
|
||||
// Silently ignore — keep default PATH
|
||||
|
||||
@@ -35,7 +35,7 @@ layer("OrchestrationEventStore", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-roundtrip"),
|
||||
title: "Roundtrip Project",
|
||||
workspaceRoot: "/tmp/project-roundtrip",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import { Effect, Layer, Option, Schema, Struct } from "effect";
|
||||
|
||||
import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
|
||||
import { ModelSelection, ProjectScript } from "@t3tools/contracts";
|
||||
import { toPersistenceSqlError } from "../Errors.ts";
|
||||
import {
|
||||
DeleteProjectionProjectInput,
|
||||
GetProjectionProjectInput,
|
||||
@@ -11,69 +11,64 @@ import {
|
||||
ProjectionProjectRepository,
|
||||
type ProjectionProjectRepositoryShape,
|
||||
} from "../Services/ProjectionProjects.ts";
|
||||
import { ProjectScript } from "@t3tools/contracts";
|
||||
|
||||
// Makes sure that the scripts are parsed from the JSON string the DB returns
|
||||
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
|
||||
Struct.assign({ scripts: Schema.fromJsonString(Schema.Array(ProjectScript)) }),
|
||||
const ProjectionProjectDbRow = ProjectionProject.mapFields(
|
||||
Struct.assign({
|
||||
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
|
||||
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
||||
}),
|
||||
);
|
||||
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown) =>
|
||||
Schema.isSchemaError(cause)
|
||||
? toPersistenceDecodeError(decodeOperation)(cause)
|
||||
: toPersistenceSqlError(sqlOperation)(cause);
|
||||
}
|
||||
type ProjectionProjectDbRow = typeof ProjectionProjectDbRow.Type;
|
||||
|
||||
const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
const upsertProjectionProjectRow = SqlSchema.void({
|
||||
Request: ProjectionProjectDbRowSchema,
|
||||
Request: ProjectionProject,
|
||||
execute: (row) =>
|
||||
sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
${row.projectId},
|
||||
${row.title},
|
||||
${row.workspaceRoot},
|
||||
${row.defaultModel},
|
||||
${row.scripts},
|
||||
${row.createdAt},
|
||||
${row.updatedAt},
|
||||
${row.deletedAt}
|
||||
)
|
||||
ON CONFLICT (project_id)
|
||||
DO UPDATE SET
|
||||
title = excluded.title,
|
||||
workspace_root = excluded.workspace_root,
|
||||
default_model = excluded.default_model,
|
||||
scripts_json = excluded.scripts_json,
|
||||
created_at = excluded.created_at,
|
||||
updated_at = excluded.updated_at,
|
||||
deleted_at = excluded.deleted_at
|
||||
`,
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
${row.projectId},
|
||||
${row.title},
|
||||
${row.workspaceRoot},
|
||||
${row.defaultModelSelection !== null ? JSON.stringify(row.defaultModelSelection) : null},
|
||||
${JSON.stringify(row.scripts)},
|
||||
${row.createdAt},
|
||||
${row.updatedAt},
|
||||
${row.deletedAt}
|
||||
)
|
||||
ON CONFLICT (project_id)
|
||||
DO UPDATE SET
|
||||
title = excluded.title,
|
||||
workspace_root = excluded.workspace_root,
|
||||
default_model_selection_json = excluded.default_model_selection_json,
|
||||
scripts_json = excluded.scripts_json,
|
||||
created_at = excluded.created_at,
|
||||
updated_at = excluded.updated_at,
|
||||
deleted_at = excluded.deleted_at
|
||||
`,
|
||||
});
|
||||
|
||||
const getProjectionProjectRow = SqlSchema.findOneOption({
|
||||
Request: GetProjectionProjectInput,
|
||||
Result: ProjectionProjectDbRowSchema,
|
||||
Result: ProjectionProjectDbRow,
|
||||
execute: ({ projectId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_model AS "defaultModel",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -85,14 +80,14 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
|
||||
const listProjectionProjectRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionProjectDbRowSchema,
|
||||
Result: ProjectionProjectDbRow,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_model AS "defaultModel",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -113,40 +108,17 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
|
||||
const upsert: ProjectionProjectRepositoryShape["upsert"] = (row) =>
|
||||
upsertProjectionProjectRow(row).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionProjectRepository.upsert:query",
|
||||
"ProjectionProjectRepository.upsert:encodeRequest",
|
||||
),
|
||||
),
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.upsert:query")),
|
||||
);
|
||||
|
||||
const getById: ProjectionProjectRepositoryShape["getById"] = (input) =>
|
||||
getProjectionProjectRow(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionProjectRepository.getById:query",
|
||||
"ProjectionProjectRepository.getById:decodeRow",
|
||||
),
|
||||
),
|
||||
Effect.flatMap((rowOption) =>
|
||||
Option.match(rowOption, {
|
||||
onNone: () => Effect.succeed(Option.none()),
|
||||
onSome: (row) =>
|
||||
Effect.succeed(Option.some(row as Schema.Schema.Type<typeof ProjectionProject>)),
|
||||
}),
|
||||
),
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.getById:query")),
|
||||
);
|
||||
|
||||
const listAll: ProjectionProjectRepositoryShape["listAll"] = () =>
|
||||
listProjectionProjectRows().pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionProjectRepository.listAll:query",
|
||||
"ProjectionProjectRepository.listAll:decodeRows",
|
||||
),
|
||||
),
|
||||
Effect.map((rows) => rows as ReadonlyArray<Schema.Schema.Type<typeof ProjectionProject>>),
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.listAll:query")),
|
||||
);
|
||||
|
||||
const deleteById: ProjectionProjectRepositoryShape["deleteById"] = (input) =>
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { SqlitePersistenceMemory } from "./Sqlite.ts";
|
||||
import { ProjectionProjectRepositoryLive } from "./ProjectionProjects.ts";
|
||||
import { ProjectionThreadRepositoryLive } from "./ProjectionThreads.ts";
|
||||
import { ProjectionProjectRepository } from "../Services/ProjectionProjects.ts";
|
||||
import { ProjectionThreadRepository } from "../Services/ProjectionThreads.ts";
|
||||
|
||||
const projectionRepositoriesLayer = it.layer(
|
||||
Layer.mergeAll(
|
||||
ProjectionProjectRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
|
||||
ProjectionThreadRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
|
||||
SqlitePersistenceMemory,
|
||||
),
|
||||
);
|
||||
|
||||
projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
it.effect("stores SQL NULL for missing project model options", () =>
|
||||
Effect.gen(function* () {
|
||||
const projects = yield* ProjectionProjectRepository;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* projects.upsert({
|
||||
projectId: ProjectId.makeUnsafe("project-null-options"),
|
||||
title: "Null options project",
|
||||
workspaceRoot: "/tmp/project-null-options",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: "2026-03-24T00:00:00.000Z",
|
||||
updatedAt: "2026-03-24T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
});
|
||||
|
||||
const rows = yield* sql<{
|
||||
readonly defaultModelSelection: string | null;
|
||||
}>`
|
||||
SELECT default_model_selection_json AS "defaultModelSelection"
|
||||
FROM projection_projects
|
||||
WHERE project_id = 'project-null-options'
|
||||
`;
|
||||
const row = rows[0];
|
||||
if (!row) {
|
||||
return yield* Effect.fail(new Error("Expected projection_projects row to exist."));
|
||||
}
|
||||
|
||||
assert.strictEqual(
|
||||
row.defaultModelSelection,
|
||||
JSON.stringify({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
}),
|
||||
);
|
||||
|
||||
const persisted = yield* projects.getById({
|
||||
projectId: ProjectId.makeUnsafe("project-null-options"),
|
||||
});
|
||||
assert.deepStrictEqual(Option.getOrNull(persisted)?.defaultModelSelection, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("stores JSON for thread model options", () =>
|
||||
Effect.gen(function* () {
|
||||
const threads = yield* ProjectionThreadRepository;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* threads.upsert({
|
||||
threadId: ThreadId.makeUnsafe("thread-null-options"),
|
||||
projectId: ProjectId.makeUnsafe("project-null-options"),
|
||||
title: "Null options thread",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurnId: null,
|
||||
createdAt: "2026-03-24T00:00:00.000Z",
|
||||
updatedAt: "2026-03-24T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
});
|
||||
|
||||
const rows = yield* sql<{
|
||||
readonly modelSelection: string | null;
|
||||
}>`
|
||||
SELECT model_selection_json AS "modelSelection"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = 'thread-null-options'
|
||||
`;
|
||||
const row = rows[0];
|
||||
if (!row) {
|
||||
return yield* Effect.fail(new Error("Expected projection_threads row to exist."));
|
||||
}
|
||||
|
||||
assert.strictEqual(
|
||||
row.modelSelection,
|
||||
JSON.stringify({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
}),
|
||||
);
|
||||
|
||||
const persisted = yield* threads.getById({
|
||||
threadId: ThreadId.makeUnsafe("thread-null-options"),
|
||||
});
|
||||
assert.deepStrictEqual(Option.getOrNull(persisted)?.modelSelection, {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
|
||||
import { toPersistenceSqlError } from "../Errors.ts";
|
||||
import {
|
||||
@@ -11,6 +11,14 @@ import {
|
||||
ProjectionThreadRepository,
|
||||
type ProjectionThreadRepositoryShape,
|
||||
} from "../Services/ProjectionThreads.ts";
|
||||
import { ModelSelection } from "@t3tools/contracts";
|
||||
|
||||
const ProjectionThreadDbRow = ProjectionThread.mapFields(
|
||||
Struct.assign({
|
||||
modelSelection: Schema.fromJsonString(ModelSelection),
|
||||
}),
|
||||
);
|
||||
type ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type;
|
||||
|
||||
const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
@@ -23,7 +31,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
@@ -31,13 +39,14 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
latest_turn_id,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
${row.threadId},
|
||||
${row.projectId},
|
||||
${row.title},
|
||||
${row.model},
|
||||
${JSON.stringify(row.modelSelection)},
|
||||
${row.runtimeMode},
|
||||
${row.interactionMode},
|
||||
${row.branch},
|
||||
@@ -45,13 +54,14 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.latestTurnId},
|
||||
${row.createdAt},
|
||||
${row.updatedAt},
|
||||
${row.archivedAt},
|
||||
${row.deletedAt}
|
||||
)
|
||||
ON CONFLICT (thread_id)
|
||||
DO UPDATE SET
|
||||
project_id = excluded.project_id,
|
||||
title = excluded.title,
|
||||
model = excluded.model,
|
||||
model_selection_json = excluded.model_selection_json,
|
||||
runtime_mode = excluded.runtime_mode,
|
||||
interaction_mode = excluded.interaction_mode,
|
||||
branch = excluded.branch,
|
||||
@@ -59,20 +69,21 @@ 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
|
||||
`,
|
||||
});
|
||||
|
||||
const getProjectionThreadRow = SqlSchema.findOneOption({
|
||||
Request: GetProjectionThreadInput,
|
||||
Result: ProjectionThread,
|
||||
Result: ProjectionThreadDbRow,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
model,
|
||||
model_selection_json AS "modelSelection",
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
@@ -80,6 +91,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
latest_turn_id AS "latestTurnId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = ${threadId}
|
||||
@@ -88,14 +100,14 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
|
||||
const listProjectionThreadRows = SqlSchema.findAll({
|
||||
Request: ListProjectionThreadsByProjectInput,
|
||||
Result: ProjectionThread,
|
||||
Result: ProjectionThreadDbRow,
|
||||
execute: ({ projectId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
model,
|
||||
model_selection_json AS "modelSelection",
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
@@ -103,6 +115,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
latest_turn_id AS "latestTurnId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
WHERE project_id = ${projectId}
|
||||
|
||||
@@ -31,7 +31,7 @@ const setup = Layer.effectDiscard(
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`PRAGMA journal_mode = WAL;`;
|
||||
yield* sql`PRAGMA foreign_keys = ON;`;
|
||||
yield* runMigrations;
|
||||
yield* runMigrations();
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
import * as Migrator from "effect/unstable/sql/Migrator";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
// Import all migrations statically
|
||||
import Migration0001 from "./Migrations/001_OrchestrationEvents.ts";
|
||||
@@ -27,7 +28,9 @@ import Migration0012 from "./Migrations/012_ProjectionThreadsInteractionMode.ts"
|
||||
import Migration0013 from "./Migrations/013_ProjectionThreadProposedPlans.ts";
|
||||
import Migration0014 from "./Migrations/014_ProjectionThreadProposedPlanImplementation.ts";
|
||||
import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts";
|
||||
import { Effect } from "effect";
|
||||
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.
|
||||
@@ -39,23 +42,35 @@ import { Effect } from "effect";
|
||||
* Uses Migrator.fromRecord which parses the key format and
|
||||
* returns migrations sorted by ID.
|
||||
*/
|
||||
const loader = Migrator.fromRecord({
|
||||
"1_OrchestrationEvents": Migration0001,
|
||||
"2_OrchestrationCommandReceipts": Migration0002,
|
||||
"3_CheckpointDiffBlobs": Migration0003,
|
||||
"4_ProviderSessionRuntime": Migration0004,
|
||||
"5_Projections": Migration0005,
|
||||
"6_ProjectionThreadSessionRuntimeModeColumns": Migration0006,
|
||||
"7_ProjectionThreadMessageAttachments": Migration0007,
|
||||
"8_ProjectionThreadActivitySequence": Migration0008,
|
||||
"9_ProviderSessionRuntimeMode": Migration0009,
|
||||
"10_ProjectionThreadsRuntimeMode": Migration0010,
|
||||
"11_OrchestrationThreadCreatedRuntimeMode": Migration0011,
|
||||
"12_ProjectionThreadsInteractionMode": Migration0012,
|
||||
"13_ProjectionThreadProposedPlans": Migration0013,
|
||||
"14_ProjectionThreadProposedPlanImplementation": Migration0014,
|
||||
"15_ProjectionTurnsSourceProposedPlan": Migration0015,
|
||||
});
|
||||
export const migrationEntries = [
|
||||
[1, "OrchestrationEvents", Migration0001],
|
||||
[2, "OrchestrationCommandReceipts", Migration0002],
|
||||
[3, "CheckpointDiffBlobs", Migration0003],
|
||||
[4, "ProviderSessionRuntime", Migration0004],
|
||||
[5, "Projections", Migration0005],
|
||||
[6, "ProjectionThreadSessionRuntimeModeColumns", Migration0006],
|
||||
[7, "ProjectionThreadMessageAttachments", Migration0007],
|
||||
[8, "ProjectionThreadActivitySequence", Migration0008],
|
||||
[9, "ProviderSessionRuntimeMode", Migration0009],
|
||||
[10, "ProjectionThreadsRuntimeMode", Migration0010],
|
||||
[11, "OrchestrationThreadCreatedRuntimeMode", Migration0011],
|
||||
[12, "ProjectionThreadsInteractionMode", Migration0012],
|
||||
[13, "ProjectionThreadProposedPlans", Migration0013],
|
||||
[14, "ProjectionThreadProposedPlanImplementation", Migration0014],
|
||||
[15, "ProjectionTurnsSourceProposedPlan", Migration0015],
|
||||
[16, "CanonicalizeModelSelections", Migration0016],
|
||||
[17, "ProjectionThreadsArchivedAt", Migration0017],
|
||||
[18, "ProjectionThreadsArchivedAtIndex", Migration0018],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
Migrator.fromRecord(
|
||||
Object.fromEntries(
|
||||
migrationEntries
|
||||
.filter(([id]) => throughId === undefined || id <= throughId)
|
||||
.map(([id, name, migration]) => [`${id}_${name}`, migration]),
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* Migrator run function - no schema dumping needed
|
||||
@@ -63,6 +78,10 @@ const loader = Migrator.fromRecord({
|
||||
*/
|
||||
const run = Migrator.make({});
|
||||
|
||||
export interface RunMigrationsOptions {
|
||||
readonly toMigrationInclusive?: number | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run all pending migrations.
|
||||
*
|
||||
@@ -73,11 +92,19 @@ const run = Migrator.make({});
|
||||
*
|
||||
* @returns Effect containing array of executed migrations
|
||||
*/
|
||||
export const runMigrations = Effect.gen(function* () {
|
||||
yield* Effect.log("Running migrations...");
|
||||
yield* run({ loader });
|
||||
yield* Effect.log("Migrations ran successfully");
|
||||
});
|
||||
export const runMigrations = ({ toMigrationInclusive }: RunMigrationsOptions = {}) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.log(
|
||||
toMigrationInclusive === undefined
|
||||
? "Running all migrations..."
|
||||
: `Running migrations 1 through ${toMigrationInclusive}...`,
|
||||
);
|
||||
const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
|
||||
yield* Effect.log("Migrations ran successfully").pipe(
|
||||
Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }),
|
||||
);
|
||||
return executedMigrations;
|
||||
});
|
||||
|
||||
/**
|
||||
* Layer that runs migrations when the layer is built.
|
||||
@@ -96,4 +123,4 @@ export const runMigrations = Effect.gen(function* () {
|
||||
* )
|
||||
* ```
|
||||
*/
|
||||
export const MigrationsLive = Layer.effectDiscard(runMigrations);
|
||||
export const MigrationsLive = Layer.effectDiscard(runMigrations());
|
||||
@@ -0,0 +1,381 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { runMigrations } from "../Migrations.ts";
|
||||
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
|
||||
|
||||
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
|
||||
|
||||
layer("016_CanonicalizeModelSelections", (it) => {
|
||||
it.effect(
|
||||
"migrates legacy projection rows and event payloads to the canonical model-selection shape",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
// Setup base state
|
||||
{
|
||||
yield* runMigrations({ toMigrationInclusive: 15 });
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES
|
||||
('project-codex', 'Codex project', '/tmp/project-codex', 'gpt-5.4', '[]', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL),
|
||||
('project-claude', 'Claude project', '/tmp/project-claude', 'claude-sonnet-4-6', '[]', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL),
|
||||
('project-null', 'Null project', '/tmp/project-null', NULL, '[]', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL)
|
||||
`;
|
||||
yield* sql`
|
||||
UPDATE projection_projects
|
||||
SET default_model = 'claude-opus-4-6'
|
||||
WHERE project_id = 'project-claude'
|
||||
`;
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at,
|
||||
runtime_mode,
|
||||
interaction_mode
|
||||
)
|
||||
VALUES
|
||||
('thread-session', 'project-codex', 'Session thread', 'gpt-5.4', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, 'full-access', 'default'),
|
||||
('thread-claude', 'project-claude', 'Claude thread', 'claude-opus-4-6', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, 'full-access', 'default'),
|
||||
('thread-codex', 'project-codex', 'Codex thread', 'gpt-5.4', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, 'full-access', 'default'),
|
||||
('thread-legacy-options', 'project-claude', 'Legacy options thread', 'claude-opus-4-6', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, 'full-access', 'default')
|
||||
`;
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_sessions (
|
||||
thread_id,
|
||||
status,
|
||||
provider_name,
|
||||
provider_session_id,
|
||||
provider_thread_id,
|
||||
active_turn_id,
|
||||
last_error,
|
||||
updated_at,
|
||||
runtime_mode
|
||||
)
|
||||
VALUES (
|
||||
'thread-session',
|
||||
'running',
|
||||
'claudeAgent',
|
||||
'provider-session-1',
|
||||
'provider-thread-1',
|
||||
NULL,
|
||||
NULL,
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'full-access'
|
||||
)
|
||||
`;
|
||||
yield* sql`
|
||||
INSERT INTO orchestration_events (
|
||||
event_id,
|
||||
aggregate_kind,
|
||||
stream_id,
|
||||
stream_version,
|
||||
event_type,
|
||||
occurred_at,
|
||||
command_id,
|
||||
causation_event_id,
|
||||
correlation_id,
|
||||
actor_kind,
|
||||
payload_json,
|
||||
metadata_json
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'event-project-created',
|
||||
'project',
|
||||
'project-1',
|
||||
1,
|
||||
'project.created',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'command-project-created',
|
||||
NULL,
|
||||
'correlation-project-created',
|
||||
'user',
|
||||
'{"projectId":"project-1","title":"Project","workspaceRoot":"/tmp/project","defaultModel":"claude-opus-4-6","defaultModelOptions":{"codex":{"reasoningEffort":"high"},"claudeAgent":{"effort":"max"}},"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-project-created-fallback',
|
||||
'project',
|
||||
'project-2',
|
||||
1,
|
||||
'project.created',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'command-project-created-fallback',
|
||||
NULL,
|
||||
'correlation-project-created-fallback',
|
||||
'user',
|
||||
'{"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',
|
||||
'thread-1',
|
||||
1,
|
||||
'thread.created',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'command-thread-created',
|
||||
NULL,
|
||||
'correlation-thread-created',
|
||||
'user',
|
||||
'{"threadId":"thread-1","projectId":"project-1","title":"Thread","model":"claude-opus-4-6","modelOptions":{"codex":{"reasoningEffort":"high"},"claudeAgent":{"effort":"max","thinking":false}},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-thread-created-fallback',
|
||||
'thread',
|
||||
'thread-2',
|
||||
1,
|
||||
'thread.created',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'command-thread-created-fallback',
|
||||
NULL,
|
||||
'correlation-thread-created-fallback',
|
||||
'user',
|
||||
'{"threadId":"thread-2","projectId":"project-1","title":"Fallback Thread","model":"gpt-5.4","modelOptions":{"claudeAgent":{"effort":"max"}},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-turn-start-requested',
|
||||
'thread',
|
||||
'thread-1',
|
||||
2,
|
||||
'thread.turn-start-requested',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'command-turn-start-requested',
|
||||
NULL,
|
||||
'correlation-turn-start-requested',
|
||||
'user',
|
||||
'{"threadId":"thread-1","turnId":"turn-1","input":"hi","model":"gpt-5.4","modelOptions":{"codex":{"fastMode":true},"claudeAgent":{"effort":"max"}},"deliveryMode":"buffered"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-thread-created-no-model',
|
||||
'thread',
|
||||
'thread-3',
|
||||
1,
|
||||
'thread.created',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'command-thread-created-no-model',
|
||||
NULL,
|
||||
'correlation-thread-created-no-model',
|
||||
'user',
|
||||
'{"threadId":"thread-3","projectId":"project-1","title":"Ancient Thread","runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
)
|
||||
`;
|
||||
}
|
||||
|
||||
// Execute migration under test
|
||||
yield* runMigrations({ toMigrationInclusive: 16 });
|
||||
|
||||
// Assert expected state
|
||||
{
|
||||
const projectRows = yield* sql<{
|
||||
readonly projectId: string;
|
||||
readonly defaultModelSelection: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
project_id AS "projectId",
|
||||
default_model_selection_json AS "defaultModelSelection"
|
||||
FROM projection_projects
|
||||
ORDER BY project_id
|
||||
`;
|
||||
assert.deepStrictEqual(projectRows, [
|
||||
{
|
||||
projectId: "project-claude",
|
||||
defaultModelSelection: '{"provider":"claudeAgent","model":"claude-opus-4-6"}',
|
||||
},
|
||||
{
|
||||
projectId: "project-codex",
|
||||
defaultModelSelection: '{"provider":"codex","model":"gpt-5.4"}',
|
||||
},
|
||||
{ projectId: "project-null", defaultModelSelection: null },
|
||||
]);
|
||||
|
||||
const threadRows = yield* sql<{
|
||||
readonly threadId: string;
|
||||
readonly modelSelection: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
model_selection_json AS "modelSelection"
|
||||
FROM projection_threads
|
||||
ORDER BY thread_id
|
||||
`;
|
||||
assert.deepStrictEqual(threadRows, [
|
||||
{
|
||||
threadId: "thread-claude",
|
||||
modelSelection: '{"provider":"claudeAgent","model":"claude-opus-4-6"}',
|
||||
},
|
||||
{
|
||||
threadId: "thread-codex",
|
||||
modelSelection: '{"provider":"codex","model":"gpt-5.4"}',
|
||||
},
|
||||
{
|
||||
threadId: "thread-legacy-options",
|
||||
modelSelection: '{"provider":"claudeAgent","model":"claude-opus-4-6"}',
|
||||
},
|
||||
{
|
||||
threadId: "thread-session",
|
||||
modelSelection: '{"provider":"claudeAgent","model":"gpt-5.4"}',
|
||||
},
|
||||
]);
|
||||
|
||||
const eventRows = yield* sql<{
|
||||
readonly payloadJson: string;
|
||||
}>`
|
||||
SELECT payload_json AS "payloadJson"
|
||||
FROM orchestration_events
|
||||
ORDER BY rowid ASC
|
||||
`;
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[0]!.payloadJson), {
|
||||
projectId: "project-1",
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[1]!.payloadJson), {
|
||||
projectId: "project-2",
|
||||
title: "Fallback Project",
|
||||
workspaceRoot: "/tmp/project-2",
|
||||
defaultModelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
reasoningEffort: "low",
|
||||
},
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
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",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
thinking: false,
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[4]!.payloadJson), {
|
||||
threadId: "thread-2",
|
||||
projectId: "project-1",
|
||||
title: "Fallback Thread",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[5]!.payloadJson), {
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
input: "hi",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
deliveryMode: "buffered",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[6]!.payloadJson), {
|
||||
threadId: "thread-3",
|
||||
projectId: "project-1",
|
||||
title: "Ancient Thread",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,235 @@
|
||||
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`
|
||||
ALTER TABLE projection_projects
|
||||
ADD COLUMN default_model_selection_json TEXT
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_projects
|
||||
SET default_model_selection_json = CASE
|
||||
WHEN default_model IS NULL THEN NULL
|
||||
ELSE json_object(
|
||||
'provider',
|
||||
CASE
|
||||
WHEN lower(default_model) LIKE '%claude%' THEN 'claudeAgent'
|
||||
ELSE 'codex'
|
||||
END,
|
||||
'model',
|
||||
default_model
|
||||
)
|
||||
END
|
||||
WHERE default_model_selection_json IS NULL
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN model_selection_json TEXT
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_threads
|
||||
SET model_selection_json = json_object(
|
||||
'provider',
|
||||
COALESCE(
|
||||
(
|
||||
SELECT provider_name
|
||||
FROM projection_thread_sessions
|
||||
WHERE projection_thread_sessions.thread_id = projection_threads.thread_id
|
||||
),
|
||||
CASE
|
||||
WHEN lower(model) LIKE '%claude%' THEN 'claudeAgent'
|
||||
ELSE 'codex'
|
||||
END,
|
||||
'codex'
|
||||
),
|
||||
'model',
|
||||
model
|
||||
)
|
||||
WHERE model_selection_json IS NULL
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_projects
|
||||
DROP COLUMN default_model
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
DROP COLUMN model
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE orchestration_events
|
||||
SET payload_json = CASE
|
||||
WHEN json_type(payload_json, '$.defaultModel') = 'null' THEN json_remove(
|
||||
json_set(payload_json, '$.defaultModelSelection', json('null')),
|
||||
'$.defaultProvider',
|
||||
'$.defaultModel',
|
||||
'$.defaultModelOptions'
|
||||
)
|
||||
ELSE json_remove(
|
||||
json_set(
|
||||
payload_json,
|
||||
'$.defaultModelSelection',
|
||||
json_patch(
|
||||
json_object(
|
||||
'provider',
|
||||
CASE
|
||||
WHEN json_extract(payload_json, '$.defaultProvider') IS NOT NULL
|
||||
THEN json_extract(payload_json, '$.defaultProvider')
|
||||
WHEN lower(json_extract(payload_json, '$.defaultModel')) LIKE '%claude%'
|
||||
THEN 'claudeAgent'
|
||||
ELSE 'codex'
|
||||
END,
|
||||
'model',
|
||||
json_extract(payload_json, '$.defaultModel')
|
||||
),
|
||||
CASE
|
||||
WHEN json_type(payload_json, '$.defaultModelOptions') IS NULL THEN '{}'
|
||||
WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL
|
||||
OR json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL
|
||||
THEN CASE
|
||||
WHEN (
|
||||
CASE
|
||||
WHEN json_extract(payload_json, '$.defaultProvider') IS NOT NULL
|
||||
THEN json_extract(payload_json, '$.defaultProvider')
|
||||
WHEN lower(json_extract(payload_json, '$.defaultModel')) LIKE '%claude%'
|
||||
THEN 'claudeAgent'
|
||||
ELSE 'codex'
|
||||
END
|
||||
) = 'claudeAgent'
|
||||
THEN CASE
|
||||
WHEN json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.defaultModelOptions.claudeAgent'))
|
||||
)
|
||||
WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.defaultModelOptions.codex'))
|
||||
)
|
||||
ELSE '{}'
|
||||
END
|
||||
ELSE CASE
|
||||
WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.defaultModelOptions.codex'))
|
||||
)
|
||||
WHEN json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.defaultModelOptions.claudeAgent'))
|
||||
)
|
||||
ELSE '{}'
|
||||
END
|
||||
END
|
||||
ELSE json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.defaultModelOptions'))
|
||||
)
|
||||
END
|
||||
)
|
||||
),
|
||||
'$.defaultProvider',
|
||||
'$.defaultModel',
|
||||
'$.defaultModelOptions'
|
||||
)
|
||||
END
|
||||
WHERE event_type IN ('project.created', 'project.meta-updated')
|
||||
AND json_type(payload_json, '$.defaultModelSelection') IS NULL
|
||||
AND json_type(payload_json, '$.defaultModel') IS NOT NULL
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE orchestration_events
|
||||
SET payload_json = json_remove(
|
||||
json_set(
|
||||
payload_json,
|
||||
'$.modelSelection',
|
||||
json_patch(
|
||||
json_object(
|
||||
'provider',
|
||||
CASE
|
||||
WHEN json_extract(payload_json, '$.provider') IS NOT NULL
|
||||
THEN json_extract(payload_json, '$.provider')
|
||||
WHEN lower(json_extract(payload_json, '$.model')) LIKE '%claude%'
|
||||
THEN 'claudeAgent'
|
||||
ELSE 'codex'
|
||||
END,
|
||||
'model',
|
||||
json_extract(payload_json, '$.model')
|
||||
),
|
||||
CASE
|
||||
WHEN json_type(payload_json, '$.modelOptions') IS NULL THEN '{}'
|
||||
WHEN json_type(payload_json, '$.modelOptions.codex') IS NOT NULL
|
||||
OR json_type(payload_json, '$.modelOptions.claudeAgent') IS NOT NULL
|
||||
THEN CASE
|
||||
WHEN (
|
||||
CASE
|
||||
WHEN json_extract(payload_json, '$.provider') IS NOT NULL
|
||||
THEN json_extract(payload_json, '$.provider')
|
||||
WHEN lower(json_extract(payload_json, '$.model')) LIKE '%claude%'
|
||||
THEN 'claudeAgent'
|
||||
ELSE 'codex'
|
||||
END
|
||||
) = 'claudeAgent'
|
||||
THEN CASE
|
||||
WHEN json_type(payload_json, '$.modelOptions.claudeAgent') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.modelOptions.claudeAgent'))
|
||||
)
|
||||
WHEN json_type(payload_json, '$.modelOptions.codex') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.modelOptions.codex'))
|
||||
)
|
||||
ELSE '{}'
|
||||
END
|
||||
ELSE CASE
|
||||
WHEN json_type(payload_json, '$.modelOptions.codex') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.modelOptions.codex'))
|
||||
)
|
||||
WHEN json_type(payload_json, '$.modelOptions.claudeAgent') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.modelOptions.claudeAgent'))
|
||||
)
|
||||
ELSE '{}'
|
||||
END
|
||||
END
|
||||
ELSE json_object('options', json(json_extract(payload_json, '$.modelOptions')))
|
||||
END
|
||||
)
|
||||
),
|
||||
'$.provider',
|
||||
'$.model',
|
||||
'$.modelOptions'
|
||||
)
|
||||
WHERE event_type IN ('thread.created', 'thread.meta-updated', 'thread.turn-start-requested')
|
||||
AND json_type(payload_json, '$.modelSelection') IS NULL
|
||||
AND json_type(payload_json, '$.model') IS NOT NULL
|
||||
`;
|
||||
|
||||
// Backfill thread.created events that predate the model field entirely
|
||||
yield* sql`
|
||||
UPDATE orchestration_events
|
||||
SET payload_json = json_set(
|
||||
payload_json,
|
||||
'$.modelSelection',
|
||||
json(json_object('provider', 'codex', 'model', 'gpt-5.4'))
|
||||
)
|
||||
WHERE event_type = 'thread.created'
|
||||
AND json_type(payload_json, '$.modelSelection') IS NULL
|
||||
AND json_type(payload_json, '$.model') IS NULL
|
||||
`;
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const columns = yield* sql<{ readonly name: string }>`
|
||||
PRAGMA table_info(projection_threads)
|
||||
`;
|
||||
|
||||
if (columns.some((column) => column.name === "archived_at")) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN archived_at TEXT
|
||||
`;
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_projection_threads_project_archived_at
|
||||
ON projection_threads(project_id, archived_at)
|
||||
`;
|
||||
});
|
||||
@@ -20,7 +20,7 @@ import * as Stream from "effect/Stream";
|
||||
import * as Reactivity from "effect/unstable/reactivity/Reactivity";
|
||||
import * as Client from "effect/unstable/sql/SqlClient";
|
||||
import type { Connection } from "effect/unstable/sql/SqlConnection";
|
||||
import { SqlError } from "effect/unstable/sql/SqlError";
|
||||
import { SqlError, classifySqliteError } from "effect/unstable/sql/SqlError";
|
||||
import * as Statement from "effect/unstable/sql/Statement";
|
||||
|
||||
const ATTR_DB_SYSTEM_NAME = "db.system.name";
|
||||
@@ -109,7 +109,13 @@ const makeWithDatabase = (
|
||||
lookup: (sql: string) =>
|
||||
Effect.try({
|
||||
try: () => db.prepare(sql),
|
||||
catch: (cause) => new SqlError({ cause, message: "Failed to prepare statement" }),
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to prepare statement",
|
||||
operation: "prepare",
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -127,7 +133,14 @@ const makeWithDatabase = (
|
||||
const result = statement.run(...(params as any));
|
||||
return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
|
||||
} catch (cause) {
|
||||
return Effect.fail(new SqlError({ cause, message: "Failed to execute statement" }));
|
||||
return Effect.fail(
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to execute statement",
|
||||
operation: "execute",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -150,7 +163,13 @@ const makeWithDatabase = (
|
||||
statement.run(...(params as any));
|
||||
return [];
|
||||
},
|
||||
catch: (cause) => new SqlError({ cause, message: "Failed to execute statement" }),
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to execute statement",
|
||||
operation: "execute",
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
(statement) =>
|
||||
Effect.sync(() => {
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* @module ProjectionProjectRepository
|
||||
*/
|
||||
import { IsoDateTime, ProjectId, ProjectScript } from "@t3tools/contracts";
|
||||
import { IsoDateTime, ModelSelection, ProjectId, ProjectScript } from "@t3tools/contracts";
|
||||
import { Option, Schema, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
@@ -16,7 +16,7 @@ export const ProjectionProject = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: Schema.String,
|
||||
workspaceRoot: Schema.String,
|
||||
defaultModel: Schema.NullOr(Schema.String),
|
||||
defaultModelSelection: Schema.NullOr(ModelSelection),
|
||||
scripts: Schema.Array(ProjectScript),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
*/
|
||||
import {
|
||||
IsoDateTime,
|
||||
ModelSelection,
|
||||
ProjectId,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
@@ -23,7 +24,7 @@ export const ProjectionThread = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
projectId: ProjectId,
|
||||
title: Schema.String,
|
||||
model: Schema.String,
|
||||
modelSelection: ModelSelection,
|
||||
runtimeMode: RuntimeMode,
|
||||
interactionMode: ProviderInteractionMode,
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
@@ -31,6 +32,7 @@ export const ProjectionThread = Schema.Struct({
|
||||
latestTurnId: Schema.NullOr(TurnId),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
archivedAt: Schema.NullOr(IsoDateTime),
|
||||
deletedAt: Schema.NullOr(IsoDateTime),
|
||||
});
|
||||
export type ProjectionThread = typeof ProjectionThread.Type;
|
||||
|
||||
@@ -37,7 +37,7 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un
|
||||
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
|
||||
}
|
||||
|
||||
function isWindowsCommandNotFound(code: number | null, stderr: string): boolean {
|
||||
export 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);
|
||||
|
||||
@@ -21,6 +21,7 @@ import { Effect, Fiber, Layer, Random, Stream } from "effect";
|
||||
|
||||
import { attachmentRelativePath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderAdapterValidationError } from "../Errors.ts";
|
||||
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
|
||||
import { makeClaudeAdapterLive, type ClaudeAdapterLiveOptions } from "./ClaudeAdapter.ts";
|
||||
@@ -168,6 +169,7 @@ function makeHarness(config?: {
|
||||
config?.baseDir ?? "/tmp",
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
query,
|
||||
@@ -301,7 +303,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("keeps explicit claude permission mode over runtime-derived defaults", () => {
|
||||
it.effect("uses bypass permissions for full-access claude sessions", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
@@ -309,16 +311,11 @@ describe("ClaudeAdapterLive", () => {
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
providerOptions: {
|
||||
claudeAgent: {
|
||||
permissionMode: "plan",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.permissionMode, "plan");
|
||||
assert.equal(createInput?.options.allowDangerouslySkipPermissions, undefined);
|
||||
assert.equal(createInput?.options.permissionMode, "bypassPermissions");
|
||||
assert.equal(createInput?.options.allowDangerouslySkipPermissions, true);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
@@ -332,13 +329,14 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
@@ -349,24 +347,25 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("ignores unsupported max effort for Sonnet 4.6", () => {
|
||||
it.effect("falls back to default effort when unsupported max is requested for Sonnet 4.6", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.effort, undefined);
|
||||
assert.equal(createInput?.options.effort, "high");
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
@@ -380,13 +379,14 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
options: {
|
||||
effort: "high",
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
@@ -404,13 +404,14 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
options: {
|
||||
thinking: false,
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
@@ -430,13 +431,14 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
thinking: false,
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
@@ -454,13 +456,14 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
@@ -480,13 +483,14 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
@@ -504,29 +508,31 @@ describe("ClaudeAdapterLive", () => {
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "ultrathink",
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "Investigate the edge cases",
|
||||
attachments: [],
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "ultrathink",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.effort, undefined);
|
||||
assert.equal(createInput?.options.effort, "high");
|
||||
const promptText = yield* Effect.promise(() => readFirstPromptText(createInput));
|
||||
assert.equal(promptText, "Ultrathink:\nInvestigate the edge cases");
|
||||
}).pipe(
|
||||
@@ -613,7 +619,10 @@ describe("ClaudeAdapterLive", () => {
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-5",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-5",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
@@ -1091,10 +1100,13 @@ describe("ClaudeAdapterLive", () => {
|
||||
it.effect("closes the session when the Claude stream aborts after a turn starts", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const services = yield* Effect.services();
|
||||
const runFork = Effect.runForkWith(services);
|
||||
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
|
||||
|
||||
const runtimeEventsFiber = Effect.runFork(
|
||||
const runtimeEventsFiber = runFork(
|
||||
Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
@@ -1183,13 +1195,17 @@ describe("ClaudeAdapterLive", () => {
|
||||
},
|
||||
}).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const services = yield* Effect.services();
|
||||
const runFork = Effect.runForkWith(services);
|
||||
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = Effect.runFork(
|
||||
const runtimeEventsFiber = runFork(
|
||||
Stream.runForEach(adapter.streamEvents, () => Effect.void),
|
||||
);
|
||||
|
||||
@@ -1225,7 +1241,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 5).pipe(
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
@@ -1267,6 +1283,127 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("emits thread token usage updates from Claude task progress", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
harness.query.emit({
|
||||
type: "system",
|
||||
subtype: "task_progress",
|
||||
task_id: "task-usage-1",
|
||||
description: "Thinking through the patch",
|
||||
usage: {
|
||||
total_tokens: 321,
|
||||
tool_uses: 2,
|
||||
duration_ms: 654,
|
||||
},
|
||||
session_id: "sdk-session-task-usage",
|
||||
uuid: "task-usage-progress-1",
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
const usageEvent = runtimeEvents.find((event) => event.type === "thread.token-usage.updated");
|
||||
const progressEvent = runtimeEvents.find((event) => event.type === "task.progress");
|
||||
assert.equal(usageEvent?.type, "thread.token-usage.updated");
|
||||
if (usageEvent?.type === "thread.token-usage.updated") {
|
||||
assert.deepEqual(usageEvent.payload, {
|
||||
usage: {
|
||||
usedTokens: 321,
|
||||
lastUsedTokens: 321,
|
||||
toolUses: 2,
|
||||
durationMs: 654,
|
||||
},
|
||||
});
|
||||
}
|
||||
assert.equal(progressEvent?.type, "task.progress");
|
||||
if (usageEvent && progressEvent) {
|
||||
assert.notStrictEqual(usageEvent.eventId, progressEvent.eventId);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("emits Claude context window on result completion usage snapshots", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 7).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: THREAD_ID,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
duration_ms: 1234,
|
||||
duration_api_ms: 1200,
|
||||
num_turns: 1,
|
||||
result: "done",
|
||||
stop_reason: "end_turn",
|
||||
session_id: "sdk-session-result-usage",
|
||||
usage: {
|
||||
input_tokens: 4,
|
||||
cache_creation_input_tokens: 2715,
|
||||
cache_read_input_tokens: 21144,
|
||||
output_tokens: 679,
|
||||
},
|
||||
modelUsage: {
|
||||
"claude-opus-4-6": {
|
||||
contextWindow: 200000,
|
||||
maxOutputTokens: 64000,
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
harness.query.finish();
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
const usageEvent = runtimeEvents.find((event) => event.type === "thread.token-usage.updated");
|
||||
assert.equal(usageEvent?.type, "thread.token-usage.updated");
|
||||
if (usageEvent?.type === "thread.token-usage.updated") {
|
||||
assert.deepEqual(usageEvent.payload, {
|
||||
usage: {
|
||||
usedTokens: 24542,
|
||||
lastUsedTokens: 24542,
|
||||
inputTokens: 23863,
|
||||
outputTokens: 679,
|
||||
maxTokens: 200000,
|
||||
},
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"emits completion only after turn result when assistant frames arrive before deltas",
|
||||
() => {
|
||||
@@ -2239,7 +2376,10 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello",
|
||||
model: "claude-opus-4-6",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
},
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
@@ -2250,6 +2390,85 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"does not re-set the Claude model when the session already uses the same effective API model",
|
||||
() => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
const modelSelection = {
|
||||
provider: "claudeAgent" as const,
|
||||
model: "claude-opus-4-6",
|
||||
};
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello",
|
||||
modelSelection,
|
||||
attachments: [],
|
||||
});
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello again",
|
||||
modelSelection,
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
assert.deepEqual(harness.query.setModelCalls, []);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("re-sets the Claude model when the effective API model changes", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
contextWindow: "1m",
|
||||
},
|
||||
},
|
||||
attachments: [],
|
||||
});
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello again",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
},
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6[1m]", "claude-opus-4-6"]);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("sets plan permission mode on sendTurn when interactionMode is plan", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,388 @@
|
||||
import type {
|
||||
ClaudeSettings,
|
||||
ClaudeModelOptions,
|
||||
ModelCapabilities,
|
||||
ServerProvider,
|
||||
ServerProviderModel,
|
||||
ServerProviderAuthStatus,
|
||||
ServerProviderState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Equal, Layer, Option, Result, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { resolveContextWindow, resolveEffort } from "@t3tools/shared/model";
|
||||
|
||||
import {
|
||||
buildServerProvider,
|
||||
DEFAULT_TIMEOUT_MS,
|
||||
detailFromResult,
|
||||
extractAuthBoolean,
|
||||
isCommandMissingCause,
|
||||
parseGenericCliVersion,
|
||||
providerModelsFromSettings,
|
||||
spawnAndCollect,
|
||||
type CommandResult,
|
||||
} from "../providerSnapshot";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider";
|
||||
import { ClaudeProvider } from "../Services/ClaudeProvider";
|
||||
import { ServerSettingsError, ServerSettingsService } from "../../serverSettings";
|
||||
|
||||
const PROVIDER = "claudeAgent" as const;
|
||||
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Claude Opus 4.6",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
{
|
||||
slug: "claude-sonnet-4-6",
|
||||
name: "Claude Sonnet 4.6",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
{
|
||||
slug: "claude-haiku-4-5",
|
||||
name: "Claude Haiku 4.5",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
];
|
||||
|
||||
export function getClaudeModelCapabilities(model: string | null | undefined): ModelCapabilities {
|
||||
const slug = model?.trim();
|
||||
return (
|
||||
BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ?? {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export function normalizeClaudeModelOptions(
|
||||
model: string | null | undefined,
|
||||
modelOptions: ClaudeModelOptions | null | undefined,
|
||||
): ClaudeModelOptions | undefined {
|
||||
const caps = getClaudeModelCapabilities(model);
|
||||
const effort = resolveEffort(caps, modelOptions?.effort);
|
||||
const thinking =
|
||||
caps.supportsThinkingToggle && modelOptions?.thinking === false ? false : undefined;
|
||||
const fastMode = caps.supportsFastMode && modelOptions?.fastMode === true ? true : undefined;
|
||||
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
|
||||
const nextOptions: ClaudeModelOptions = {
|
||||
...(thinking === false ? { thinking: false } : {}),
|
||||
...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
...(contextWindow ? { contextWindow } : {}),
|
||||
};
|
||||
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
|
||||
}
|
||||
|
||||
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
|
||||
readonly status: Exclude<ServerProviderState, "disabled">;
|
||||
readonly authStatus: ServerProviderAuthStatus;
|
||||
readonly message?: string;
|
||||
} {
|
||||
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
|
||||
|
||||
if (
|
||||
lowerOutput.includes("unknown command") ||
|
||||
lowerOutput.includes("unrecognized command") ||
|
||||
lowerOutput.includes("unexpected argument")
|
||||
) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
"Claude Agent authentication status command is unavailable in this version of Claude.",
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
lowerOutput.includes("not logged in") ||
|
||||
lowerOutput.includes("login required") ||
|
||||
lowerOutput.includes("authentication required") ||
|
||||
lowerOutput.includes("run `claude login`") ||
|
||||
lowerOutput.includes("run claude login")
|
||||
) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
message: "Claude is not authenticated. Run `claude auth login` and try again.",
|
||||
};
|
||||
}
|
||||
|
||||
const parsedAuth = (() => {
|
||||
const trimmed = result.stdout.trim();
|
||||
if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
|
||||
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
|
||||
}
|
||||
try {
|
||||
return {
|
||||
attemptedJsonParse: true as const,
|
||||
auth: extractAuthBoolean(JSON.parse(trimmed)),
|
||||
};
|
||||
} catch {
|
||||
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
|
||||
}
|
||||
})();
|
||||
|
||||
if (parsedAuth.auth === true) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
}
|
||||
if (parsedAuth.auth === false) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
message: "Claude is not authenticated. Run `claude auth login` and try again.",
|
||||
};
|
||||
}
|
||||
if (parsedAuth.attemptedJsonParse) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
"Could not verify Claude authentication status from JSON output (missing auth marker).",
|
||||
};
|
||||
}
|
||||
if (result.code === 0) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
}
|
||||
|
||||
const detail = detailFromResult(result);
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: detail
|
||||
? `Could not verify Claude authentication status. ${detail}`
|
||||
: "Could not verify Claude authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
const runClaudeCommand = (args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
|
||||
Effect.flatMap((service) => service.getSettings),
|
||||
Effect.map((settings) => settings.providers.claudeAgent),
|
||||
);
|
||||
const command = ChildProcess.make(claudeSettings.binaryPath, [...args], {
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
return yield* spawnAndCollect(claudeSettings.binaryPath, command);
|
||||
});
|
||||
|
||||
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
function* (): Effect.fn.Return<
|
||||
ServerProvider,
|
||||
ServerSettingsError,
|
||||
ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
|
||||
> {
|
||||
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
|
||||
Effect.flatMap((service) => service.getSettings),
|
||||
Effect.map((settings) => settings.providers.claudeAgent),
|
||||
);
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(
|
||||
BUILT_IN_MODELS,
|
||||
PROVIDER,
|
||||
claudeSettings.customModels,
|
||||
);
|
||||
|
||||
if (!claudeSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Claude is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: !isCommandMissingCause(error),
|
||||
version: null,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: isCommandMissingCause(error)
|
||||
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
|
||||
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (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,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: parsed.status,
|
||||
authStatus: parsed.authStatus,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
export const ClaudeProviderLive = Layer.effect(
|
||||
ClaudeProvider,
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const checkProvider = checkClaudeProviderStatus().pipe(
|
||||
Effect.provideService(ServerSettingsService, serverSettings),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
|
||||
return yield* makeManagedServerProvider<ClaudeSettings>({
|
||||
getSettings: serverSettings.getSettings.pipe(
|
||||
Effect.map((settings) => settings.providers.claudeAgent),
|
||||
Effect.orDie,
|
||||
),
|
||||
streamSettings: serverSettings.streamChanges.pipe(
|
||||
Stream.map((settings) => settings.providers.claudeAgent),
|
||||
),
|
||||
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
|
||||
checkProvider,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
type CodexAppServerSendTurnInput,
|
||||
} from "../../codexAppServerManager.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderAdapterValidationError } from "../Errors.ts";
|
||||
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
@@ -151,6 +152,7 @@ const validationManager = new FakeCodexManager();
|
||||
const validationLayer = it.layer(
|
||||
makeCodexAdapterLive({ manager: validationManager }).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
@@ -188,9 +190,10 @@ validationLayer("CodexAdapterLive validation", (it) => {
|
||||
yield* adapter.startSession({
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
@@ -200,6 +203,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
|
||||
assert.deepStrictEqual(validationManager.startSessionImpl.mock.calls[0]?.[0], {
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
binaryPath: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
serviceTier: "fast",
|
||||
runtimeMode: "full-access",
|
||||
@@ -215,6 +219,7 @@ sessionErrorManager.sendTurnImpl.mockImplementation(async () => {
|
||||
const sessionErrorLayer = it.layer(
|
||||
makeCodexAdapterLive({ manager: sessionErrorManager }).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
@@ -256,9 +261,10 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
||||
adapter.sendTurn({
|
||||
threadId: asThreadId("sess-missing"),
|
||||
input: "hello",
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -282,6 +288,7 @@ const lifecycleManager = new FakeCodexManager();
|
||||
const lifecycleLayer = it.layer(
|
||||
makeCodexAdapterLive({ manager: lifecycleManager }).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
@@ -467,6 +474,40 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps process stderr notifications to runtime.warning", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
|
||||
|
||||
lifecycleManager.emit("event", {
|
||||
id: asEventId("evt-process-stderr"),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "process/stderr",
|
||||
turnId: asTurnId("turn-1"),
|
||||
message: "The filename or extension is too long. (os error 206)",
|
||||
} satisfies ProviderEvent);
|
||||
|
||||
const firstEvent = yield* Fiber.join(firstEventFiber);
|
||||
|
||||
assert.equal(firstEvent._tag, "Some");
|
||||
if (firstEvent._tag !== "Some") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.type, "runtime.warning");
|
||||
if (firstEvent.value.type !== "runtime.warning") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.turnId, "turn-1");
|
||||
assert.equal(
|
||||
firstEvent.value.payload.message,
|
||||
"The filename or extension is too long. (os error 206)",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves request type when mapping serverRequest/resolved", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
@@ -839,6 +880,70 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||
assert.equal(firstEvent.value.payload.taskId, "turn-child");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("unwraps Codex token usage payloads for context window events", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
|
||||
|
||||
lifecycleManager.emit("event", {
|
||||
id: asEventId("evt-codex-thread-token-usage-updated"),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "thread/tokenUsage/updated",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
tokenUsage: {
|
||||
total: {
|
||||
inputTokens: 11_833,
|
||||
cachedInputTokens: 3456,
|
||||
outputTokens: 6,
|
||||
reasoningOutputTokens: 0,
|
||||
totalTokens: 11_839,
|
||||
},
|
||||
last: {
|
||||
inputTokens: 120,
|
||||
cachedInputTokens: 0,
|
||||
outputTokens: 6,
|
||||
reasoningOutputTokens: 0,
|
||||
totalTokens: 126,
|
||||
},
|
||||
modelContextWindow: 258_400,
|
||||
},
|
||||
},
|
||||
} satisfies ProviderEvent);
|
||||
|
||||
const firstEvent = yield* Fiber.join(firstEventFiber);
|
||||
assert.equal(firstEvent._tag, "Some");
|
||||
if (firstEvent._tag !== "Some") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.type, "thread.token-usage.updated");
|
||||
if (firstEvent.value.type !== "thread.token-usage.updated") {
|
||||
return;
|
||||
}
|
||||
|
||||
assert.deepEqual(firstEvent.value.payload.usage, {
|
||||
usedTokens: 126,
|
||||
totalProcessedTokens: 11_839,
|
||||
maxTokens: 258_400,
|
||||
inputTokens: 120,
|
||||
cachedInputTokens: 0,
|
||||
outputTokens: 6,
|
||||
reasoningOutputTokens: 0,
|
||||
lastUsedTokens: 126,
|
||||
lastInputTokens: 120,
|
||||
lastCachedInputTokens: 0,
|
||||
lastOutputTokens: 6,
|
||||
lastReasoningOutputTokens: 0,
|
||||
compactsAutomatically: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
type CanonicalRequestType,
|
||||
type ProviderEvent,
|
||||
type ProviderRuntimeEvent,
|
||||
type ThreadTokenUsageSnapshot,
|
||||
type ProviderUserInputAnswers,
|
||||
RuntimeItemId,
|
||||
RuntimeRequestId,
|
||||
@@ -19,6 +20,7 @@ import {
|
||||
ProviderItemId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
ProviderSendTurnInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, FileSystem, Layer, Queue, Schema, ServiceMap, Stream } from "effect";
|
||||
|
||||
@@ -37,6 +39,7 @@ import {
|
||||
} from "../../codexAppServerManager.ts";
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
|
||||
const PROVIDER = "codex" as const;
|
||||
@@ -109,6 +112,48 @@ function asNumber(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function normalizeCodexTokenUsage(value: unknown): ThreadTokenUsageSnapshot | undefined {
|
||||
const usage = asObject(value);
|
||||
const totalUsage = asObject(usage?.total_token_usage ?? usage?.total);
|
||||
const lastUsage = asObject(usage?.last_token_usage ?? usage?.last);
|
||||
|
||||
const totalProcessedTokens =
|
||||
asNumber(totalUsage?.total_tokens) ?? asNumber(totalUsage?.totalTokens);
|
||||
const usedTokens =
|
||||
asNumber(lastUsage?.total_tokens) ?? asNumber(lastUsage?.totalTokens) ?? totalProcessedTokens;
|
||||
if (usedTokens === undefined || usedTokens <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const maxTokens = asNumber(usage?.model_context_window) ?? asNumber(usage?.modelContextWindow);
|
||||
const inputTokens = asNumber(lastUsage?.input_tokens) ?? asNumber(lastUsage?.inputTokens);
|
||||
const cachedInputTokens =
|
||||
asNumber(lastUsage?.cached_input_tokens) ?? asNumber(lastUsage?.cachedInputTokens);
|
||||
const outputTokens = asNumber(lastUsage?.output_tokens) ?? asNumber(lastUsage?.outputTokens);
|
||||
const reasoningOutputTokens =
|
||||
asNumber(lastUsage?.reasoning_output_tokens) ?? asNumber(lastUsage?.reasoningOutputTokens);
|
||||
|
||||
return {
|
||||
usedTokens,
|
||||
...(totalProcessedTokens !== undefined && totalProcessedTokens > usedTokens
|
||||
? { totalProcessedTokens }
|
||||
: {}),
|
||||
...(maxTokens !== undefined ? { maxTokens } : {}),
|
||||
...(inputTokens !== undefined ? { inputTokens } : {}),
|
||||
...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),
|
||||
...(outputTokens !== undefined ? { outputTokens } : {}),
|
||||
...(reasoningOutputTokens !== undefined ? { reasoningOutputTokens } : {}),
|
||||
...(usedTokens !== undefined ? { lastUsedTokens: usedTokens } : {}),
|
||||
...(inputTokens !== undefined ? { lastInputTokens: inputTokens } : {}),
|
||||
...(cachedInputTokens !== undefined ? { lastCachedInputTokens: cachedInputTokens } : {}),
|
||||
...(outputTokens !== undefined ? { lastOutputTokens: outputTokens } : {}),
|
||||
...(reasoningOutputTokens !== undefined
|
||||
? { lastReasoningOutputTokens: reasoningOutputTokens }
|
||||
: {}),
|
||||
compactsAutomatically: true,
|
||||
};
|
||||
}
|
||||
|
||||
function toTurnId(value: string | undefined): TurnId | undefined {
|
||||
return value?.trim() ? TurnId.makeUnsafe(value) : undefined;
|
||||
}
|
||||
@@ -708,12 +753,17 @@ function mapToRuntimeEvents(
|
||||
}
|
||||
|
||||
if (event.method === "thread/tokenUsage/updated") {
|
||||
const tokenUsage = asObject(payload?.tokenUsage);
|
||||
const normalizedUsage = normalizeCodexTokenUsage(tokenUsage ?? event.payload);
|
||||
if (!normalizedUsage) {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
{
|
||||
type: "thread.token-usage.updated",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
usage: event.payload ?? {},
|
||||
usage: normalizedUsage,
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -1218,6 +1268,19 @@ function mapToRuntimeEvents(
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "process/stderr") {
|
||||
return [
|
||||
{
|
||||
type: "runtime.warning",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
message: event.message ?? "Codex process stderr",
|
||||
...(event.payload !== undefined ? { detail: event.payload } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "windows/worldWritableWarning") {
|
||||
return [
|
||||
{
|
||||
@@ -1265,59 +1328,79 @@ function mapToRuntimeEvents(
|
||||
return [];
|
||||
}
|
||||
|
||||
const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
(options?.nativeEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
|
||||
stream: "native",
|
||||
})
|
||||
: undefined);
|
||||
const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
options?: CodexAdapterLiveOptions,
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
(options?.nativeEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
|
||||
stream: "native",
|
||||
})
|
||||
: undefined);
|
||||
|
||||
const manager = yield* Effect.acquireRelease(
|
||||
Effect.gen(function* () {
|
||||
if (options?.manager) {
|
||||
return options.manager;
|
||||
}
|
||||
const services = yield* Effect.services<never>();
|
||||
return options?.makeManager?.(services) ?? new CodexAppServerManager(services);
|
||||
}),
|
||||
(manager) =>
|
||||
Effect.sync(() => {
|
||||
try {
|
||||
manager.stopAll();
|
||||
} catch {
|
||||
// Finalizers should never fail and block shutdown.
|
||||
}
|
||||
}),
|
||||
);
|
||||
const acquireManager = Effect.fn("acquireManager")(function* () {
|
||||
if (options?.manager) {
|
||||
return options.manager;
|
||||
}
|
||||
const services = yield* Effect.services<never>();
|
||||
return options?.makeManager?.(services) ?? new CodexAppServerManager(services);
|
||||
});
|
||||
|
||||
const startSession: CodexAdapterShape["startSession"] = (input) => {
|
||||
const manager = yield* Effect.acquireRelease(acquireManager(), (manager) =>
|
||||
Effect.sync(() => {
|
||||
try {
|
||||
manager.stopAll();
|
||||
} catch {
|
||||
// Finalizers should never fail and block shutdown.
|
||||
}
|
||||
}),
|
||||
);
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
|
||||
const startSession: CodexAdapterShape["startSession"] = Effect.fn("startSession")(
|
||||
function* (input) {
|
||||
if (input.provider !== undefined && input.provider !== PROVIDER) {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "startSession",
|
||||
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
|
||||
}),
|
||||
);
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "startSession",
|
||||
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
const codexSettings = yield* serverSettingsService.getSettings.pipe(
|
||||
Effect.map((settings) => settings.providers.codex),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
detail: error.message,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const binaryPath = codexSettings.binaryPath;
|
||||
const homePath = codexSettings.homePath;
|
||||
const managerInput: CodexAppServerStartSessionInput = {
|
||||
threadId: input.threadId,
|
||||
provider: "codex",
|
||||
...(input.cwd !== undefined ? { cwd: input.cwd } : {}),
|
||||
...(input.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
|
||||
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
|
||||
runtimeMode: input.runtimeMode,
|
||||
...(input.model !== undefined ? { model: input.model } : {}),
|
||||
...(input.modelOptions?.codex?.fastMode ? { serviceTier: "fast" } : {}),
|
||||
binaryPath,
|
||||
...(homePath ? { homePath } : {}),
|
||||
...(input.modelSelection?.provider === "codex"
|
||||
? { model: input.modelSelection.model }
|
||||
: {}),
|
||||
...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode
|
||||
? { serviceTier: "fast" }
|
||||
: {}),
|
||||
};
|
||||
|
||||
return Effect.tryPromise({
|
||||
return yield* Effect.tryPromise({
|
||||
try: () => manager.startSession(managerInput),
|
||||
catch: (cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
@@ -1326,206 +1409,213 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
detail: toMessage(cause, "Failed to start Codex adapter session."),
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.map((session) => session));
|
||||
};
|
||||
|
||||
const sendTurn: CodexAdapterShape["sendTurn"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const codexAttachments = yield* Effect.forEach(
|
||||
input.attachments ?? [],
|
||||
(attachment) =>
|
||||
Effect.gen(function* () {
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* toRequestError(
|
||||
input.threadId,
|
||||
"turn/start",
|
||||
new Error(`Invalid attachment id '${attachment.id}'.`),
|
||||
);
|
||||
}
|
||||
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "turn/start",
|
||||
detail: toMessage(cause, "Failed to read attachment file."),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return {
|
||||
type: "image" as const,
|
||||
url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`,
|
||||
};
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
return yield* Effect.tryPromise({
|
||||
try: () => {
|
||||
const managerInput = {
|
||||
threadId: input.threadId,
|
||||
...(input.input !== undefined ? { input: input.input } : {}),
|
||||
...(input.model !== undefined ? { model: input.model } : {}),
|
||||
...(input.modelOptions?.codex?.reasoningEffort !== undefined
|
||||
? { effort: input.modelOptions.codex.reasoningEffort }
|
||||
: {}),
|
||||
...(input.modelOptions?.codex?.fastMode ? { serviceTier: "fast" } : {}),
|
||||
...(input.interactionMode !== undefined
|
||||
? { interactionMode: input.interactionMode }
|
||||
: {}),
|
||||
...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),
|
||||
};
|
||||
return manager.sendTurn(managerInput);
|
||||
},
|
||||
catch: (cause) => toRequestError(input.threadId, "turn/start", cause),
|
||||
}).pipe(
|
||||
Effect.map((result) => ({
|
||||
...result,
|
||||
threadId: input.threadId,
|
||||
})),
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const interruptTurn: CodexAdapterShape["interruptTurn"] = (threadId, turnId) =>
|
||||
Effect.tryPromise({
|
||||
try: () => manager.interruptTurn(threadId, turnId),
|
||||
catch: (cause) => toRequestError(threadId, "turn/interrupt", cause),
|
||||
});
|
||||
|
||||
const readThread: CodexAdapterShape["readThread"] = (threadId) =>
|
||||
Effect.tryPromise({
|
||||
try: () => manager.readThread(threadId),
|
||||
catch: (cause) => toRequestError(threadId, "thread/read", cause),
|
||||
}).pipe(
|
||||
Effect.map((snapshot) => ({
|
||||
threadId,
|
||||
turns: snapshot.turns,
|
||||
})),
|
||||
const resolveAttachment = Effect.fn("resolveAttachment")(function* (
|
||||
input: ProviderSendTurnInput,
|
||||
attachment: NonNullable<ProviderSendTurnInput["attachments"]>[number],
|
||||
) {
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* toRequestError(
|
||||
input.threadId,
|
||||
"turn/start",
|
||||
new Error(`Invalid attachment id '${attachment.id}'.`),
|
||||
);
|
||||
|
||||
const rollbackThread: CodexAdapterShape["rollbackThread"] = (threadId, numTurns) => {
|
||||
if (!Number.isInteger(numTurns) || numTurns < 1) {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterValidationError({
|
||||
}
|
||||
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
operation: "rollbackThread",
|
||||
issue: "numTurns must be an integer >= 1.",
|
||||
method: "turn/start",
|
||||
detail: toMessage(cause, "Failed to read attachment file."),
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.tryPromise({
|
||||
try: () => manager.rollbackThread(threadId, numTurns),
|
||||
catch: (cause) => toRequestError(threadId, "thread/rollback", cause),
|
||||
}).pipe(
|
||||
Effect.map((snapshot) => ({
|
||||
threadId,
|
||||
turns: snapshot.turns,
|
||||
})),
|
||||
);
|
||||
),
|
||||
);
|
||||
return {
|
||||
type: "image" as const,
|
||||
url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`,
|
||||
};
|
||||
});
|
||||
|
||||
const respondToRequest: CodexAdapterShape["respondToRequest"] = (
|
||||
threadId,
|
||||
requestId,
|
||||
decision,
|
||||
) =>
|
||||
Effect.tryPromise({
|
||||
try: () => manager.respondToRequest(threadId, requestId, decision),
|
||||
catch: (cause) => toRequestError(threadId, "item/requestApproval/decision", cause),
|
||||
});
|
||||
|
||||
const respondToUserInput: CodexAdapterShape["respondToUserInput"] = (
|
||||
threadId,
|
||||
requestId,
|
||||
answers,
|
||||
) =>
|
||||
Effect.tryPromise({
|
||||
try: () => manager.respondToUserInput(threadId, requestId, answers),
|
||||
catch: (cause) => toRequestError(threadId, "item/tool/requestUserInput", cause),
|
||||
});
|
||||
|
||||
const stopSession: CodexAdapterShape["stopSession"] = (threadId) =>
|
||||
Effect.sync(() => {
|
||||
manager.stopSession(threadId);
|
||||
});
|
||||
|
||||
const listSessions: CodexAdapterShape["listSessions"] = () =>
|
||||
Effect.sync(() => manager.listSessions());
|
||||
|
||||
const hasSession: CodexAdapterShape["hasSession"] = (threadId) =>
|
||||
Effect.sync(() => manager.hasSession(threadId));
|
||||
|
||||
const stopAll: CodexAdapterShape["stopAll"] = () =>
|
||||
Effect.sync(() => {
|
||||
manager.stopAll();
|
||||
});
|
||||
|
||||
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.gen(function* () {
|
||||
const writeNativeEvent = (event: ProviderEvent) =>
|
||||
Effect.gen(function* () {
|
||||
if (!nativeEventLogger) {
|
||||
return;
|
||||
}
|
||||
yield* nativeEventLogger.write(event, event.threadId);
|
||||
});
|
||||
|
||||
const services = yield* Effect.services<never>();
|
||||
const listener = (event: ProviderEvent) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeNativeEvent(event);
|
||||
const runtimeEvents = mapToRuntimeEvents(event, event.threadId);
|
||||
if (runtimeEvents.length === 0) {
|
||||
yield* Effect.logDebug("ignoring unhandled Codex provider event", {
|
||||
method: event.method,
|
||||
threadId: event.threadId,
|
||||
turnId: event.turnId,
|
||||
itemId: event.itemId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
yield* Queue.offerAll(runtimeEventQueue, runtimeEvents);
|
||||
}).pipe(Effect.runPromiseWith(services));
|
||||
manager.on("event", listener);
|
||||
return listener;
|
||||
}),
|
||||
(listener) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.sync(() => {
|
||||
manager.off("event", listener);
|
||||
});
|
||||
yield* Queue.shutdown(runtimeEventQueue);
|
||||
}),
|
||||
const sendTurn: CodexAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {
|
||||
const codexAttachments = yield* Effect.forEach(
|
||||
input.attachments ?? [],
|
||||
(attachment) => resolveAttachment(input, attachment),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
return {
|
||||
provider: PROVIDER,
|
||||
capabilities: {
|
||||
sessionModelSwitch: "in-session",
|
||||
return yield* Effect.tryPromise({
|
||||
try: () => {
|
||||
const managerInput = {
|
||||
threadId: input.threadId,
|
||||
...(input.input !== undefined ? { input: input.input } : {}),
|
||||
...(input.modelSelection?.provider === "codex"
|
||||
? { model: input.modelSelection.model }
|
||||
: {}),
|
||||
...(input.modelSelection?.provider === "codex" &&
|
||||
input.modelSelection.options?.reasoningEffort !== undefined
|
||||
? { effort: input.modelSelection.options.reasoningEffort }
|
||||
: {}),
|
||||
...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode
|
||||
? { serviceTier: "fast" }
|
||||
: {}),
|
||||
...(input.interactionMode !== undefined
|
||||
? { interactionMode: input.interactionMode }
|
||||
: {}),
|
||||
...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),
|
||||
};
|
||||
return manager.sendTurn(managerInput);
|
||||
},
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
readThread,
|
||||
rollbackThread,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions,
|
||||
hasSession,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromQueue(runtimeEventQueue),
|
||||
} satisfies CodexAdapterShape;
|
||||
catch: (cause) => toRequestError(input.threadId, "turn/start", cause),
|
||||
}).pipe(
|
||||
Effect.map((result) => ({
|
||||
...result,
|
||||
threadId: input.threadId,
|
||||
})),
|
||||
);
|
||||
});
|
||||
|
||||
const interruptTurn: CodexAdapterShape["interruptTurn"] = (threadId, turnId) =>
|
||||
Effect.tryPromise({
|
||||
try: () => manager.interruptTurn(threadId, turnId),
|
||||
catch: (cause) => toRequestError(threadId, "turn/interrupt", cause),
|
||||
});
|
||||
|
||||
const readThread: CodexAdapterShape["readThread"] = (threadId) =>
|
||||
Effect.tryPromise({
|
||||
try: () => manager.readThread(threadId),
|
||||
catch: (cause) => toRequestError(threadId, "thread/read", cause),
|
||||
}).pipe(
|
||||
Effect.map((snapshot) => ({
|
||||
threadId,
|
||||
turns: snapshot.turns,
|
||||
})),
|
||||
);
|
||||
|
||||
const rollbackThread: CodexAdapterShape["rollbackThread"] = (threadId, numTurns) => {
|
||||
if (!Number.isInteger(numTurns) || numTurns < 1) {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "rollbackThread",
|
||||
issue: "numTurns must be an integer >= 1.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.tryPromise({
|
||||
try: () => manager.rollbackThread(threadId, numTurns),
|
||||
catch: (cause) => toRequestError(threadId, "thread/rollback", cause),
|
||||
}).pipe(
|
||||
Effect.map((snapshot) => ({
|
||||
threadId,
|
||||
turns: snapshot.turns,
|
||||
})),
|
||||
);
|
||||
};
|
||||
|
||||
const respondToRequest: CodexAdapterShape["respondToRequest"] = (threadId, requestId, decision) =>
|
||||
Effect.tryPromise({
|
||||
try: () => manager.respondToRequest(threadId, requestId, decision),
|
||||
catch: (cause) => toRequestError(threadId, "item/requestApproval/decision", cause),
|
||||
});
|
||||
|
||||
const respondToUserInput: CodexAdapterShape["respondToUserInput"] = (
|
||||
threadId,
|
||||
requestId,
|
||||
answers,
|
||||
) =>
|
||||
Effect.tryPromise({
|
||||
try: () => manager.respondToUserInput(threadId, requestId, answers),
|
||||
catch: (cause) => toRequestError(threadId, "item/tool/requestUserInput", cause),
|
||||
});
|
||||
|
||||
const stopSession: CodexAdapterShape["stopSession"] = (threadId) =>
|
||||
Effect.sync(() => {
|
||||
manager.stopSession(threadId);
|
||||
});
|
||||
|
||||
const listSessions: CodexAdapterShape["listSessions"] = () =>
|
||||
Effect.sync(() => manager.listSessions());
|
||||
|
||||
const hasSession: CodexAdapterShape["hasSession"] = (threadId) =>
|
||||
Effect.sync(() => manager.hasSession(threadId));
|
||||
|
||||
const stopAll: CodexAdapterShape["stopAll"] = () =>
|
||||
Effect.sync(() => {
|
||||
manager.stopAll();
|
||||
});
|
||||
|
||||
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
|
||||
const writeNativeEvent = Effect.fn("writeNativeEvent")(function* (event: ProviderEvent) {
|
||||
if (!nativeEventLogger) {
|
||||
return;
|
||||
}
|
||||
yield* nativeEventLogger.write(event, event.threadId);
|
||||
});
|
||||
|
||||
const registerListener = Effect.fn("registerListener")(function* () {
|
||||
const services = yield* Effect.services<never>();
|
||||
const listenerEffect = Effect.fn("listener")(function* (event: ProviderEvent) {
|
||||
yield* writeNativeEvent(event);
|
||||
const runtimeEvents = mapToRuntimeEvents(event, event.threadId);
|
||||
if (runtimeEvents.length === 0) {
|
||||
yield* Effect.logDebug("ignoring unhandled Codex provider event", {
|
||||
method: event.method,
|
||||
threadId: event.threadId,
|
||||
turnId: event.turnId,
|
||||
itemId: event.itemId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
yield* Queue.offerAll(runtimeEventQueue, runtimeEvents);
|
||||
});
|
||||
const listener = (event: ProviderEvent) =>
|
||||
listenerEffect(event).pipe(Effect.runPromiseWith(services));
|
||||
manager.on("event", listener);
|
||||
return listener;
|
||||
});
|
||||
|
||||
const unregisterListener = Effect.fn("unregisterListener")(function* (
|
||||
listener: (event: ProviderEvent) => Promise<void>,
|
||||
) {
|
||||
yield* Effect.sync(() => {
|
||||
manager.off("event", listener);
|
||||
});
|
||||
yield* Queue.shutdown(runtimeEventQueue);
|
||||
});
|
||||
|
||||
yield* Effect.acquireRelease(registerListener(), unregisterListener);
|
||||
|
||||
return {
|
||||
provider: PROVIDER,
|
||||
capabilities: {
|
||||
sessionModelSwitch: "in-session",
|
||||
},
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
readThread,
|
||||
rollbackThread,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions,
|
||||
hasSession,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromQueue(runtimeEventQueue),
|
||||
} satisfies CodexAdapterShape;
|
||||
});
|
||||
|
||||
export const CodexAdapterLive = Layer.effect(CodexAdapter, makeCodexAdapter());
|
||||
|
||||
export function makeCodexAdapterLive(options?: CodexAdapterLiveOptions) {
|
||||
|
||||
@@ -0,0 +1,525 @@
|
||||
import * as OS from "node:os";
|
||||
import type {
|
||||
ModelCapabilities,
|
||||
CodexModelOptions,
|
||||
CodexSettings,
|
||||
ServerProvider,
|
||||
ServerProviderModel,
|
||||
ServerProviderAuthStatus,
|
||||
ServerProviderState,
|
||||
} from "@t3tools/contracts";
|
||||
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,
|
||||
DEFAULT_TIMEOUT_MS,
|
||||
detailFromResult,
|
||||
extractAuthBoolean,
|
||||
isCommandMissingCause,
|
||||
parseGenericCliVersion,
|
||||
providerModelsFromSettings,
|
||||
spawnAndCollect,
|
||||
type CommandResult,
|
||||
} from "../providerSnapshot";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider";
|
||||
import {
|
||||
formatCodexCliUpgradeMessage,
|
||||
isCodexCliVersionSupported,
|
||||
parseCodexCliVersion,
|
||||
} from "../codexCliVersion";
|
||||
import { CodexProvider } from "../Services/CodexProvider";
|
||||
import { ServerSettingsError, ServerSettingsService } from "../../serverSettings";
|
||||
|
||||
const PROVIDER = "codex" as const;
|
||||
const OPENAI_AUTH_PROVIDERS = new Set(["openai"]);
|
||||
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
{
|
||||
slug: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "low", label: "Low" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.4-mini",
|
||||
name: "GPT-5.4 Mini",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "low", label: "Low" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.3-codex",
|
||||
name: "GPT-5.3 Codex",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "low", label: "Low" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.3-codex-spark",
|
||||
name: "GPT-5.3 Codex Spark",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "low", label: "Low" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.2-codex",
|
||||
name: "GPT-5.2 Codex",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "low", label: "Low" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.2",
|
||||
name: "GPT-5.2",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "low", label: "Low" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export function getCodexModelCapabilities(model: string | null | undefined): ModelCapabilities {
|
||||
const slug = model?.trim();
|
||||
return (
|
||||
BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ?? {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export function normalizeCodexModelOptions(
|
||||
model: string | null | undefined,
|
||||
modelOptions: CodexModelOptions | null | undefined,
|
||||
): CodexModelOptions | undefined {
|
||||
const caps = getCodexModelCapabilities(model);
|
||||
const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort);
|
||||
const fastModeEnabled = modelOptions?.fastMode === true;
|
||||
const nextOptions: CodexModelOptions = {
|
||||
...(reasoningEffort
|
||||
? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] }
|
||||
: {}),
|
||||
...(fastModeEnabled ? { fastMode: true } : {}),
|
||||
};
|
||||
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
|
||||
}
|
||||
|
||||
export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
readonly status: Exclude<ServerProviderState, "disabled">;
|
||||
readonly authStatus: ServerProviderAuthStatus;
|
||||
readonly message?: string;
|
||||
} {
|
||||
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
|
||||
|
||||
if (
|
||||
lowerOutput.includes("unknown command") ||
|
||||
lowerOutput.includes("unrecognized command") ||
|
||||
lowerOutput.includes("unexpected argument")
|
||||
) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Codex CLI authentication status command is unavailable in this Codex version.",
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
lowerOutput.includes("not logged in") ||
|
||||
lowerOutput.includes("login required") ||
|
||||
lowerOutput.includes("authentication required") ||
|
||||
lowerOutput.includes("run `codex login`") ||
|
||||
lowerOutput.includes("run codex login")
|
||||
) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
};
|
||||
}
|
||||
|
||||
const parsedAuth = (() => {
|
||||
const trimmed = result.stdout.trim();
|
||||
if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
|
||||
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
|
||||
}
|
||||
try {
|
||||
return {
|
||||
attemptedJsonParse: true as const,
|
||||
auth: extractAuthBoolean(JSON.parse(trimmed)),
|
||||
};
|
||||
} catch {
|
||||
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
|
||||
}
|
||||
})();
|
||||
|
||||
if (parsedAuth.auth === true) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
}
|
||||
if (parsedAuth.auth === false) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
};
|
||||
}
|
||||
if (parsedAuth.attemptedJsonParse) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
"Could not verify Codex authentication status from JSON output (missing auth marker).",
|
||||
};
|
||||
}
|
||||
if (result.code === 0) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
}
|
||||
|
||||
const detail = detailFromResult(result);
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: detail
|
||||
? `Could not verify Codex authentication status. ${detail}`
|
||||
: "Could not verify Codex authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
export const readCodexConfigModelProvider = Effect.fn("readCodexConfigModelProvider")(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const settingsService = yield* ServerSettingsService;
|
||||
const codexHome = yield* settingsService.getSettings.pipe(
|
||||
Effect.map(
|
||||
(settings) =>
|
||||
settings.providers.codex.homePath ||
|
||||
process.env.CODEX_HOME ||
|
||||
path.join(OS.homedir(), ".codex"),
|
||||
),
|
||||
);
|
||||
const configPath = path.join(codexHome, "config.toml");
|
||||
|
||||
const content = yield* fileSystem
|
||||
.readFileString(configPath)
|
||||
.pipe(Effect.orElseSucceed(() => undefined));
|
||||
if (content === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let inTopLevel = true;
|
||||
for (const line of content.split("\n")) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith("#")) continue;
|
||||
if (trimmed.startsWith("[")) {
|
||||
inTopLevel = false;
|
||||
continue;
|
||||
}
|
||||
if (!inTopLevel) continue;
|
||||
|
||||
const match = trimmed.match(/^model_provider\s*=\s*["']([^"']+)["']/);
|
||||
if (match) return match[1];
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
|
||||
export const hasCustomModelProvider = readCodexConfigModelProvider().pipe(
|
||||
Effect.map((provider) => provider !== undefined && !OPENAI_AUTH_PROVIDERS.has(provider)),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
|
||||
const runCodexCommand = (args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const settingsService = yield* ServerSettingsService;
|
||||
const codexSettings = yield* settingsService.getSettings.pipe(
|
||||
Effect.map((settings) => settings.providers.codex),
|
||||
);
|
||||
const command = ChildProcess.make(codexSettings.binaryPath, [...args], {
|
||||
shell: process.platform === "win32",
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexSettings.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
|
||||
},
|
||||
});
|
||||
return yield* spawnAndCollect(codexSettings.binaryPath, command);
|
||||
});
|
||||
|
||||
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(
|
||||
function* (): Effect.fn.Return<
|
||||
ServerProvider,
|
||||
ServerSettingsError,
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| Path.Path
|
||||
| ServerSettingsService
|
||||
> {
|
||||
const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
|
||||
Effect.flatMap((service) => service.getSettings),
|
||||
Effect.map((settings) => settings.providers.codex),
|
||||
);
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(
|
||||
BUILT_IN_MODELS,
|
||||
PROVIDER,
|
||||
codexSettings.customModels,
|
||||
);
|
||||
|
||||
if (!codexSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Codex is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: !isCommandMissingCause(error),
|
||||
version: null,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: isCommandMissingCause(error)
|
||||
? "Codex CLI (`codex`) is not installed or not on PATH."
|
||||
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (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,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: parsed.status,
|
||||
authStatus: parsed.authStatus,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
export const CodexProviderLive = Layer.effect(
|
||||
CodexProvider,
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const checkProvider = checkCodexProviderStatus().pipe(
|
||||
Effect.provideService(ServerSettingsService, serverSettings),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
|
||||
return yield* makeManagedServerProvider<CodexSettings>({
|
||||
getSettings: serverSettings.getSettings.pipe(
|
||||
Effect.map((settings) => settings.providers.codex),
|
||||
Effect.orDie,
|
||||
),
|
||||
streamSettings: serverSettings.streamChanges.pipe(
|
||||
Stream.map((settings) => settings.providers.codex),
|
||||
),
|
||||
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
|
||||
checkProvider,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1,640 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, it, assert } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path, Sink, Stream } from "effect";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
checkClaudeProviderStatus,
|
||||
checkCodexProviderStatus,
|
||||
hasCustomModelProvider,
|
||||
parseAuthStatusFromOutput,
|
||||
parseClaudeAuthStatusFromOutput,
|
||||
readCodexConfigModelProvider,
|
||||
} from "./ProviderHealth";
|
||||
|
||||
// ── Test helpers ────────────────────────────────────────────────────
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
function mockHandle(result: { stdout: string; stderr: string; code: number }) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.make(encoder.encode(result.stdout)),
|
||||
stderr: Stream.make(encoder.encode(result.stderr)),
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
}
|
||||
|
||||
function mockSpawnerLayer(
|
||||
handler: (args: ReadonlyArray<string>) => { stdout: string; stderr: string; code: number },
|
||||
) {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const cmd = command as unknown as { args: ReadonlyArray<string> };
|
||||
return Effect.succeed(mockHandle(handler(cmd.args)));
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function failingSpawnerLayer(description: string) {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "ChildProcess",
|
||||
method: "spawn",
|
||||
description,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a temporary CODEX_HOME scoped to the current Effect test.
|
||||
* Cleanup is registered in the test scope rather than via Vitest hooks.
|
||||
*/
|
||||
function withTempCodexHome(configContent?: string) {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tmpDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-test-codex-" });
|
||||
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
const originalCodexHome = process.env.CODEX_HOME;
|
||||
process.env.CODEX_HOME = tmpDir;
|
||||
return originalCodexHome;
|
||||
}),
|
||||
(originalCodexHome) =>
|
||||
Effect.sync(() => {
|
||||
if (originalCodexHome !== undefined) {
|
||||
process.env.CODEX_HOME = originalCodexHome;
|
||||
} else {
|
||||
delete process.env.CODEX_HOME;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
if (configContent !== undefined) {
|
||||
yield* fileSystem.writeFileString(path.join(tmpDir, "config.toml"), configContent);
|
||||
}
|
||||
|
||||
return { tmpDir } as const;
|
||||
});
|
||||
}
|
||||
|
||||
it.layer(NodeServices.layer)("ProviderHealth", (it) => {
|
||||
// ── checkCodexProviderStatus tests ────────────────────────────────
|
||||
//
|
||||
// These tests control CODEX_HOME to ensure the custom-provider detection
|
||||
// in hasCustomModelProvider() does not interfere with the auth-probe
|
||||
// path being tested.
|
||||
|
||||
describe("checkCodexProviderStatus", () => {
|
||||
it.effect("returns ready when codex is installed and authenticated", () =>
|
||||
Effect.gen(function* () {
|
||||
// Point CODEX_HOME at an empty tmp dir (no config.toml) so the
|
||||
// default code path (OpenAI provider, auth probe runs) is exercised.
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when codex is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, false);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(status.message, "Codex CLI (`codex`) is not installed or not on PATH.");
|
||||
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when codex is below the minimum supported version", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, false);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 0.36.0\n", stderr: "", code: 0 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unauthenticated when auth probe reports login required", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") {
|
||||
return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unauthenticated when login status output includes 'not logged in'", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status")
|
||||
return { stdout: "Not logged in\n", stderr: "", code: 1 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns warning when login status command is unsupported", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "warning");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI authentication status command is unavailable in this Codex version.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") {
|
||||
return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
// ── Custom model provider: checkCodexProviderStatus integration ───
|
||||
|
||||
describe("checkCodexProviderStatus with custom model provider", () => {
|
||||
it.effect("skips auth probe and returns ready when a custom model provider is configured", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome(
|
||||
[
|
||||
'model_provider = "portkey"',
|
||||
"",
|
||||
"[model_providers.portkey]",
|
||||
'base_url = "https://api.portkey.ai/v1"',
|
||||
'env_key = "PORTKEY_API_KEY"',
|
||||
].join("\n"),
|
||||
);
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Using a custom Codex model provider; OpenAI login check skipped.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
// The spawner only handles --version; if the test attempts
|
||||
// "login status" the throw proves the auth probe was NOT skipped.
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
throw new Error(`Auth probe should have been skipped but got args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("still reports error when codex CLI is missing even with custom provider", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome(
|
||||
[
|
||||
'model_provider = "portkey"',
|
||||
"",
|
||||
"[model_providers.portkey]",
|
||||
'base_url = "https://api.portkey.ai/v1"',
|
||||
'env_key = "PORTKEY_API_KEY"',
|
||||
].join("\n"),
|
||||
);
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, false);
|
||||
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
|
||||
);
|
||||
});
|
||||
|
||||
describe("checkCodexProviderStatus with openai model provider", () => {
|
||||
it.effect("still runs auth probe when model_provider is openai", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model_provider = "openai"\n');
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
// The auth probe runs and sees "not logged in" → error
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status")
|
||||
return { stdout: "Not logged in\n", stderr: "", code: 1 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
// ── parseAuthStatusFromOutput pure tests ──────────────────────────
|
||||
|
||||
describe("parseAuthStatusFromOutput", () => {
|
||||
it("exit code 0 with no auth markers is ready", () => {
|
||||
const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
|
||||
assert.strictEqual(parsed.status, "ready");
|
||||
assert.strictEqual(parsed.authStatus, "authenticated");
|
||||
});
|
||||
|
||||
it("JSON with authenticated=false is unauthenticated", () => {
|
||||
const parsed = parseAuthStatusFromOutput({
|
||||
stdout: '[{"authenticated":false}]\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "error");
|
||||
assert.strictEqual(parsed.authStatus, "unauthenticated");
|
||||
});
|
||||
|
||||
it("JSON without auth marker is warning", () => {
|
||||
const parsed = parseAuthStatusFromOutput({
|
||||
stdout: '[{"ok":true}]\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "warning");
|
||||
assert.strictEqual(parsed.authStatus, "unknown");
|
||||
});
|
||||
});
|
||||
|
||||
// ── readCodexConfigModelProvider tests ─────────────────────────────
|
||||
|
||||
describe("readCodexConfigModelProvider", () => {
|
||||
it.effect("returns undefined when config file does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider, undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns undefined when config has no model_provider key", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model = "gpt-5-codex"\n');
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider, undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns the provider when model_provider is set at top level", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model = "gpt-5-codex"\nmodel_provider = "portkey"\n');
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider, "portkey");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns openai when model_provider is openai", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model_provider = "openai"\n');
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider, "openai");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ignores model_provider inside section headers", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome(
|
||||
[
|
||||
'model = "gpt-5-codex"',
|
||||
"",
|
||||
"[model_providers.portkey]",
|
||||
'base_url = "https://api.portkey.ai/v1"',
|
||||
'model_provider = "should-be-ignored"',
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider, undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("handles comments and whitespace", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome(
|
||||
[
|
||||
"# This is a comment",
|
||||
"",
|
||||
' model_provider = "azure" ',
|
||||
"",
|
||||
"[profiles.deep-review]",
|
||||
'model = "gpt-5-pro"',
|
||||
].join("\n"),
|
||||
);
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider, "azure");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("handles single-quoted values in TOML", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome("model_provider = 'mistral'\n");
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider, "mistral");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── hasCustomModelProvider tests ───────────────────────────────────
|
||||
|
||||
describe("hasCustomModelProvider", () => {
|
||||
it.effect("returns false when no config file exists", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
assert.strictEqual(yield* hasCustomModelProvider, false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns false when model_provider is not set", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model = "gpt-5-codex"\n');
|
||||
assert.strictEqual(yield* hasCustomModelProvider, false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns false when model_provider is openai", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model_provider = "openai"\n');
|
||||
assert.strictEqual(yield* hasCustomModelProvider, false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns true when model_provider is portkey", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model_provider = "portkey"\n');
|
||||
assert.strictEqual(yield* hasCustomModelProvider, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns true when model_provider is azure", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model_provider = "azure"\n');
|
||||
assert.strictEqual(yield* hasCustomModelProvider, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns true when model_provider is ollama", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model_provider = "ollama"\n');
|
||||
assert.strictEqual(yield* hasCustomModelProvider, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns true when model_provider is a custom proxy", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model_provider = "my-company-proxy"\n');
|
||||
assert.strictEqual(yield* hasCustomModelProvider, true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── checkClaudeProviderStatus tests ──────────────────────────
|
||||
|
||||
describe("checkClaudeProviderStatus", () => {
|
||||
it.effect("returns ready when claude is installed and authenticated", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when claude is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, false);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude Agent CLI (`claude`) is not installed or not on PATH.",
|
||||
);
|
||||
}).pipe(Effect.provide(failingSpawnerLayer("spawn claude ENOENT"))),
|
||||
);
|
||||
|
||||
it.effect("returns error when version check fails with non-zero exit code", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, false);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version")
|
||||
return { stdout: "", stderr: "Something went wrong", code: 1 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unauthenticated when auth status reports not logged in", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude is not authenticated. Run `claude auth login` and try again.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":false}\n',
|
||||
stderr: "",
|
||||
code: 1,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unauthenticated when output includes 'not logged in'", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status") return { stdout: "Not logged in\n", stderr: "", code: 1 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns warning when auth status command is unsupported", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "warning");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude Agent authentication status command is unavailable in this version of Claude.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return { stdout: "", stderr: "error: unknown command 'auth'", code: 2 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
// ── parseClaudeAuthStatusFromOutput pure tests ────────────────────
|
||||
|
||||
describe("parseClaudeAuthStatusFromOutput", () => {
|
||||
it("exit code 0 with no auth markers is ready", () => {
|
||||
const parsed = parseClaudeAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
|
||||
assert.strictEqual(parsed.status, "ready");
|
||||
assert.strictEqual(parsed.authStatus, "authenticated");
|
||||
});
|
||||
|
||||
it("JSON with loggedIn=true is authenticated", () => {
|
||||
const parsed = parseClaudeAuthStatusFromOutput({
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "ready");
|
||||
assert.strictEqual(parsed.authStatus, "authenticated");
|
||||
});
|
||||
|
||||
it("JSON with loggedIn=false is unauthenticated", () => {
|
||||
const parsed = parseClaudeAuthStatusFromOutput({
|
||||
stdout: '{"loggedIn":false}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "error");
|
||||
assert.strictEqual(parsed.authStatus, "unauthenticated");
|
||||
});
|
||||
|
||||
it("JSON without auth marker is warning", () => {
|
||||
const parsed = parseClaudeAuthStatusFromOutput({
|
||||
stdout: '{"ok":true}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "warning");
|
||||
assert.strictEqual(parsed.authStatus, "unknown");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,603 +0,0 @@
|
||||
/**
|
||||
* ProviderHealthLive - Startup-time provider health checks.
|
||||
*
|
||||
* Performs one-time provider readiness probes when the server starts and
|
||||
* keeps the resulting snapshot in memory for `server.getConfig`.
|
||||
*
|
||||
* Uses effect's ChildProcessSpawner to run CLI probes natively.
|
||||
*
|
||||
* @module ProviderHealthLive
|
||||
*/
|
||||
import * as OS from "node:os";
|
||||
import type {
|
||||
ServerProviderAuthStatus,
|
||||
ServerProviderStatus,
|
||||
ServerProviderStatusState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Array, Effect, Fiber, FileSystem, Layer, Option, Path, Result, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
formatCodexCliUpgradeMessage,
|
||||
isCodexCliVersionSupported,
|
||||
parseCodexCliVersion,
|
||||
} from "../codexCliVersion";
|
||||
import { ProviderHealth, type ProviderHealthShape } from "../Services/ProviderHealth";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 4_000;
|
||||
const CODEX_PROVIDER = "codex" as const;
|
||||
const CLAUDE_AGENT_PROVIDER = "claudeAgent" as const;
|
||||
|
||||
// ── Pure helpers ────────────────────────────────────────────────────
|
||||
|
||||
export interface CommandResult {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly code: number;
|
||||
}
|
||||
|
||||
function nonEmptyTrimmed(value: string | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function isCommandMissingCause(error: unknown): boolean {
|
||||
if (!(error instanceof Error)) return false;
|
||||
const lower = error.message.toLowerCase();
|
||||
return lower.includes("enoent") || lower.includes("notfound");
|
||||
}
|
||||
|
||||
function detailFromResult(
|
||||
result: CommandResult & { readonly timedOut?: boolean },
|
||||
): string | undefined {
|
||||
if (result.timedOut) return "Timed out while running command.";
|
||||
const stderr = nonEmptyTrimmed(result.stderr);
|
||||
if (stderr) return stderr;
|
||||
const stdout = nonEmptyTrimmed(result.stdout);
|
||||
if (stdout) return stdout;
|
||||
if (result.code !== 0) {
|
||||
return `Command exited with code ${result.code}.`;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function extractAuthBoolean(value: unknown): boolean | undefined {
|
||||
if (Array.isArray(value)) {
|
||||
for (const entry of value) {
|
||||
const nested = extractAuthBoolean(entry);
|
||||
if (nested !== undefined) return nested;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (!value || typeof value !== "object") return undefined;
|
||||
|
||||
const record = value as Record<string, unknown>;
|
||||
for (const key of ["authenticated", "isAuthenticated", "loggedIn", "isLoggedIn"] as const) {
|
||||
if (typeof record[key] === "boolean") return record[key];
|
||||
}
|
||||
for (const key of ["auth", "status", "session", "account"] as const) {
|
||||
const nested = extractAuthBoolean(record[key]);
|
||||
if (nested !== undefined) return nested;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
readonly status: ServerProviderStatusState;
|
||||
readonly authStatus: ServerProviderAuthStatus;
|
||||
readonly message?: string;
|
||||
} {
|
||||
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
|
||||
|
||||
if (
|
||||
lowerOutput.includes("unknown command") ||
|
||||
lowerOutput.includes("unrecognized command") ||
|
||||
lowerOutput.includes("unexpected argument")
|
||||
) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Codex CLI authentication status command is unavailable in this Codex version.",
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
lowerOutput.includes("not logged in") ||
|
||||
lowerOutput.includes("login required") ||
|
||||
lowerOutput.includes("authentication required") ||
|
||||
lowerOutput.includes("run `codex login`") ||
|
||||
lowerOutput.includes("run codex login")
|
||||
) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
};
|
||||
}
|
||||
|
||||
const parsedAuth = (() => {
|
||||
const trimmed = result.stdout.trim();
|
||||
if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
|
||||
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
|
||||
}
|
||||
try {
|
||||
return {
|
||||
attemptedJsonParse: true as const,
|
||||
auth: extractAuthBoolean(JSON.parse(trimmed)),
|
||||
};
|
||||
} catch {
|
||||
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
|
||||
}
|
||||
})();
|
||||
|
||||
if (parsedAuth.auth === true) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
}
|
||||
if (parsedAuth.auth === false) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
};
|
||||
}
|
||||
if (parsedAuth.attemptedJsonParse) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
"Could not verify Codex authentication status from JSON output (missing auth marker).",
|
||||
};
|
||||
}
|
||||
if (result.code === 0) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
}
|
||||
|
||||
const detail = detailFromResult(result);
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: detail
|
||||
? `Could not verify Codex authentication status. ${detail}`
|
||||
: "Could not verify Codex authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
// ── Codex CLI config detection ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Providers that use OpenAI-native authentication via `codex login`.
|
||||
* When the configured `model_provider` is one of these, the `codex login
|
||||
* status` probe still runs. For any other provider value the auth probe
|
||||
* is skipped because authentication is handled externally (e.g. via
|
||||
* environment variables like `PORTKEY_API_KEY` or `AZURE_API_KEY`).
|
||||
*/
|
||||
const OPENAI_AUTH_PROVIDERS = new Set(["openai"]);
|
||||
|
||||
/**
|
||||
* Read the `model_provider` value from the Codex CLI config file.
|
||||
*
|
||||
* Looks for the file at `$CODEX_HOME/config.toml` (falls back to
|
||||
* `~/.codex/config.toml`). Uses a simple line-by-line scan rather than
|
||||
* a full TOML parser to avoid adding a dependency for a single key.
|
||||
*
|
||||
* Returns `undefined` when the file does not exist or does not set
|
||||
* `model_provider`.
|
||||
*/
|
||||
export const readCodexConfigModelProvider = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const codexHome = process.env.CODEX_HOME || path.join(OS.homedir(), ".codex");
|
||||
const configPath = path.join(codexHome, "config.toml");
|
||||
|
||||
const content = yield* fileSystem
|
||||
.readFileString(configPath)
|
||||
.pipe(Effect.orElseSucceed(() => undefined));
|
||||
if (content === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// We need to find `model_provider = "..."` at the top level of the
|
||||
// TOML file (i.e. before any `[section]` header). Lines inside
|
||||
// `[profiles.*]`, `[model_providers.*]`, etc. are ignored.
|
||||
let inTopLevel = true;
|
||||
for (const line of content.split("\n")) {
|
||||
const trimmed = line.trim();
|
||||
// Skip comments and empty lines.
|
||||
if (!trimmed || trimmed.startsWith("#")) continue;
|
||||
// Detect section headers — once we leave the top level, stop.
|
||||
if (trimmed.startsWith("[")) {
|
||||
inTopLevel = false;
|
||||
continue;
|
||||
}
|
||||
if (!inTopLevel) continue;
|
||||
|
||||
const match = trimmed.match(/^model_provider\s*=\s*["']([^"']+)["']/);
|
||||
if (match) return match[1];
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
|
||||
/**
|
||||
* Returns `true` when the Codex CLI is configured with a custom
|
||||
* (non-OpenAI) model provider, meaning `codex login` auth is not
|
||||
* required because authentication is handled through provider-specific
|
||||
* environment variables.
|
||||
*/
|
||||
export const hasCustomModelProvider = Effect.map(
|
||||
readCodexConfigModelProvider,
|
||||
(provider) => provider !== undefined && !OPENAI_AUTH_PROVIDERS.has(provider),
|
||||
);
|
||||
|
||||
// ── Effect-native command execution ─────────────────────────────────
|
||||
|
||||
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
|
||||
Stream.runFold(
|
||||
stream,
|
||||
() => "",
|
||||
(acc, chunk) => acc + new TextDecoder().decode(chunk),
|
||||
);
|
||||
|
||||
const runCodexCommand = (args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make("codex", [...args], {
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
|
||||
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" },
|
||||
);
|
||||
|
||||
return { stdout, stderr, code: exitCode } satisfies CommandResult;
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
const runClaudeCommand = (args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make("claude", [...args], {
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
|
||||
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" },
|
||||
);
|
||||
|
||||
return { stdout, stderr, code: exitCode } satisfies CommandResult;
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
// ── Health check ────────────────────────────────────────────────────
|
||||
|
||||
export const checkCodexProviderStatus: Effect.Effect<
|
||||
ServerProviderStatus,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
|
||||
> = Effect.gen(function* () {
|
||||
const checkedAt = new Date().toISOString();
|
||||
|
||||
// Probe 1: `codex --version` — is the CLI reachable?
|
||||
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
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 {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: "Codex CLI is installed but failed to run. Timed out while running command.",
|
||||
};
|
||||
}
|
||||
|
||||
const version = versionProbe.success.value;
|
||||
if (version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: detail
|
||||
? `Codex CLI is installed but failed to run. ${detail}`
|
||||
: "Codex CLI is installed but failed to run.",
|
||||
};
|
||||
}
|
||||
|
||||
const parsedVersion = parseCodexCliVersion(`${version.stdout}\n${version.stderr}`);
|
||||
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: formatCodexCliUpgradeMessage(parsedVersion),
|
||||
};
|
||||
}
|
||||
|
||||
// Probe 2: `codex login status` — is the user authenticated?
|
||||
//
|
||||
// Custom model providers (e.g. Portkey, Azure OpenAI proxy) handle
|
||||
// authentication through their own environment variables, so `codex
|
||||
// login status` will report "not logged in" even when the CLI works
|
||||
// fine. Skip the auth probe entirely for non-OpenAI providers.
|
||||
if (yield* hasCustomModelProvider) {
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "ready" as const,
|
||||
available: true,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: "Using a custom Codex model provider; OpenAI login check skipped.",
|
||||
} satisfies ServerProviderStatus;
|
||||
}
|
||||
|
||||
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "warning" as const,
|
||||
available: true,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message:
|
||||
error instanceof Error
|
||||
? `Could not verify Codex authentication status: ${error.message}.`
|
||||
: "Could not verify Codex authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
if (Option.isNone(authProbe.success)) {
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "warning" as const,
|
||||
available: true,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: "Could not verify Codex authentication status. Timed out while running command.",
|
||||
};
|
||||
}
|
||||
|
||||
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: parsed.status,
|
||||
available: true,
|
||||
authStatus: parsed.authStatus,
|
||||
checkedAt,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
} satisfies ServerProviderStatus;
|
||||
});
|
||||
|
||||
// ── Claude Agent health check ───────────────────────────────────────
|
||||
|
||||
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
|
||||
readonly status: ServerProviderStatusState;
|
||||
readonly authStatus: ServerProviderAuthStatus;
|
||||
readonly message?: string;
|
||||
} {
|
||||
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
|
||||
|
||||
if (
|
||||
lowerOutput.includes("unknown command") ||
|
||||
lowerOutput.includes("unrecognized command") ||
|
||||
lowerOutput.includes("unexpected argument")
|
||||
) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
"Claude Agent authentication status command is unavailable in this version of Claude.",
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
lowerOutput.includes("not logged in") ||
|
||||
lowerOutput.includes("login required") ||
|
||||
lowerOutput.includes("authentication required") ||
|
||||
lowerOutput.includes("run `claude login`") ||
|
||||
lowerOutput.includes("run claude login")
|
||||
) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
message: "Claude is not authenticated. Run `claude auth login` and try again.",
|
||||
};
|
||||
}
|
||||
|
||||
// `claude auth status` returns JSON with a `loggedIn` boolean.
|
||||
const parsedAuth = (() => {
|
||||
const trimmed = result.stdout.trim();
|
||||
if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
|
||||
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
|
||||
}
|
||||
try {
|
||||
return {
|
||||
attemptedJsonParse: true as const,
|
||||
auth: extractAuthBoolean(JSON.parse(trimmed)),
|
||||
};
|
||||
} catch {
|
||||
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
|
||||
}
|
||||
})();
|
||||
|
||||
if (parsedAuth.auth === true) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
}
|
||||
if (parsedAuth.auth === false) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
message: "Claude is not authenticated. Run `claude auth login` and try again.",
|
||||
};
|
||||
}
|
||||
if (parsedAuth.attemptedJsonParse) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
"Could not verify Claude authentication status from JSON output (missing auth marker).",
|
||||
};
|
||||
}
|
||||
if (result.code === 0) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
}
|
||||
|
||||
const detail = detailFromResult(result);
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: detail
|
||||
? `Could not verify Claude authentication status. ${detail}`
|
||||
: "Could not verify Claude authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
export const checkClaudeProviderStatus: Effect.Effect<
|
||||
ServerProviderStatus,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> = Effect.gen(function* () {
|
||||
const checkedAt = new Date().toISOString();
|
||||
|
||||
// Probe 1: `claude --version` — is the CLI reachable?
|
||||
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return {
|
||||
provider: CLAUDE_AGENT_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
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 {
|
||||
provider: CLAUDE_AGENT_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: "Claude Agent CLI is installed but failed to run. Timed out while running command.",
|
||||
};
|
||||
}
|
||||
|
||||
const version = versionProbe.success.value;
|
||||
if (version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return {
|
||||
provider: CLAUDE_AGENT_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: detail
|
||||
? `Claude Agent CLI is installed but failed to run. ${detail}`
|
||||
: "Claude Agent CLI is installed but failed to run.",
|
||||
};
|
||||
}
|
||||
|
||||
// Probe 2: `claude auth status` — is the user authenticated?
|
||||
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return {
|
||||
provider: CLAUDE_AGENT_PROVIDER,
|
||||
status: "warning" as const,
|
||||
available: true,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message:
|
||||
error instanceof Error
|
||||
? `Could not verify Claude authentication status: ${error.message}.`
|
||||
: "Could not verify Claude authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
if (Option.isNone(authProbe.success)) {
|
||||
return {
|
||||
provider: CLAUDE_AGENT_PROVIDER,
|
||||
status: "warning" as const,
|
||||
available: true,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: "Could not verify Claude authentication status. Timed out while running command.",
|
||||
};
|
||||
}
|
||||
|
||||
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
|
||||
return {
|
||||
provider: CLAUDE_AGENT_PROVIDER,
|
||||
status: parsed.status,
|
||||
available: true,
|
||||
authStatus: parsed.authStatus,
|
||||
checkedAt,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
} satisfies ServerProviderStatus;
|
||||
});
|
||||
|
||||
// ── Layer ───────────────────────────────────────────────────────────
|
||||
|
||||
export const ProviderHealthLive = Layer.effect(
|
||||
ProviderHealth,
|
||||
Effect.gen(function* () {
|
||||
const statusesFiber = yield* Effect.all([checkCodexProviderStatus, checkClaudeProviderStatus], {
|
||||
concurrency: "unbounded",
|
||||
}).pipe(Effect.forkScoped);
|
||||
|
||||
return {
|
||||
getStatuses: Fiber.join(statusesFiber),
|
||||
} satisfies ProviderHealthShape;
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,881 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, it, assert } from "@effect/vitest";
|
||||
import {
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
Layer,
|
||||
Path,
|
||||
PubSub,
|
||||
Ref,
|
||||
Schema,
|
||||
Scope,
|
||||
Sink,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import {
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
ServerSettings,
|
||||
type ServerProvider,
|
||||
type ServerSettings as ContractServerSettings,
|
||||
} from "@t3tools/contracts";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { deepMerge } from "@t3tools/shared/Struct";
|
||||
|
||||
import {
|
||||
checkCodexProviderStatus,
|
||||
hasCustomModelProvider,
|
||||
parseAuthStatusFromOutput,
|
||||
readCodexConfigModelProvider,
|
||||
} from "./CodexProvider";
|
||||
import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider";
|
||||
import { haveProvidersChanged, ProviderRegistryLive } from "./ProviderRegistry";
|
||||
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings";
|
||||
import { ProviderRegistry } from "../Services/ProviderRegistry";
|
||||
|
||||
// ── Test helpers ────────────────────────────────────────────────────
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
function mockHandle(result: { stdout: string; stderr: string; code: number }) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.make(encoder.encode(result.stdout)),
|
||||
stderr: Stream.make(encoder.encode(result.stderr)),
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
}
|
||||
|
||||
function mockSpawnerLayer(
|
||||
handler: (args: ReadonlyArray<string>) => { stdout: string; stderr: string; code: number },
|
||||
) {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const cmd = command as unknown as { args: ReadonlyArray<string> };
|
||||
return Effect.succeed(mockHandle(handler(cmd.args)));
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function mockCommandSpawnerLayer(
|
||||
handler: (
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
) => { stdout: string; stderr: string; code: number },
|
||||
) {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const cmd = command as unknown as { command: string; args: ReadonlyArray<string> };
|
||||
return Effect.succeed(mockHandle(handler(cmd.command, cmd.args)));
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function failingSpawnerLayer(description: string) {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "ChildProcess",
|
||||
method: "spawn",
|
||||
description,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function makeMutableServerSettingsService(
|
||||
initial: ContractServerSettings = DEFAULT_SERVER_SETTINGS,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const settingsRef = yield* Ref.make(initial);
|
||||
const changes = yield* PubSub.unbounded<ContractServerSettings>();
|
||||
|
||||
return {
|
||||
start: Effect.void,
|
||||
ready: Effect.void,
|
||||
getSettings: Ref.get(settingsRef),
|
||||
updateSettings: (patch) =>
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(settingsRef);
|
||||
const next = Schema.decodeSync(ServerSettings)(deepMerge(current, patch));
|
||||
yield* Ref.set(settingsRef, next);
|
||||
yield* PubSub.publish(changes, next);
|
||||
return next;
|
||||
}),
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
} satisfies ServerSettingsShape;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a temporary CODEX_HOME scoped to the current Effect test.
|
||||
* Cleanup is registered in the test scope rather than via Vitest hooks.
|
||||
*/
|
||||
function withTempCodexHome(configContent?: string) {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tmpDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-test-codex-" });
|
||||
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
const originalCodexHome = process.env.CODEX_HOME;
|
||||
process.env.CODEX_HOME = tmpDir;
|
||||
return originalCodexHome;
|
||||
}),
|
||||
(originalCodexHome) =>
|
||||
Effect.sync(() => {
|
||||
if (originalCodexHome !== undefined) {
|
||||
process.env.CODEX_HOME = originalCodexHome;
|
||||
} else {
|
||||
delete process.env.CODEX_HOME;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
if (configContent !== undefined) {
|
||||
yield* fileSystem.writeFileString(path.join(tmpDir, "config.toml"), configContent);
|
||||
}
|
||||
|
||||
return { tmpDir } as const;
|
||||
});
|
||||
}
|
||||
|
||||
it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
"ProviderRegistry",
|
||||
(it) => {
|
||||
// ── checkCodexProviderStatus tests ────────────────────────────────
|
||||
//
|
||||
// These tests control CODEX_HOME to ensure the custom-provider detection
|
||||
// in hasCustomModelProvider() does not interfere with the auth-probe
|
||||
// path being tested.
|
||||
|
||||
describe("checkCodexProviderStatus", () => {
|
||||
it.effect("returns ready when codex is installed and authenticated", () =>
|
||||
Effect.gen(function* () {
|
||||
// Point CODEX_HOME at an empty tmp dir (no config.toml) so the
|
||||
// default code path (OpenAI provider, auth probe runs) is exercised.
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus();
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect.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,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
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", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus();
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, false);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI (`codex`) is not installed or not on PATH.",
|
||||
);
|
||||
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when codex is below the minimum supported version", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus();
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 0.36.0\n", stderr: "", code: 0 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unauthenticated when auth probe reports login required", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus();
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") {
|
||||
return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unauthenticated when login status output includes 'not logged in'", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus();
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status")
|
||||
return { stdout: "Not logged in\n", stderr: "", code: 1 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns warning when login status command is unsupported", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus();
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "warning");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI authentication status command is unavailable in this Codex version.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") {
|
||||
return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
describe("ProviderRegistryLive", () => {
|
||||
it("treats equal provider snapshots as unchanged", () => {
|
||||
const providers = [
|
||||
{
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
authStatus: "authenticated",
|
||||
checkedAt: "2026-03-25T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
},
|
||||
{
|
||||
provider: "claudeAgent",
|
||||
status: "warning",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
authStatus: "unknown",
|
||||
checkedAt: "2026-03-25T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
},
|
||||
] as const satisfies ReadonlyArray<ServerProvider>;
|
||||
|
||||
assert.strictEqual(haveProvidersChanged(providers, [...providers]), false);
|
||||
});
|
||||
|
||||
it.effect("reruns codex health when codex provider settings change", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* makeMutableServerSettingsService();
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const providerRegistryLayer = ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)),
|
||||
Layer.provideMerge(
|
||||
mockCommandSpawnerLayer((command, args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") {
|
||||
if (command === "codex") {
|
||||
return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
}
|
||||
return { stdout: "", stderr: "spawn ENOENT", code: 1 };
|
||||
}
|
||||
if (joined === "login status") {
|
||||
return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
);
|
||||
const runtimeServices = yield* Layer.build(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(ServerSettingsService, serverSettings),
|
||||
providerRegistryLayer,
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* ProviderRegistry;
|
||||
|
||||
const initial = yield* registry.getProviders;
|
||||
assert.strictEqual(
|
||||
initial.find((status) => status.provider === "codex")?.status,
|
||||
"ready",
|
||||
);
|
||||
|
||||
yield* serverSettings.updateSettings({
|
||||
providers: {
|
||||
codex: {
|
||||
binaryPath: "/custom/codex",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
for (let attempt = 0; attempt < 20; attempt += 1) {
|
||||
const updated = yield* registry.getProviders;
|
||||
if (updated.find((status) => status.provider === "codex")?.status === "error") {
|
||||
return;
|
||||
}
|
||||
yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 0)));
|
||||
}
|
||||
|
||||
const updated = yield* registry.getProviders;
|
||||
assert.strictEqual(
|
||||
updated.find((status) => status.provider === "codex")?.status,
|
||||
"error",
|
||||
);
|
||||
}).pipe(Effect.provide(runtimeServices));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips codex probes entirely when the provider is disabled", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
codex: {
|
||||
enabled: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* checkCodexProviderStatus().pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(serverSettingsLayer, failingSpawnerLayer("spawn codex ENOENT")),
|
||||
),
|
||||
);
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.enabled, false);
|
||||
assert.strictEqual(status.status, "disabled");
|
||||
assert.strictEqual(status.installed, false);
|
||||
assert.strictEqual(status.message, "Codex is disabled in T3 Code settings.");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── Custom model provider: checkCodexProviderStatus integration ───
|
||||
|
||||
describe("checkCodexProviderStatus with custom model provider", () => {
|
||||
it.effect(
|
||||
"skips auth probe and returns ready when a custom model provider is configured",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome(
|
||||
[
|
||||
'model_provider = "portkey"',
|
||||
"",
|
||||
"[model_providers.portkey]",
|
||||
'base_url = "https://api.portkey.ai/v1"',
|
||||
'env_key = "PORTKEY_API_KEY"',
|
||||
].join("\n"),
|
||||
);
|
||||
const status = yield* checkCodexProviderStatus();
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Using a custom Codex model provider; OpenAI login check skipped.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
// The spawner only handles --version; if the test attempts
|
||||
// "login status" the throw proves the auth probe was NOT skipped.
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
throw new Error(`Auth probe should have been skipped but got args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("still reports error when codex CLI is missing even with custom provider", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome(
|
||||
[
|
||||
'model_provider = "portkey"',
|
||||
"",
|
||||
"[model_providers.portkey]",
|
||||
'base_url = "https://api.portkey.ai/v1"',
|
||||
'env_key = "PORTKEY_API_KEY"',
|
||||
].join("\n"),
|
||||
);
|
||||
const status = yield* checkCodexProviderStatus();
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, false);
|
||||
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
|
||||
);
|
||||
});
|
||||
|
||||
describe("checkCodexProviderStatus with openai model provider", () => {
|
||||
it.effect("still runs auth probe when model_provider is openai", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model_provider = "openai"\n');
|
||||
const status = yield* checkCodexProviderStatus();
|
||||
// The auth probe runs and sees "not logged in" → error
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status")
|
||||
return { stdout: "Not logged in\n", stderr: "", code: 1 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
// ── parseAuthStatusFromOutput pure tests ──────────────────────────
|
||||
|
||||
describe("parseAuthStatusFromOutput", () => {
|
||||
it("exit code 0 with no auth markers is ready", () => {
|
||||
const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
|
||||
assert.strictEqual(parsed.status, "ready");
|
||||
assert.strictEqual(parsed.authStatus, "authenticated");
|
||||
});
|
||||
|
||||
it("JSON with authenticated=false is unauthenticated", () => {
|
||||
const parsed = parseAuthStatusFromOutput({
|
||||
stdout: '[{"authenticated":false}]\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "error");
|
||||
assert.strictEqual(parsed.authStatus, "unauthenticated");
|
||||
});
|
||||
|
||||
it("JSON without auth marker is warning", () => {
|
||||
const parsed = parseAuthStatusFromOutput({
|
||||
stdout: '[{"ok":true}]\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "warning");
|
||||
assert.strictEqual(parsed.authStatus, "unknown");
|
||||
});
|
||||
});
|
||||
|
||||
// ── readCodexConfigModelProvider tests ─────────────────────────────
|
||||
|
||||
describe("readCodexConfigModelProvider", () => {
|
||||
it.effect("returns undefined when config file does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider(), undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns undefined when config has no model_provider key", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model = "gpt-5-codex"\n');
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider(), undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns the provider when model_provider is set at top level", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model = "gpt-5-codex"\nmodel_provider = "portkey"\n');
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider(), "portkey");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns openai when model_provider is openai", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model_provider = "openai"\n');
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider(), "openai");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ignores model_provider inside section headers", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome(
|
||||
[
|
||||
'model = "gpt-5-codex"',
|
||||
"",
|
||||
"[model_providers.portkey]",
|
||||
'base_url = "https://api.portkey.ai/v1"',
|
||||
'model_provider = "should-be-ignored"',
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider(), undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("handles comments and whitespace", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome(
|
||||
[
|
||||
"# This is a comment",
|
||||
"",
|
||||
' model_provider = "azure" ',
|
||||
"",
|
||||
"[profiles.deep-review]",
|
||||
'model = "gpt-5-pro"',
|
||||
].join("\n"),
|
||||
);
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider(), "azure");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("handles single-quoted values in TOML", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome("model_provider = 'mistral'\n");
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider(), "mistral");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── hasCustomModelProvider tests ───────────────────────────────────
|
||||
|
||||
describe("hasCustomModelProvider", () => {
|
||||
it.effect("returns false when no config file exists", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
assert.strictEqual(yield* hasCustomModelProvider, false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns false when model_provider is not set", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model = "gpt-5-codex"\n');
|
||||
assert.strictEqual(yield* hasCustomModelProvider, false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns false when model_provider is openai", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model_provider = "openai"\n');
|
||||
assert.strictEqual(yield* hasCustomModelProvider, false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns true when model_provider is portkey", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model_provider = "portkey"\n');
|
||||
assert.strictEqual(yield* hasCustomModelProvider, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns true when model_provider is azure", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model_provider = "azure"\n');
|
||||
assert.strictEqual(yield* hasCustomModelProvider, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns true when model_provider is ollama", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model_provider = "ollama"\n');
|
||||
assert.strictEqual(yield* hasCustomModelProvider, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns true when model_provider is a custom proxy", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model_provider = "my-company-proxy"\n');
|
||||
assert.strictEqual(yield* hasCustomModelProvider, true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── checkClaudeProviderStatus tests ──────────────────────────
|
||||
|
||||
describe("checkClaudeProviderStatus", () => {
|
||||
it.effect("returns ready when claude is installed and authenticated", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus();
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when claude is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus();
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, false);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude Agent CLI (`claude`) is not installed or not on PATH.",
|
||||
);
|
||||
}).pipe(Effect.provide(failingSpawnerLayer("spawn claude ENOENT"))),
|
||||
);
|
||||
|
||||
it.effect("returns error when version check fails with non-zero exit code", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus();
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version")
|
||||
return { stdout: "", stderr: "Something went wrong", code: 1 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unauthenticated when auth status reports not logged in", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus();
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude is not authenticated. Run `claude auth login` and try again.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":false}\n',
|
||||
stderr: "",
|
||||
code: 1,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unauthenticated when output includes 'not logged in'", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus();
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return { stdout: "Not logged in\n", stderr: "", code: 1 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns warning when auth status command is unsupported", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus();
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "warning");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude Agent authentication status command is unavailable in this version of Claude.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return { stdout: "", stderr: "error: unknown command 'auth'", code: 2 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
// ── parseClaudeAuthStatusFromOutput pure tests ────────────────────
|
||||
|
||||
describe("parseClaudeAuthStatusFromOutput", () => {
|
||||
it("exit code 0 with no auth markers is ready", () => {
|
||||
const parsed = parseClaudeAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
|
||||
assert.strictEqual(parsed.status, "ready");
|
||||
assert.strictEqual(parsed.authStatus, "authenticated");
|
||||
});
|
||||
|
||||
it("JSON with loggedIn=true is authenticated", () => {
|
||||
const parsed = parseClaudeAuthStatusFromOutput({
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "ready");
|
||||
assert.strictEqual(parsed.authStatus, "authenticated");
|
||||
});
|
||||
|
||||
it("JSON with loggedIn=false is unauthenticated", () => {
|
||||
const parsed = parseClaudeAuthStatusFromOutput({
|
||||
stdout: '{"loggedIn":false}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "error");
|
||||
assert.strictEqual(parsed.authStatus, "unauthenticated");
|
||||
});
|
||||
|
||||
it("JSON without auth marker is warning", () => {
|
||||
const parsed = parseClaudeAuthStatusFromOutput({
|
||||
stdout: '{"ok":true}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "warning");
|
||||
assert.strictEqual(parsed.authStatus, "unknown");
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* ProviderRegistryLive - Aggregates provider-specific snapshot services.
|
||||
*
|
||||
* @module ProviderRegistryLive
|
||||
*/
|
||||
import type { ProviderKind, ServerProvider } from "@t3tools/contracts";
|
||||
import { Effect, Equal, Layer, PubSub, Ref, Stream } from "effect";
|
||||
|
||||
import { ClaudeProviderLive } from "./ClaudeProvider";
|
||||
import { CodexProviderLive } from "./CodexProvider";
|
||||
import type { ClaudeProviderShape } from "../Services/ClaudeProvider";
|
||||
import { ClaudeProvider } from "../Services/ClaudeProvider";
|
||||
import type { CodexProviderShape } from "../Services/CodexProvider";
|
||||
import { CodexProvider } from "../Services/CodexProvider";
|
||||
import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry";
|
||||
|
||||
const loadProviders = (
|
||||
codexProvider: CodexProviderShape,
|
||||
claudeProvider: ClaudeProviderShape,
|
||||
): Effect.Effect<readonly [ServerProvider, ServerProvider]> =>
|
||||
Effect.all([codexProvider.getSnapshot, claudeProvider.getSnapshot], {
|
||||
concurrency: "unbounded",
|
||||
});
|
||||
|
||||
export const haveProvidersChanged = (
|
||||
previousProviders: ReadonlyArray<ServerProvider>,
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
): boolean => !Equal.equals(previousProviders, nextProviders);
|
||||
|
||||
export const ProviderRegistryLive = Layer.effect(
|
||||
ProviderRegistry,
|
||||
Effect.gen(function* () {
|
||||
const codexProvider = yield* CodexProvider;
|
||||
const claudeProvider = yield* ClaudeProvider;
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
|
||||
PubSub.shutdown,
|
||||
);
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(
|
||||
yield* loadProviders(codexProvider, claudeProvider),
|
||||
);
|
||||
|
||||
const syncProviders = (options?: { readonly publish?: boolean }) =>
|
||||
Effect.gen(function* () {
|
||||
const previousProviders = yield* Ref.get(providersRef);
|
||||
const providers = yield* loadProviders(codexProvider, claudeProvider);
|
||||
yield* Ref.set(providersRef, providers);
|
||||
|
||||
if (options?.publish !== false && haveProvidersChanged(previousProviders, providers)) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
}
|
||||
|
||||
return providers;
|
||||
});
|
||||
|
||||
yield* Stream.runForEach(codexProvider.streamChanges, () => syncProviders()).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* Stream.runForEach(claudeProvider.streamChanges, () => syncProviders()).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
return {
|
||||
getProviders: syncProviders({ publish: false }).pipe(
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orElseSucceed(() => []),
|
||||
),
|
||||
refresh: (provider?: ProviderKind) =>
|
||||
Effect.gen(function* () {
|
||||
switch (provider) {
|
||||
case "codex":
|
||||
yield* codexProvider.refresh;
|
||||
break;
|
||||
case "claudeAgent":
|
||||
yield* claudeProvider.refresh;
|
||||
break;
|
||||
default:
|
||||
yield* Effect.all([codexProvider.refresh, claudeProvider.refresh], {
|
||||
concurrency: "unbounded",
|
||||
});
|
||||
break;
|
||||
}
|
||||
return yield* syncProviders();
|
||||
}).pipe(
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orElseSucceed(() => []),
|
||||
),
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
} satisfies ProviderRegistryShape;
|
||||
}),
|
||||
).pipe(Layer.provideMerge(CodexProviderLive), Layer.provideMerge(ClaudeProviderLive));
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
import { it, assert, vi } from "@effect/vitest";
|
||||
import { assertFailure } from "@effect/vitest/utils";
|
||||
|
||||
import { Effect, Fiber, Layer, Option, PubSub, Ref, Stream } from "effect";
|
||||
import { Cause, Effect, Fiber, Layer, Option, PubSub, Ref, Schema, Stream } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import {
|
||||
@@ -42,7 +42,11 @@ import {
|
||||
makeSqlitePersistenceLive,
|
||||
SqlitePersistenceMemory,
|
||||
} from "../../persistence/Layers/Sqlite.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";
|
||||
import { clearWorkspacePathStateCache } from "../../workspacePaths.ts";
|
||||
|
||||
const defaultServerSettingsLayer = ServerSettingsService.layerTest();
|
||||
|
||||
const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
@@ -227,6 +231,16 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
|
||||
const sleep = (ms: number) =>
|
||||
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
|
||||
|
||||
for (const workspaceRoot of [
|
||||
"/tmp/project",
|
||||
"/tmp/project-claude",
|
||||
"/tmp/project-send-turn",
|
||||
"/tmp/project-claude-send-turn",
|
||||
"/tmp/project-claude-start",
|
||||
]) {
|
||||
fs.mkdirSync(workspaceRoot, { recursive: true });
|
||||
}
|
||||
|
||||
function makeProviderServiceLayer() {
|
||||
const codex = makeFakeCodexAdapter();
|
||||
const claude = makeFakeCodexAdapter("claudeAgent");
|
||||
@@ -251,6 +265,7 @@ function makeProviderServiceLayer() {
|
||||
makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerAdapterLayer),
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provideMerge(AnalyticsService.layerTest),
|
||||
),
|
||||
directoryLayer,
|
||||
@@ -267,6 +282,55 @@ function makeProviderServiceLayer() {
|
||||
};
|
||||
}
|
||||
|
||||
it.effect("ProviderServiceLive rejects new sessions for disabled providers", () =>
|
||||
Effect.gen(function* () {
|
||||
const codex = makeFakeCodexAdapter();
|
||||
const claude = makeFakeCodexAdapter("claudeAgent");
|
||||
const registry: typeof ProviderAdapterRegistry.Service = {
|
||||
getByProvider: (provider) =>
|
||||
provider === "codex"
|
||||
? Effect.succeed(codex.adapter)
|
||||
: provider === "claudeAgent"
|
||||
? Effect.succeed(claude.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["codex", "claudeAgent"]),
|
||||
};
|
||||
const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
claudeAgent: {
|
||||
enabled: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
const providerLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerAdapterLayer),
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(serverSettingsLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
);
|
||||
|
||||
const failure = yield* Effect.flip(
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
return yield* provider.startSession(asThreadId("thread-disabled"), {
|
||||
provider: "claudeAgent",
|
||||
threadId: asThreadId("thread-disabled"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
}).pipe(Effect.provide(providerLayer)),
|
||||
);
|
||||
|
||||
assert.instanceOf(failure, ProviderValidationError);
|
||||
assert.include(failure.issue, "Provider 'claudeAgent' is disabled in T3 Code settings.");
|
||||
assert.equal(claude.startSession.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
const routing = makeProviderServiceLayer();
|
||||
it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -299,6 +363,7 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (
|
||||
const providerLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)),
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
);
|
||||
|
||||
@@ -358,6 +423,7 @@ it.effect(
|
||||
const firstProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)),
|
||||
Layer.provide(firstDirectoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
);
|
||||
const updatedResumeCursor = {
|
||||
@@ -409,6 +475,7 @@ it.effect(
|
||||
const secondProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)),
|
||||
Layer.provide(secondDirectoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
);
|
||||
|
||||
@@ -625,6 +692,46 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails recovery cleanly when the persisted workspace has been deleted", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const workspaceRoot = fs.mkdtempSync(path.join(os.tmpdir(), "provider-missing-cwd-"));
|
||||
|
||||
const initial = yield* provider.startSession(asThreadId("thread-missing-cwd"), {
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-missing-cwd"),
|
||||
cwd: workspaceRoot,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
fs.rmSync(workspaceRoot, { recursive: true, force: true });
|
||||
clearWorkspacePathStateCache(workspaceRoot);
|
||||
yield* routing.codex.stopAll();
|
||||
routing.codex.startSession.mockClear();
|
||||
routing.codex.sendTurn.mockClear();
|
||||
|
||||
const exit = yield* Effect.exit(
|
||||
provider.sendTurn({
|
||||
threadId: initial.threadId,
|
||||
input: "resume",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(routing.codex.startSession.mock.calls.length, 0);
|
||||
assert.equal(routing.codex.sendTurn.mock.calls.length, 0);
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.equal(Schema.is(ProviderValidationError)(error), true);
|
||||
assert.equal(
|
||||
(error as ProviderValidationError).message.includes("Workspace folder is missing"),
|
||||
true,
|
||||
);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("recovers stale claudeAgent sessions for sendTurn using persisted cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
@@ -633,8 +740,10 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
provider: "claudeAgent",
|
||||
threadId: asThreadId("thread-claude-send-turn"),
|
||||
cwd: "/tmp/project-claude-send-turn",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
@@ -658,14 +767,16 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
const startPayload = resumedStartInput as {
|
||||
provider?: string;
|
||||
cwd?: string;
|
||||
modelOptions?: unknown;
|
||||
modelSelection?: unknown;
|
||||
resumeCursor?: unknown;
|
||||
threadId?: string;
|
||||
};
|
||||
assert.equal(startPayload.provider, "claudeAgent");
|
||||
assert.equal(startPayload.cwd, "/tmp/project-claude-send-turn");
|
||||
assert.deepEqual(startPayload.modelOptions, {
|
||||
claudeAgent: {
|
||||
assert.deepEqual(startPayload.modelSelection, {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
@@ -765,6 +876,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
const firstProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)),
|
||||
Layer.provide(firstDirectoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
);
|
||||
|
||||
@@ -797,6 +909,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
const secondProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)),
|
||||
Layer.provide(secondDirectoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
);
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
* @module ProviderServiceLive
|
||||
*/
|
||||
import {
|
||||
ModelSelection,
|
||||
NonNegativeInt,
|
||||
ThreadId,
|
||||
ProviderInterruptTurnInput,
|
||||
@@ -32,6 +33,8 @@ import {
|
||||
} from "../Services/ProviderSessionDirectory.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { assertWorkspaceDirectory } from "../../workspacePaths.ts";
|
||||
|
||||
export interface ProviderServiceLiveOptions {
|
||||
readonly canonicalEventLogPath?: string;
|
||||
@@ -89,8 +92,7 @@ function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "st
|
||||
function toRuntimePayloadFromSession(
|
||||
session: ProviderSession,
|
||||
extra?: {
|
||||
readonly modelOptions?: unknown;
|
||||
readonly providerOptions?: unknown;
|
||||
readonly modelSelection?: unknown;
|
||||
readonly lastRuntimeEvent?: string;
|
||||
readonly lastRuntimeEventAt?: string;
|
||||
},
|
||||
@@ -100,8 +102,7 @@ function toRuntimePayloadFromSession(
|
||||
model: session.model ?? null,
|
||||
activeTurnId: session.activeTurnId ?? null,
|
||||
lastError: session.lastError ?? null,
|
||||
...(extra?.modelOptions !== undefined ? { modelOptions: extra.modelOptions } : {}),
|
||||
...(extra?.providerOptions !== undefined ? { providerOptions: extra.providerOptions } : {}),
|
||||
...(extra?.modelSelection !== undefined ? { modelSelection: extra.modelSelection } : {}),
|
||||
...(extra?.lastRuntimeEvent !== undefined ? { lastRuntimeEvent: extra.lastRuntimeEvent } : {}),
|
||||
...(extra?.lastRuntimeEventAt !== undefined
|
||||
? { lastRuntimeEventAt: extra.lastRuntimeEventAt }
|
||||
@@ -109,26 +110,14 @@ function toRuntimePayloadFromSession(
|
||||
};
|
||||
}
|
||||
|
||||
function readPersistedModelOptions(
|
||||
function readPersistedModelSelection(
|
||||
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
|
||||
): Record<string, unknown> | undefined {
|
||||
): ModelSelection | undefined {
|
||||
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
|
||||
return undefined;
|
||||
}
|
||||
const raw = "modelOptions" in runtimePayload ? runtimePayload.modelOptions : undefined;
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
|
||||
return raw as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function readPersistedProviderOptions(
|
||||
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
|
||||
): Record<string, unknown> | undefined {
|
||||
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
|
||||
return undefined;
|
||||
}
|
||||
const raw = "providerOptions" in runtimePayload ? runtimePayload.providerOptions : undefined;
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
|
||||
return raw as Record<string, unknown>;
|
||||
const raw = "modelSelection" in runtimePayload ? runtimePayload.modelSelection : undefined;
|
||||
return Schema.is(ModelSelection)(raw) ? raw : undefined;
|
||||
}
|
||||
|
||||
function readPersistedCwd(
|
||||
@@ -146,6 +135,7 @@ function readPersistedCwd(
|
||||
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const analytics = yield* Effect.service(AnalyticsService);
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const canonicalEventLogger =
|
||||
options?.canonicalEventLogger ??
|
||||
(options?.canonicalEventLogPath !== undefined
|
||||
@@ -172,8 +162,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
session: ProviderSession,
|
||||
threadId: ThreadId,
|
||||
extra?: {
|
||||
readonly modelOptions?: unknown;
|
||||
readonly providerOptions?: unknown;
|
||||
readonly modelSelection?: unknown;
|
||||
readonly lastRuntimeEvent?: string;
|
||||
readonly lastRuntimeEventAt?: string;
|
||||
},
|
||||
@@ -238,15 +227,28 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
}
|
||||
|
||||
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
|
||||
const persistedModelOptions = readPersistedModelOptions(input.binding.runtimePayload);
|
||||
const persistedProviderOptions = readPersistedProviderOptions(input.binding.runtimePayload);
|
||||
const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
|
||||
|
||||
if (persistedCwd) {
|
||||
yield* assertWorkspaceDirectory(
|
||||
persistedCwd,
|
||||
"ProviderService.recoverSessionForThread",
|
||||
).pipe(
|
||||
Effect.mapError((error) =>
|
||||
toValidationError(
|
||||
input.operation,
|
||||
`Cannot recover thread '${input.binding.threadId}'. ${error.message}`,
|
||||
error,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const resumed = yield* adapter.startSession({
|
||||
threadId: input.binding.threadId,
|
||||
provider: input.binding.provider,
|
||||
...(persistedCwd ? { cwd: persistedCwd } : {}),
|
||||
...(persistedModelOptions ? { modelOptions: persistedModelOptions } : {}),
|
||||
...(persistedProviderOptions ? { providerOptions: persistedProviderOptions } : {}),
|
||||
...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
|
||||
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
|
||||
runtimeMode: input.binding.runtimeMode ?? "full-access",
|
||||
});
|
||||
@@ -308,12 +310,34 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
threadId,
|
||||
provider: parsed.provider ?? "codex",
|
||||
};
|
||||
const settings = yield* serverSettings.getSettings.pipe(
|
||||
Effect.mapError((error) =>
|
||||
toValidationError(
|
||||
"ProviderService.startSession",
|
||||
`Failed to load provider settings: ${error.message}`,
|
||||
error,
|
||||
),
|
||||
),
|
||||
);
|
||||
if (!settings.providers[input.provider].enabled) {
|
||||
return yield* toValidationError(
|
||||
"ProviderService.startSession",
|
||||
`Provider '${input.provider}' is disabled in T3 Code settings.`,
|
||||
);
|
||||
}
|
||||
const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
|
||||
const effectiveResumeCursor =
|
||||
input.resumeCursor ??
|
||||
(persistedBinding?.provider === input.provider
|
||||
? persistedBinding.resumeCursor
|
||||
: undefined);
|
||||
if (input.cwd) {
|
||||
yield* assertWorkspaceDirectory(input.cwd, "ProviderService.startSession").pipe(
|
||||
Effect.mapError((error) =>
|
||||
toValidationError("ProviderService.startSession", error.message, error),
|
||||
),
|
||||
);
|
||||
}
|
||||
const adapter = yield* registry.getByProvider(input.provider);
|
||||
const session = yield* adapter.startSession({
|
||||
...input,
|
||||
@@ -328,15 +352,16 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
}
|
||||
|
||||
yield* upsertSessionBinding(session, threadId, {
|
||||
modelOptions: input.modelOptions,
|
||||
providerOptions: input.providerOptions,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
yield* analytics.record("provider.session.started", {
|
||||
provider: session.provider,
|
||||
runtimeMode: input.runtimeMode,
|
||||
hasResumeCursor: session.resumeCursor !== undefined,
|
||||
hasCwd: typeof input.cwd === "string" && input.cwd.trim().length > 0,
|
||||
hasModel: typeof input.model === "string" && input.model.trim().length > 0,
|
||||
hasModel:
|
||||
typeof input.modelSelection?.model === "string" &&
|
||||
input.modelSelection.model.trim().length > 0,
|
||||
});
|
||||
|
||||
return session;
|
||||
@@ -372,6 +397,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
status: "running",
|
||||
...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
|
||||
runtimePayload: {
|
||||
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
|
||||
activeTurnId: turn.turnId,
|
||||
lastRuntimeEvent: "provider.sendTurn",
|
||||
lastRuntimeEventAt: new Date().toISOString(),
|
||||
@@ -379,7 +405,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
});
|
||||
yield* analytics.record("provider.turn.sent", {
|
||||
provider: routed.adapter.provider,
|
||||
model: input.model,
|
||||
model: input.modelSelection?.model,
|
||||
interactionMode: input.interactionMode,
|
||||
attachmentCount: input.attachments.length,
|
||||
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { ServiceMap } from "effect";
|
||||
|
||||
import type { ServerProviderShape } from "./ServerProvider";
|
||||
|
||||
export interface ClaudeProviderShape extends ServerProviderShape {}
|
||||
|
||||
export class ClaudeProvider extends ServiceMap.Service<ClaudeProvider, ClaudeProviderShape>()(
|
||||
"t3/provider/Services/ClaudeProvider",
|
||||
) {}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { ServiceMap } from "effect";
|
||||
|
||||
import type { ServerProviderShape } from "./ServerProvider";
|
||||
|
||||
export interface CodexProviderShape extends ServerProviderShape {}
|
||||
|
||||
export class CodexProvider extends ServiceMap.Service<CodexProvider, CodexProviderShape>()(
|
||||
"t3/provider/Services/CodexProvider",
|
||||
) {}
|
||||
@@ -1,22 +0,0 @@
|
||||
/**
|
||||
* ProviderHealth - Provider readiness snapshot service.
|
||||
*
|
||||
* Owns provider health checks (install/auth reachability) and exposes the
|
||||
* latest results to transport layers.
|
||||
*
|
||||
* @module ProviderHealth
|
||||
*/
|
||||
import type { ServerProviderStatus } from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export interface ProviderHealthShape {
|
||||
/**
|
||||
* Read the latest provider health statuses.
|
||||
*/
|
||||
readonly getStatuses: Effect.Effect<ReadonlyArray<ServerProviderStatus>>;
|
||||
}
|
||||
|
||||
export class ProviderHealth extends ServiceMap.Service<ProviderHealth, ProviderHealthShape>()(
|
||||
"t3/provider/Services/ProviderHealth",
|
||||
) {}
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* ProviderRegistry - Provider snapshot service.
|
||||
*
|
||||
* Owns provider install/auth/version/model snapshots and exposes the latest
|
||||
* provider state to transport layers.
|
||||
*
|
||||
* @module ProviderRegistry
|
||||
*/
|
||||
import type { ProviderKind, ServerProvider } from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
|
||||
export interface ProviderRegistryShape {
|
||||
/**
|
||||
* Read the latest provider snapshots.
|
||||
*/
|
||||
readonly getProviders: Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Refresh all providers, or a single provider when specified.
|
||||
*/
|
||||
readonly refresh: (provider?: ProviderKind) => Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Stream of provider snapshot updates.
|
||||
*/
|
||||
readonly streamChanges: Stream.Stream<ReadonlyArray<ServerProvider>>;
|
||||
}
|
||||
|
||||
export class ProviderRegistry extends ServiceMap.Service<ProviderRegistry, ProviderRegistryShape>()(
|
||||
"t3/provider/Services/ProviderRegistry",
|
||||
) {}
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { ServerProvider } from "@t3tools/contracts";
|
||||
import type { Effect, Stream } from "effect";
|
||||
|
||||
export interface ServerProviderShape {
|
||||
readonly getSnapshot: Effect.Effect<ServerProvider>;
|
||||
readonly refresh: Effect.Effect<ServerProvider>;
|
||||
readonly streamChanges: Stream.Stream<ServerProvider>;
|
||||
}
|
||||
Loaded 100 of 238 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user