Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
04ffe3b247 | ||
|
|
df5009c70b | ||
|
|
454d97f0cf | ||
|
|
4acb6e91ca | ||
|
|
45745a247a | ||
|
|
b175d6b2a3 | ||
|
|
c5c12aa738 | ||
|
|
7241400edd | ||
|
|
310fd0b187 | ||
|
|
db94743220 | ||
|
|
07aaf37fd4 | ||
|
|
65a808808f | ||
|
|
cca1aa1588 | ||
|
|
c9d4b773c9 | ||
|
|
e23f3102f4 | ||
|
|
ec89587c37 | ||
|
|
32d89806d7 | ||
|
|
2fd4e06b34 | ||
|
|
3cffdce1c1 | ||
|
|
6d2f4f4cdf | ||
|
|
865d7bd684 | ||
|
|
392d63231c | ||
|
|
7559f5ad70 | ||
|
|
605e8143e0 | ||
|
|
5b056cd337 | ||
|
|
6c350489b1 | ||
|
|
2ae63f4aa2 | ||
|
|
3d0233e3b0 | ||
|
|
64f2c3a465 | ||
|
|
0a12333448 | ||
|
|
9db54c9b19 | ||
|
|
34430e3514 | ||
|
|
99e44f2c23 | ||
|
|
7a0f2d9b30 | ||
|
|
4bf310f7ca | ||
|
|
8b9fbe701d | ||
|
|
0c5be023e4 | ||
|
|
86e87a8789 | ||
|
|
404e78a506 | ||
|
|
73563c7c25 | ||
|
|
326595b148 | ||
|
|
41a8468b08 | ||
|
|
ced2ecb6ba | ||
|
|
2d746b3a7e | ||
|
|
e6ac39de75 | ||
|
|
b76a0a6c91 | ||
|
|
9fdec3c2c8 | ||
|
|
760fe643e8 | ||
|
|
93af851dc5 | ||
|
|
fabb3e0734 | ||
|
|
9ca9a862a5 | ||
|
|
827dc9ff9f | ||
|
|
09b32ac9dd | ||
|
|
253684e280 | ||
|
|
f6d40ce841 | ||
|
|
36fb1bb7e4 | ||
|
|
4a82c1608f | ||
|
|
3efb3da007 | ||
|
|
11606fd9c6 | ||
|
|
a935db07ef | ||
|
|
98860a9549 | ||
|
|
7688742b2a | ||
|
|
b2efe4f83c | ||
|
|
f934b435fa | ||
|
|
3c121585da | ||
|
|
40acfbd2df | ||
|
|
0af61bf6ba | ||
|
|
7b2968f2ff | ||
|
|
a1c7b98f98 | ||
|
|
99ea16a969 | ||
|
|
ebe44d03a5 | ||
|
|
dcd2d50768 | ||
|
|
f11764c517 | ||
|
|
77c81b7468 | ||
|
|
7a5ccd3310 | ||
|
|
e4df6fcf8e | ||
|
|
b2be7f4e4f | ||
|
|
94beb21a43 | ||
|
|
30e05538b7 | ||
|
|
c884947ea8 | ||
|
|
61289a152d | ||
|
|
906550f9af | ||
|
|
c2aaa89b57 | ||
|
|
dde48e9414 | ||
|
|
b1608f41ad | ||
|
|
78d89e3d35 | ||
|
|
1309495218 | ||
|
|
c34a4c69e5 | ||
|
|
2f6cac0cf0 | ||
|
|
5c26df3a4f |
No files matched your search
@@ -198,6 +198,7 @@ jobs:
|
||||
--target "${{ matrix.target }}"
|
||||
--arch "${{ matrix.arch }}"
|
||||
--build-version "${{ needs.preflight.outputs.version }}"
|
||||
--verbose
|
||||
)
|
||||
|
||||
has_all() {
|
||||
@@ -239,57 +240,71 @@ jobs:
|
||||
|
||||
bun run dist:desktop:artifact -- "${args[@]}"
|
||||
|
||||
- name: Collect release assets
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p release-publish
|
||||
|
||||
shopt -s nullglob
|
||||
for pattern in \
|
||||
"release/*.dmg" \
|
||||
"release/*.zip" \
|
||||
"release/*.AppImage" \
|
||||
"release/*.exe" \
|
||||
"release/*.blockmap" \
|
||||
"release/latest*.yml"; do
|
||||
for file in $pattern; do
|
||||
cp "$file" release-publish/
|
||||
done
|
||||
done
|
||||
|
||||
if [[ "${{ matrix.platform }}" == "mac" && "${{ matrix.arch }}" != "arm64" ]]; then
|
||||
if [[ -f release-publish/latest-mac.yml ]]; then
|
||||
mv release-publish/latest-mac.yml "release-publish/latest-mac-${{ matrix.arch }}.yml"
|
||||
fi
|
||||
fi
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: desktop-${{ matrix.platform }}-${{ matrix.arch }}
|
||||
path: release/*
|
||||
path: release-publish/*
|
||||
if-no-files-found: error
|
||||
|
||||
# publish_cli:
|
||||
# name: Publish CLI to npm
|
||||
# needs: [preflight, build]
|
||||
# runs-on: ubuntu-24.04
|
||||
# steps:
|
||||
# - name: Checkout
|
||||
# uses: actions/checkout@v4
|
||||
publish_cli:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, build]
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
# - name: Setup Bun
|
||||
# uses: oven-sh/setup-bun@v2
|
||||
# with:
|
||||
# bun-version-file: package.json
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
# - name: Setup Node
|
||||
# uses: actions/setup-node@v4
|
||||
# with:
|
||||
# node-version-file: package.json
|
||||
# registry-url: https://registry.npmjs.org
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
registry-url: https://registry.npmjs.org
|
||||
|
||||
# - name: Install dependencies
|
||||
# run: bun install --frozen-lockfile
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
# - name: Set CLI package version from release tag
|
||||
# env:
|
||||
# RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
|
||||
# run: |
|
||||
# node --input-type=module -e '
|
||||
# import { readFileSync, writeFileSync } from "node:fs";
|
||||
# const packagePath = "apps/server/package.json";
|
||||
# const packageJson = JSON.parse(readFileSync(packagePath, "utf8"));
|
||||
# packageJson.version = process.env.RELEASE_VERSION;
|
||||
# writeFileSync(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`);
|
||||
# '
|
||||
- name: Build CLI package
|
||||
run: bun run build --filter=@t3tools/web --filter=t3
|
||||
|
||||
# - name: Build CLI package
|
||||
# run: bun run build --filter=@t3tools/web --filter=t3
|
||||
|
||||
# - name: Publish CLI package
|
||||
# run: bun --cwd apps/server publish --access public
|
||||
- name: Publish CLI package
|
||||
run: node apps/server/scripts/cli.ts publish --tag alpha --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
|
||||
release:
|
||||
name: Publish GitHub Release
|
||||
needs: [preflight, build]
|
||||
# needs: [preflight, build, publish_cli]
|
||||
needs: [preflight, build, publish_cli]
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Download all desktop artifacts
|
||||
@@ -305,5 +320,11 @@ jobs:
|
||||
tag_name: ${{ needs.preflight.outputs.tag }}
|
||||
name: T3 Code v${{ needs.preflight.outputs.version }}
|
||||
generate_release_notes: true
|
||||
files: release-assets/*
|
||||
files: |
|
||||
release-assets/*.dmg
|
||||
release-assets/*.zip
|
||||
release-assets/*.AppImage
|
||||
release-assets/*.exe
|
||||
release-assets/*.blockmap
|
||||
release-assets/latest*.yml
|
||||
fail_on_unmatched_files: true
|
||||
@@ -18,11 +18,16 @@ This repository is a VERY EARLY WIP. Proposing sweeping changes that improve lon
|
||||
|
||||
If a tradeoff is required, choose correctness and robustness over short-term convenience.
|
||||
|
||||
## Maintainability
|
||||
|
||||
Long term maintainability is a core priority. If you add new functionality, first check if there are shared logic that can be extracted to a separate module. Duplicate logic across mulitple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
|
||||
|
||||
## Package Roles
|
||||
|
||||
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
|
||||
- `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
|
||||
- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
|
||||
- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types. Keep this package schema-only — no runtime logic.
|
||||
- `packages/shared`: Shared runtime utilities consumed by both server and web. Uses explicit subpath exports (e.g. `@t3tools/shared/git`) — no barrel index.
|
||||
|
||||
## Codex App Server (Important)
|
||||
|
||||
@@ -45,7 +50,3 @@ Docs:
|
||||
- Codex-Monitor (Tauri, feature-complete, strong reference implementation): https://github.com/Dimillian/CodexMonitor
|
||||
|
||||
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
|
||||
|
||||
## Dummy Change
|
||||
|
||||
- Placeholder line to validate a docs-only edit.
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
@@ -14,15 +14,17 @@
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"electron": "40.6.0"
|
||||
"effect": "catalog:",
|
||||
"electron": "40.6.0",
|
||||
"electron-updater": "^6.6.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@types/node": "^24.10.13",
|
||||
"electronmon": "^2.0.2",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@types/node": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
"wait-on": "^8.0.2"
|
||||
},
|
||||
"productName": "T3 Code (Alpha)"
|
||||
|
||||
@@ -1,43 +1,171 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
import electronmon from "electronmon";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { watch } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import waitOn from "wait-on";
|
||||
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
|
||||
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
|
||||
const devServerUrl = `http://localhost:${port}`;
|
||||
const requiredFiles = ["dist-electron/main.js", "dist-electron/preload.js", "../server/dist/index.mjs"];
|
||||
const watchedDirectories = [
|
||||
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
|
||||
{ directory: "../server/dist", files: new Set(["index.mjs"]) },
|
||||
];
|
||||
const forcedShutdownTimeoutMs = 1_500;
|
||||
const restartDebounceMs = 120;
|
||||
const childTreeGracePeriodMs = 1_200;
|
||||
|
||||
await waitOn({
|
||||
resources: [
|
||||
`tcp:${port}`,
|
||||
"file:dist-electron/main.js",
|
||||
"file:dist-electron/preload.js",
|
||||
"file:../server/dist/index.mjs",
|
||||
],
|
||||
resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
|
||||
});
|
||||
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const monitor = await electronmon({
|
||||
cwd: desktopDir,
|
||||
args: ["dist-electron/main.js"],
|
||||
env: {
|
||||
...childEnv,
|
||||
VITE_DEV_SERVER_URL: devServerUrl,
|
||||
},
|
||||
electronPath: resolveElectronPath(),
|
||||
});
|
||||
|
||||
let shuttingDown = false;
|
||||
let restartTimer = null;
|
||||
let currentApp = null;
|
||||
let restartQueue = Promise.resolve();
|
||||
const expectedExits = new WeakSet();
|
||||
const watchers = [];
|
||||
|
||||
function killChildTreeByPid(pid, signal) {
|
||||
if (process.platform === "win32" || typeof pid !== "number") {
|
||||
return;
|
||||
}
|
||||
|
||||
spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
function cleanupStaleDevApps() {
|
||||
if (process.platform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
function startApp() {
|
||||
if (shuttingDown || currentApp !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const app = spawn(
|
||||
resolveElectronPath(),
|
||||
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
|
||||
{
|
||||
cwd: desktopDir,
|
||||
env: {
|
||||
...childEnv,
|
||||
VITE_DEV_SERVER_URL: devServerUrl,
|
||||
},
|
||||
stdio: "inherit",
|
||||
},
|
||||
);
|
||||
|
||||
currentApp = app;
|
||||
|
||||
app.once("error", () => {
|
||||
if (currentApp === app) {
|
||||
currentApp = null;
|
||||
}
|
||||
|
||||
if (!shuttingDown) {
|
||||
scheduleRestart();
|
||||
}
|
||||
});
|
||||
|
||||
app.once("exit", () => {
|
||||
if (currentApp === app) {
|
||||
currentApp = null;
|
||||
}
|
||||
|
||||
if (!shuttingDown && !expectedExits.has(app)) {
|
||||
scheduleRestart();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function stopApp() {
|
||||
const app = currentApp;
|
||||
if (!app) {
|
||||
return;
|
||||
}
|
||||
|
||||
currentApp = null;
|
||||
expectedExits.add(app);
|
||||
|
||||
await new Promise((resolve) => {
|
||||
let settled = false;
|
||||
|
||||
const finish = () => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
settled = true;
|
||||
resolve();
|
||||
};
|
||||
|
||||
app.once("exit", finish);
|
||||
app.kill("SIGTERM");
|
||||
killChildTreeByPid(app.pid, "TERM");
|
||||
|
||||
setTimeout(() => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
app.kill("SIGKILL");
|
||||
killChildTreeByPid(app.pid, "KILL");
|
||||
finish();
|
||||
}, forcedShutdownTimeoutMs).unref();
|
||||
});
|
||||
}
|
||||
|
||||
function scheduleRestart() {
|
||||
if (shuttingDown) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
}
|
||||
|
||||
restartTimer = setTimeout(() => {
|
||||
restartTimer = null;
|
||||
restartQueue = restartQueue
|
||||
.catch(() => undefined)
|
||||
.then(async () => {
|
||||
await stopApp();
|
||||
if (!shuttingDown) {
|
||||
startApp();
|
||||
}
|
||||
});
|
||||
}, restartDebounceMs);
|
||||
}
|
||||
|
||||
function startWatchers() {
|
||||
for (const { directory, files } of watchedDirectories) {
|
||||
const watcher = watch(join(desktopDir, directory), { persistent: true }, (_eventType, filename) => {
|
||||
if (typeof filename !== "string" || !files.has(filename)) {
|
||||
return;
|
||||
}
|
||||
|
||||
scheduleRestart();
|
||||
});
|
||||
|
||||
watchers.push(watcher);
|
||||
}
|
||||
}
|
||||
|
||||
function killChildTree(signal) {
|
||||
if (process.platform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
// electronmon may leave Electron orphaned when parent shutdown races; kill direct children as fallback.
|
||||
// Kill direct children as a final fallback in case normal shutdown leaves stragglers.
|
||||
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
@@ -45,20 +173,29 @@ async function shutdown(exitCode) {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
|
||||
try {
|
||||
await Promise.race([monitor.destroy(), new Promise((resolve) => setTimeout(resolve, 1_500))]);
|
||||
} catch {
|
||||
// Best effort only; fallback process kill below handles stubborn children.
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
restartTimer = null;
|
||||
}
|
||||
|
||||
for (const watcher of watchers) {
|
||||
watcher.close();
|
||||
}
|
||||
|
||||
await stopApp();
|
||||
killChildTree("TERM");
|
||||
setTimeout(() => {
|
||||
killChildTree("KILL");
|
||||
}, 1_200).unref();
|
||||
await new Promise((resolve) => {
|
||||
setTimeout(resolve, childTreeGracePeriodMs);
|
||||
});
|
||||
killChildTree("KILL");
|
||||
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
startWatchers();
|
||||
cleanupStaleDevApps();
|
||||
startApp();
|
||||
|
||||
process.once("SIGINT", () => {
|
||||
void shutdown(130);
|
||||
});
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import * as ChildProcess from "node:child_process";
|
||||
|
||||
export function fixPath(): void {
|
||||
if (process.platform !== "darwin") return;
|
||||
|
||||
try {
|
||||
const shell = process.env.SHELL ?? "/bin/zsh";
|
||||
const result = execFileSync(shell, ["-ilc", "echo -n $PATH"], {
|
||||
const result = ChildProcess.execFileSync(shell, ["-ilc", "echo -n $PATH"], {
|
||||
encoding: "utf8",
|
||||
timeout: 5000,
|
||||
});
|
||||
|
||||
+614
-66
@@ -1,16 +1,36 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import net from "node:net";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import * as ChildProcess from "node:child_process";
|
||||
import * as Crypto from "node:crypto";
|
||||
import * as FS from "node:fs";
|
||||
import * as OS from "node:os";
|
||||
import * as Path from "node:path";
|
||||
|
||||
import { app, BrowserWindow, dialog, ipcMain, Menu, nativeImage, protocol, shell } from "electron";
|
||||
import type { MenuItemConstructorOptions } from "electron";
|
||||
import * as Effect from "effect/Effect";
|
||||
import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts";
|
||||
import { autoUpdater } from "electron-updater";
|
||||
|
||||
import type { ContextMenuItem } from "@t3tools/contracts";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
import { fixPath } from "./fixPath";
|
||||
import {
|
||||
getAutoUpdateDisabledReason,
|
||||
shouldBroadcastDownloadProgress,
|
||||
} from "./updateState";
|
||||
import {
|
||||
createInitialDesktopUpdateState,
|
||||
reduceDesktopUpdateStateOnCheckFailure,
|
||||
reduceDesktopUpdateStateOnCheckStart,
|
||||
reduceDesktopUpdateStateOnDownloadComplete,
|
||||
reduceDesktopUpdateStateOnDownloadFailure,
|
||||
reduceDesktopUpdateStateOnDownloadProgress,
|
||||
reduceDesktopUpdateStateOnDownloadStart,
|
||||
reduceDesktopUpdateStateOnInstallFailure,
|
||||
reduceDesktopUpdateStateOnNoUpdate,
|
||||
reduceDesktopUpdateStateOnUpdateAvailable,
|
||||
} from "./updateMachine";
|
||||
|
||||
fixPath();
|
||||
|
||||
@@ -19,18 +39,30 @@ const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
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_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
const STATE_DIR =
|
||||
process.env.T3CODE_STATE_DIR?.trim() || path.join(os.homedir(), ".t3", "userdata");
|
||||
process.env.T3CODE_STATE_DIR?.trim() || Path.join(OS.homedir(), ".t3", "userdata");
|
||||
const DESKTOP_SCHEME = "t3";
|
||||
const ROOT_DIR = path.resolve(__dirname, "../../..");
|
||||
const ROOT_DIR = Path.resolve(__dirname, "../../..");
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_USER_MODEL_ID = "com.t3tools.t3code";
|
||||
const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i;
|
||||
const COMMIT_HASH_DISPLAY_LENGTH = 12;
|
||||
const LOG_DIR = Path.join(STATE_DIR, "logs");
|
||||
const LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||
const LOG_FILE_MAX_FILES = 10;
|
||||
const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
|
||||
const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
|
||||
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
|
||||
|
||||
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
|
||||
|
||||
let mainWindow: BrowserWindow | null = null;
|
||||
let backendProcess: ChildProcess | null = null;
|
||||
let backendProcess: ChildProcess.ChildProcess | null = null;
|
||||
let backendPort = 0;
|
||||
let backendAuthToken = "";
|
||||
let backendWsUrl = "";
|
||||
@@ -39,8 +71,133 @@ let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let isQuitting = false;
|
||||
let desktopProtocolRegistered = false;
|
||||
let aboutCommitHashCache: string | null | undefined;
|
||||
let desktopLogSink: RotatingFileSink | null = null;
|
||||
let backendLogSink: RotatingFileSink | null = null;
|
||||
let restoreStdIoCapture: (() => void) | null = null;
|
||||
|
||||
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
|
||||
const initialUpdateState = (): DesktopUpdateState => createInitialDesktopUpdateState(app.getVersion());
|
||||
|
||||
function logTimestamp(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function logScope(scope: string): string {
|
||||
return `${scope} run=${APP_RUN_ID}`;
|
||||
}
|
||||
|
||||
function sanitizeLogValue(value: string): string {
|
||||
return value.replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
function writeDesktopLogHeader(message: string): void {
|
||||
if (!desktopLogSink) return;
|
||||
desktopLogSink.write(`[${logTimestamp()}] [${logScope("desktop")}] ${message}\n`);
|
||||
}
|
||||
|
||||
function writeBackendSessionBoundary(phase: "START" | "END", details: string): void {
|
||||
if (!backendLogSink) return;
|
||||
const normalizedDetails = sanitizeLogValue(details);
|
||||
backendLogSink.write(
|
||||
`[${logTimestamp()}] ---- APP SESSION ${phase} run=${APP_RUN_ID} ${normalizedDetails} ----\n`,
|
||||
);
|
||||
}
|
||||
|
||||
function formatErrorMessage(error: unknown): string {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
return String(error);
|
||||
}
|
||||
|
||||
function writeDesktopStreamChunk(
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: unknown,
|
||||
encoding: BufferEncoding | undefined,
|
||||
): void {
|
||||
if (!desktopLogSink) return;
|
||||
const buffer = Buffer.isBuffer(chunk)
|
||||
? chunk
|
||||
: Buffer.from(String(chunk), typeof chunk === "string" ? encoding : undefined);
|
||||
desktopLogSink.write(`[${logTimestamp()}] [${logScope(streamName)}] `);
|
||||
desktopLogSink.write(buffer);
|
||||
if (buffer.length === 0 || buffer[buffer.length - 1] !== 0x0a) {
|
||||
desktopLogSink.write("\n");
|
||||
}
|
||||
}
|
||||
|
||||
function installStdIoCapture(): void {
|
||||
if (!app.isPackaged || desktopLogSink === null || restoreStdIoCapture !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const originalStdoutWrite = process.stdout.write.bind(process.stdout);
|
||||
const originalStderrWrite = process.stderr.write.bind(process.stderr);
|
||||
|
||||
const patchWrite =
|
||||
(streamName: "stdout" | "stderr", originalWrite: typeof process.stdout.write) =>
|
||||
(
|
||||
chunk: string | Uint8Array,
|
||||
encodingOrCallback?: BufferEncoding | ((error?: Error | null) => void),
|
||||
callback?: (error?: Error | null) => void,
|
||||
): boolean => {
|
||||
const encoding = typeof encodingOrCallback === "string" ? encodingOrCallback : undefined;
|
||||
writeDesktopStreamChunk(streamName, chunk, encoding);
|
||||
if (typeof encodingOrCallback === "function") {
|
||||
return originalWrite(chunk, encodingOrCallback);
|
||||
}
|
||||
if (callback !== undefined) {
|
||||
return originalWrite(chunk, encoding, callback);
|
||||
}
|
||||
if (encoding !== undefined) {
|
||||
return originalWrite(chunk, encoding);
|
||||
}
|
||||
return originalWrite(chunk);
|
||||
};
|
||||
|
||||
process.stdout.write = patchWrite("stdout", originalStdoutWrite);
|
||||
process.stderr.write = patchWrite("stderr", originalStderrWrite);
|
||||
|
||||
restoreStdIoCapture = () => {
|
||||
process.stdout.write = originalStdoutWrite;
|
||||
process.stderr.write = originalStderrWrite;
|
||||
restoreStdIoCapture = null;
|
||||
};
|
||||
}
|
||||
|
||||
function initializePackagedLogging(): void {
|
||||
if (!app.isPackaged) return;
|
||||
try {
|
||||
desktopLogSink = new RotatingFileSink({
|
||||
filePath: Path.join(LOG_DIR, "desktop-main.log"),
|
||||
maxBytes: LOG_FILE_MAX_BYTES,
|
||||
maxFiles: LOG_FILE_MAX_FILES,
|
||||
});
|
||||
backendLogSink = new RotatingFileSink({
|
||||
filePath: Path.join(LOG_DIR, "server-child.log"),
|
||||
maxBytes: LOG_FILE_MAX_BYTES,
|
||||
maxFiles: LOG_FILE_MAX_FILES,
|
||||
});
|
||||
installStdIoCapture();
|
||||
writeDesktopLogHeader(`runtime log capture enabled logDir=${LOG_DIR}`);
|
||||
} catch (error) {
|
||||
// Logging setup should never block app startup.
|
||||
console.error("[desktop] failed to initialize packaged logging", error);
|
||||
}
|
||||
}
|
||||
|
||||
function captureBackendOutput(child: ChildProcess.ChildProcess): void {
|
||||
if (!app.isPackaged || backendLogSink === null) return;
|
||||
const writeChunk = (chunk: unknown): void => {
|
||||
if (!backendLogSink) return;
|
||||
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8");
|
||||
backendLogSink.write(buffer);
|
||||
};
|
||||
child.stdout?.on("data", writeChunk);
|
||||
child.stderr?.on("data", writeChunk);
|
||||
}
|
||||
|
||||
initializePackagedLogging();
|
||||
|
||||
function getDestructiveMenuIcon(): Electron.NativeImage | undefined {
|
||||
if (process.platform !== "darwin") return undefined;
|
||||
@@ -64,6 +221,18 @@ function getDestructiveMenuIcon(): Electron.NativeImage | undefined {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
let updatePollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let updateStartupTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let updateCheckInFlight = false;
|
||||
let updateDownloadInFlight = false;
|
||||
let updaterConfigured = false;
|
||||
let updateState: DesktopUpdateState = initialUpdateState();
|
||||
|
||||
function resolveUpdaterErrorContext(): DesktopUpdateErrorContext {
|
||||
if (updateDownloadInFlight) return "download";
|
||||
if (updateCheckInFlight) return "check";
|
||||
return updateState.errorContext;
|
||||
}
|
||||
|
||||
protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
@@ -84,6 +253,28 @@ function resolveAppRoot(): string {
|
||||
return app.getAppPath();
|
||||
}
|
||||
|
||||
/** Read the baked-in app-update.yml config (if applicable). */
|
||||
function readAppUpdateYml(): Record<string, string> | null {
|
||||
try {
|
||||
// electron-updater reads from process.resourcesPath in packaged builds,
|
||||
// or dev-app-update.yml via app.getAppPath() in dev.
|
||||
const ymlPath = app.isPackaged
|
||||
? Path.join(process.resourcesPath, "app-update.yml")
|
||||
: Path.join(app.getAppPath(), "dev-app-update.yml");
|
||||
const raw = FS.readFileSync(ymlPath, "utf-8");
|
||||
// The YAML is simple key-value pairs — avoid pulling in a YAML parser by
|
||||
// doing a line-based parse (fields: provider, owner, repo, releaseType, …).
|
||||
const entries: Record<string, string> = {};
|
||||
for (const line of raw.split("\n")) {
|
||||
const match = line.match(/^(\w+):\s*(.+)$/);
|
||||
if (match?.[1] && match[2]) entries[match[1]] = match[2].trim();
|
||||
}
|
||||
return entries.provider ? entries : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeCommitHash(value: unknown): string | null {
|
||||
if (typeof value !== "string") {
|
||||
return null;
|
||||
@@ -96,13 +287,13 @@ function normalizeCommitHash(value: unknown): string | null {
|
||||
}
|
||||
|
||||
function resolveEmbeddedCommitHash(): string | null {
|
||||
const packageJsonPath = path.join(resolveAppRoot(), "package.json");
|
||||
if (!fs.existsSync(packageJsonPath)) {
|
||||
const packageJsonPath = Path.join(resolveAppRoot(), "package.json");
|
||||
if (!FS.existsSync(packageJsonPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = fs.readFileSync(packageJsonPath, "utf8");
|
||||
const raw = FS.readFileSync(packageJsonPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as { t3codeCommitHash?: unknown };
|
||||
return normalizeCommitHash(parsed.t3codeCommitHash);
|
||||
} catch {
|
||||
@@ -133,25 +324,25 @@ function resolveAboutCommitHash(): string | null {
|
||||
}
|
||||
|
||||
function resolveBackendEntry(): string {
|
||||
return path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
|
||||
return Path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
|
||||
}
|
||||
|
||||
function resolveBackendCwd(): string {
|
||||
if (!app.isPackaged) {
|
||||
return resolveAppRoot();
|
||||
}
|
||||
return os.homedir();
|
||||
return OS.homedir();
|
||||
}
|
||||
|
||||
function resolveDesktopStaticDir(): string | null {
|
||||
const appRoot = resolveAppRoot();
|
||||
const candidates = [
|
||||
path.join(appRoot, "apps/server/dist/client"),
|
||||
path.join(appRoot, "apps/web/dist"),
|
||||
Path.join(appRoot, "apps/server/dist/client"),
|
||||
Path.join(appRoot, "apps/web/dist"),
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (fs.existsSync(path.join(candidate, "index.html"))) {
|
||||
if (FS.existsSync(Path.join(candidate, "index.html"))) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
@@ -162,35 +353,50 @@ function resolveDesktopStaticDir(): string | null {
|
||||
function resolveDesktopStaticPath(staticRoot: string, requestUrl: string): string {
|
||||
const url = new URL(requestUrl);
|
||||
const rawPath = decodeURIComponent(url.pathname);
|
||||
const normalizedPath = path.posix.normalize(rawPath).replace(/^\/+/, "");
|
||||
const normalizedPath = Path.posix.normalize(rawPath).replace(/^\/+/, "");
|
||||
if (normalizedPath.includes("..")) {
|
||||
return path.join(staticRoot, "index.html");
|
||||
return Path.join(staticRoot, "index.html");
|
||||
}
|
||||
|
||||
const requestedPath = normalizedPath.length > 0 ? normalizedPath : "index.html";
|
||||
const resolvedPath = path.join(staticRoot, requestedPath);
|
||||
const resolvedPath = Path.join(staticRoot, requestedPath);
|
||||
|
||||
if (path.extname(resolvedPath)) {
|
||||
if (Path.extname(resolvedPath)) {
|
||||
return resolvedPath;
|
||||
}
|
||||
|
||||
const nestedIndex = path.join(resolvedPath, "index.html");
|
||||
if (fs.existsSync(nestedIndex)) {
|
||||
const nestedIndex = Path.join(resolvedPath, "index.html");
|
||||
if (FS.existsSync(nestedIndex)) {
|
||||
return nestedIndex;
|
||||
}
|
||||
|
||||
return path.join(staticRoot, "index.html");
|
||||
return Path.join(staticRoot, "index.html");
|
||||
}
|
||||
|
||||
function isStaticAssetRequest(requestUrl: string): boolean {
|
||||
try {
|
||||
const url = new URL(requestUrl);
|
||||
return path.extname(url.pathname).length > 0;
|
||||
return Path.extname(url.pathname).length > 0;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleFatalStartupError(stage: string, error: unknown): void {
|
||||
const message = formatErrorMessage(error);
|
||||
const detail =
|
||||
error instanceof Error && typeof error.stack === "string" ? `\n${error.stack}` : "";
|
||||
writeDesktopLogHeader(`fatal startup error stage=${stage} message=${message}`);
|
||||
console.error(`[desktop] fatal startup error (${stage})`, error);
|
||||
if (!isQuitting) {
|
||||
isQuitting = true;
|
||||
dialog.showErrorBox("T3 Code failed to start", `Stage: ${stage}\n${message}${detail}`);
|
||||
}
|
||||
stopBackend();
|
||||
restoreStdIoCapture?.();
|
||||
app.quit();
|
||||
}
|
||||
|
||||
function registerDesktopProtocol(): void {
|
||||
if (isDevelopment || desktopProtocolRegistered) return;
|
||||
|
||||
@@ -201,19 +407,19 @@ function registerDesktopProtocol(): void {
|
||||
);
|
||||
}
|
||||
|
||||
const staticRootResolved = path.resolve(staticRoot);
|
||||
const staticRootPrefix = `${staticRootResolved}${path.sep}`;
|
||||
const fallbackIndex = path.join(staticRootResolved, "index.html");
|
||||
const staticRootResolved = Path.resolve(staticRoot);
|
||||
const staticRootPrefix = `${staticRootResolved}${Path.sep}`;
|
||||
const fallbackIndex = Path.join(staticRootResolved, "index.html");
|
||||
|
||||
protocol.registerFileProtocol(DESKTOP_SCHEME, (request, callback) => {
|
||||
try {
|
||||
const candidate = resolveDesktopStaticPath(staticRootResolved, request.url);
|
||||
const resolvedCandidate = path.resolve(candidate);
|
||||
const resolvedCandidate = Path.resolve(candidate);
|
||||
const isInRoot =
|
||||
resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
|
||||
const isAssetRequest = isStaticAssetRequest(request.url);
|
||||
|
||||
if (!isInRoot || !fs.existsSync(resolvedCandidate)) {
|
||||
if (!isInRoot || !FS.existsSync(resolvedCandidate)) {
|
||||
if (isAssetRequest) {
|
||||
callback({ error: -6 });
|
||||
return;
|
||||
@@ -256,6 +462,32 @@ function dispatchMenuAction(action: string): void {
|
||||
send();
|
||||
}
|
||||
|
||||
function handleCheckForUpdatesMenuClick(): void {
|
||||
const disabledReason = getAutoUpdateDisabledReason({
|
||||
isDevelopment,
|
||||
isPackaged: app.isPackaged,
|
||||
platform: process.platform,
|
||||
appImage: process.env.APPIMAGE,
|
||||
disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
|
||||
});
|
||||
if (disabledReason) {
|
||||
console.info("[desktop-updater] Manual update check requested, but updates are disabled.");
|
||||
void dialog.showMessageBox({
|
||||
type: "info",
|
||||
title: "Updates unavailable",
|
||||
message: "Automatic updates are not available right now.",
|
||||
detail: disabledReason,
|
||||
buttons: ["OK"],
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!BrowserWindow.getAllWindows().length) {
|
||||
mainWindow = createWindow();
|
||||
}
|
||||
void checkForUpdates("menu");
|
||||
}
|
||||
|
||||
function configureApplicationMenu(): void {
|
||||
const template: MenuItemConstructorOptions[] = [];
|
||||
|
||||
@@ -264,6 +496,11 @@ function configureApplicationMenu(): void {
|
||||
label: app.name,
|
||||
submenu: [
|
||||
{ role: "about" },
|
||||
{
|
||||
label: "Check for Updates...",
|
||||
click: () => handleCheckForUpdatesMenuClick(),
|
||||
},
|
||||
{ type: "separator" },
|
||||
{
|
||||
label: "Settings...",
|
||||
accelerator: "CmdOrCtrl+,",
|
||||
@@ -301,6 +538,15 @@ function configureApplicationMenu(): void {
|
||||
{ role: "editMenu" },
|
||||
{ role: "viewMenu" },
|
||||
{ role: "windowMenu" },
|
||||
{
|
||||
role: "help",
|
||||
submenu: [
|
||||
{
|
||||
label: "Check for Updates...",
|
||||
click: () => handleCheckForUpdatesMenuClick(),
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
|
||||
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
|
||||
@@ -308,13 +554,13 @@ function configureApplicationMenu(): void {
|
||||
|
||||
function resolveResourcePath(fileName: string): string | null {
|
||||
const candidates = [
|
||||
path.join(__dirname, "../resources", fileName),
|
||||
path.join(process.resourcesPath, "resources", fileName),
|
||||
path.join(process.resourcesPath, fileName),
|
||||
Path.join(__dirname, "../resources", fileName),
|
||||
Path.join(process.resourcesPath, "resources", fileName),
|
||||
Path.join(process.resourcesPath, fileName),
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (fs.existsSync(candidate)) {
|
||||
if (FS.existsSync(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
@@ -347,24 +593,200 @@ function configureAppIdentity(): void {
|
||||
}
|
||||
}
|
||||
|
||||
async function reserveLoopbackPort(): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const probe = net.createServer();
|
||||
probe.listen(0, "127.0.0.1", () => {
|
||||
const address = probe.address();
|
||||
const port = typeof address === "object" && address !== null ? address.port : 0;
|
||||
probe.close(() => {
|
||||
if (port > 0) {
|
||||
resolve(port);
|
||||
return;
|
||||
}
|
||||
reject(new Error("Failed to reserve backend port"));
|
||||
});
|
||||
});
|
||||
probe.on("error", reject);
|
||||
});
|
||||
function clearUpdatePollTimer(): void {
|
||||
if (updateStartupTimer) {
|
||||
clearTimeout(updateStartupTimer);
|
||||
updateStartupTimer = null;
|
||||
}
|
||||
if (updatePollTimer) {
|
||||
clearInterval(updatePollTimer);
|
||||
updatePollTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function emitUpdateState(): void {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (window.isDestroyed()) continue;
|
||||
window.webContents.send(UPDATE_STATE_CHANNEL, updateState);
|
||||
}
|
||||
}
|
||||
|
||||
function setUpdateState(patch: Partial<DesktopUpdateState>): void {
|
||||
updateState = { ...updateState, ...patch };
|
||||
emitUpdateState();
|
||||
}
|
||||
|
||||
function shouldEnableAutoUpdates(): boolean {
|
||||
return (
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment,
|
||||
isPackaged: app.isPackaged,
|
||||
platform: process.platform,
|
||||
appImage: process.env.APPIMAGE,
|
||||
disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
|
||||
}) === null
|
||||
);
|
||||
}
|
||||
|
||||
async function checkForUpdates(reason: string): Promise<void> {
|
||||
if (isQuitting || !updaterConfigured || updateCheckInFlight) return;
|
||||
if (updateState.status === "downloading" || updateState.status === "downloaded") {
|
||||
console.info(
|
||||
`[desktop-updater] Skipping update check (${reason}) while status=${updateState.status}.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
updateCheckInFlight = true;
|
||||
setUpdateState(reduceDesktopUpdateStateOnCheckStart(updateState, new Date().toISOString()));
|
||||
console.info(`[desktop-updater] Checking for updates (${reason})...`);
|
||||
|
||||
try {
|
||||
await autoUpdater.checkForUpdates();
|
||||
} 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}`);
|
||||
} finally {
|
||||
updateCheckInFlight = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadAvailableUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
|
||||
if (!updaterConfigured || updateDownloadInFlight || updateState.status !== "available") {
|
||||
return { accepted: false, completed: false };
|
||||
}
|
||||
updateDownloadInFlight = true;
|
||||
setUpdateState(reduceDesktopUpdateStateOnDownloadStart(updateState));
|
||||
console.info("[desktop-updater] Downloading update...");
|
||||
|
||||
try {
|
||||
await autoUpdater.downloadUpdate();
|
||||
return { accepted: true, completed: true };
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
setUpdateState(reduceDesktopUpdateStateOnDownloadFailure(updateState, message));
|
||||
console.error(`[desktop-updater] Failed to download update: ${message}`);
|
||||
return { accepted: true, completed: false };
|
||||
} finally {
|
||||
updateDownloadInFlight = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
|
||||
if (isQuitting || !updaterConfigured || updateState.status !== "downloaded") {
|
||||
return { accepted: false, completed: false };
|
||||
}
|
||||
|
||||
isQuitting = true;
|
||||
clearUpdatePollTimer();
|
||||
try {
|
||||
await stopBackendAndWaitForExit();
|
||||
autoUpdater.quitAndInstall();
|
||||
return { accepted: true, completed: true };
|
||||
} catch (error: unknown) {
|
||||
const message = formatErrorMessage(error);
|
||||
isQuitting = false;
|
||||
setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
|
||||
console.error(`[desktop-updater] Failed to install update: ${message}`);
|
||||
return { accepted: true, completed: false };
|
||||
}
|
||||
}
|
||||
|
||||
function configureAutoUpdater(): void {
|
||||
const enabled = shouldEnableAutoUpdates();
|
||||
setUpdateState({
|
||||
...createInitialDesktopUpdateState(app.getVersion()),
|
||||
enabled,
|
||||
status: enabled ? "idle" : "disabled",
|
||||
});
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
updaterConfigured = true;
|
||||
|
||||
const githubToken =
|
||||
process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() ||
|
||||
process.env.GH_TOKEN?.trim() ||
|
||||
"";
|
||||
if (githubToken) {
|
||||
// When a token is provided, re-configure the feed with `private: true` so
|
||||
// electron-updater uses the GitHub API (api.github.com) instead of the
|
||||
// public Atom feed (github.com/…/releases.atom) which rejects Bearer auth.
|
||||
const appUpdateYml = readAppUpdateYml();
|
||||
if (appUpdateYml?.provider === "github") {
|
||||
autoUpdater.setFeedURL({
|
||||
...appUpdateYml,
|
||||
provider: "github" as const,
|
||||
private: true,
|
||||
token: githubToken,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
autoUpdater.autoDownload = false;
|
||||
autoUpdater.autoInstallOnAppQuit = false;
|
||||
autoUpdater.allowPrerelease = app.getVersion().includes("-");
|
||||
let lastLoggedDownloadMilestone = -1;
|
||||
|
||||
autoUpdater.on("checking-for-update", () => {
|
||||
console.info("[desktop-updater] Looking for updates...");
|
||||
});
|
||||
autoUpdater.on("update-available", (info) => {
|
||||
setUpdateState(reduceDesktopUpdateStateOnUpdateAvailable(updateState, info.version, new Date().toISOString()));
|
||||
lastLoggedDownloadMilestone = -1;
|
||||
console.info(`[desktop-updater] Update available: ${info.version}`);
|
||||
});
|
||||
autoUpdater.on("update-not-available", () => {
|
||||
setUpdateState(reduceDesktopUpdateStateOnNoUpdate(updateState, new Date().toISOString()));
|
||||
lastLoggedDownloadMilestone = -1;
|
||||
console.info("[desktop-updater] No updates available.");
|
||||
});
|
||||
autoUpdater.on("error", (error) => {
|
||||
const message = formatErrorMessage(error);
|
||||
if (!updateCheckInFlight && !updateDownloadInFlight) {
|
||||
setUpdateState({
|
||||
status: "error",
|
||||
message,
|
||||
checkedAt: new Date().toISOString(),
|
||||
downloadPercent: null,
|
||||
errorContext: resolveUpdaterErrorContext(),
|
||||
canRetry: updateState.availableVersion !== null || updateState.downloadedVersion !== null,
|
||||
});
|
||||
}
|
||||
console.error(`[desktop-updater] Updater error: ${message}`);
|
||||
});
|
||||
autoUpdater.on("download-progress", (progress) => {
|
||||
const percent = Math.floor(progress.percent);
|
||||
if (
|
||||
shouldBroadcastDownloadProgress(updateState, progress.percent) ||
|
||||
updateState.message !== null
|
||||
) {
|
||||
setUpdateState(reduceDesktopUpdateStateOnDownloadProgress(updateState, progress.percent));
|
||||
}
|
||||
const milestone = percent - (percent % 10);
|
||||
if (milestone > lastLoggedDownloadMilestone) {
|
||||
lastLoggedDownloadMilestone = milestone;
|
||||
console.info(`[desktop-updater] Download progress: ${percent}%`);
|
||||
}
|
||||
});
|
||||
autoUpdater.on("update-downloaded", (info) => {
|
||||
setUpdateState(reduceDesktopUpdateStateOnDownloadComplete(updateState, info.version));
|
||||
console.info(`[desktop-updater] Update downloaded: ${info.version}`);
|
||||
});
|
||||
|
||||
clearUpdatePollTimer();
|
||||
|
||||
updateStartupTimer = setTimeout(() => {
|
||||
updateStartupTimer = null;
|
||||
void checkForUpdates("startup");
|
||||
}, AUTO_UPDATE_STARTUP_DELAY_MS);
|
||||
updateStartupTimer.unref();
|
||||
|
||||
updatePollTimer = setInterval(() => {
|
||||
void checkForUpdates("poll");
|
||||
}, AUTO_UPDATE_POLL_INTERVAL_MS);
|
||||
updatePollTimer.unref();
|
||||
}
|
||||
function backendEnv(): NodeJS.ProcessEnv {
|
||||
return {
|
||||
...process.env,
|
||||
@@ -393,12 +815,13 @@ function startBackend(): void {
|
||||
if (isQuitting || backendProcess) return;
|
||||
|
||||
const backendEntry = resolveBackendEntry();
|
||||
if (!fs.existsSync(backendEntry)) {
|
||||
if (!FS.existsSync(backendEntry)) {
|
||||
scheduleBackendRestart(`missing server entry at ${backendEntry}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const child = spawn(process.execPath, [backendEntry], {
|
||||
const captureBackendLogs = app.isPackaged && backendLogSink !== null;
|
||||
const child = ChildProcess.spawn(process.execPath, [backendEntry], {
|
||||
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.
|
||||
@@ -406,9 +829,20 @@ function startBackend(): void {
|
||||
...backendEnv(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
stdio: "inherit",
|
||||
stdio: captureBackendLogs ? ["ignore", "pipe", "pipe"] : "inherit",
|
||||
});
|
||||
backendProcess = child;
|
||||
let backendSessionClosed = false;
|
||||
const closeBackendSession = (details: string) => {
|
||||
if (backendSessionClosed) return;
|
||||
backendSessionClosed = true;
|
||||
writeBackendSessionBoundary("END", details);
|
||||
};
|
||||
writeBackendSessionBoundary(
|
||||
"START",
|
||||
`pid=${child.pid ?? "unknown"} port=${backendPort} cwd=${resolveBackendCwd()}`,
|
||||
);
|
||||
captureBackendOutput(child);
|
||||
|
||||
child.once("spawn", () => {
|
||||
restartAttempt = 0;
|
||||
@@ -418,6 +852,7 @@ function startBackend(): void {
|
||||
if (backendProcess === child) {
|
||||
backendProcess = null;
|
||||
}
|
||||
closeBackendSession(`pid=${child.pid ?? "unknown"} error=${error.message}`);
|
||||
scheduleBackendRestart(error.message);
|
||||
});
|
||||
|
||||
@@ -425,6 +860,9 @@ function startBackend(): void {
|
||||
if (backendProcess === child) {
|
||||
backendProcess = null;
|
||||
}
|
||||
closeBackendSession(
|
||||
`pid=${child.pid ?? "unknown"} code=${code ?? "null"} signal=${signal ?? "null"}`,
|
||||
);
|
||||
if (isQuitting) return;
|
||||
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
|
||||
scheduleBackendRestart(reason);
|
||||
@@ -451,6 +889,57 @@ function stopBackend(): void {
|
||||
}
|
||||
}
|
||||
|
||||
async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
restartTimer = null;
|
||||
}
|
||||
|
||||
const child = backendProcess;
|
||||
backendProcess = null;
|
||||
if (!child) return;
|
||||
const backendChild = child;
|
||||
if (backendChild.exitCode !== null || backendChild.signalCode !== null) return;
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
let settled = false;
|
||||
let forceKillTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let exitTimeoutTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
function settle(): void {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
backendChild.off("exit", onExit);
|
||||
if (forceKillTimer) {
|
||||
clearTimeout(forceKillTimer);
|
||||
}
|
||||
if (exitTimeoutTimer) {
|
||||
clearTimeout(exitTimeoutTimer);
|
||||
}
|
||||
resolve();
|
||||
}
|
||||
|
||||
function onExit(): void {
|
||||
settle();
|
||||
}
|
||||
|
||||
backendChild.once("exit", onExit);
|
||||
backendChild.kill("SIGTERM");
|
||||
|
||||
forceKillTimer = setTimeout(() => {
|
||||
if (backendChild.exitCode === null && backendChild.signalCode === null) {
|
||||
backendChild.kill("SIGKILL");
|
||||
}
|
||||
}, 2_000);
|
||||
forceKillTimer.unref();
|
||||
|
||||
exitTimeoutTimer = setTimeout(() => {
|
||||
settle();
|
||||
}, timeoutMs);
|
||||
exitTimeoutTimer.unref();
|
||||
});
|
||||
}
|
||||
|
||||
function registerIpcHandlers(): void {
|
||||
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
|
||||
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
|
||||
@@ -561,6 +1050,36 @@ function registerIpcHandlers(): void {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(UPDATE_GET_STATE_CHANNEL);
|
||||
ipcMain.handle(UPDATE_GET_STATE_CHANNEL, async () => updateState);
|
||||
|
||||
ipcMain.removeHandler(UPDATE_DOWNLOAD_CHANNEL);
|
||||
ipcMain.handle(UPDATE_DOWNLOAD_CHANNEL, async () => {
|
||||
const result = await downloadAvailableUpdate();
|
||||
return {
|
||||
accepted: result.accepted,
|
||||
completed: result.completed,
|
||||
state: updateState,
|
||||
} satisfies DesktopUpdateActionResult;
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(UPDATE_INSTALL_CHANNEL);
|
||||
ipcMain.handle(UPDATE_INSTALL_CHANNEL, async () => {
|
||||
if (isQuitting) {
|
||||
return {
|
||||
accepted: false,
|
||||
completed: false,
|
||||
state: updateState,
|
||||
} satisfies DesktopUpdateActionResult;
|
||||
}
|
||||
const result = await installDownloadedUpdate();
|
||||
return {
|
||||
accepted: result.accepted,
|
||||
completed: result.completed,
|
||||
state: updateState,
|
||||
} satisfies DesktopUpdateActionResult;
|
||||
});
|
||||
}
|
||||
|
||||
function getIconOption(): { icon: string } | Record<string, never> {
|
||||
@@ -583,7 +1102,7 @@ function createWindow(): BrowserWindow {
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, "preload.js"),
|
||||
preload: Path.join(__dirname, "preload.js"),
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: true,
|
||||
@@ -597,6 +1116,7 @@ function createWindow(): BrowserWindow {
|
||||
});
|
||||
window.webContents.on("did-finish-load", () => {
|
||||
window.setTitle(APP_DISPLAY_NAME);
|
||||
emitUpdateState();
|
||||
});
|
||||
window.once("ready-to-show", () => {
|
||||
window.show();
|
||||
@@ -621,33 +1141,55 @@ function createWindow(): BrowserWindow {
|
||||
configureAppIdentity();
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
backendPort = await reserveLoopbackPort();
|
||||
backendAuthToken = randomBytes(24).toString("hex");
|
||||
writeDesktopLogHeader("bootstrap start");
|
||||
backendPort = await Effect.service(NetService).pipe(
|
||||
Effect.flatMap((net) => net.reserveLoopbackPort()),
|
||||
Effect.provide(NetService.layer),
|
||||
Effect.runPromise,
|
||||
);
|
||||
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}`);
|
||||
|
||||
registerIpcHandlers();
|
||||
writeDesktopLogHeader("bootstrap ipc handlers registered");
|
||||
startBackend();
|
||||
writeDesktopLogHeader("bootstrap backend start requested");
|
||||
mainWindow = createWindow();
|
||||
writeDesktopLogHeader("bootstrap main window created");
|
||||
}
|
||||
|
||||
app.on("before-quit", () => {
|
||||
isQuitting = true;
|
||||
writeDesktopLogHeader("before-quit received");
|
||||
clearUpdatePollTimer();
|
||||
stopBackend();
|
||||
restoreStdIoCapture?.();
|
||||
});
|
||||
|
||||
app.whenReady().then(() => {
|
||||
configureAppIdentity();
|
||||
configureApplicationMenu();
|
||||
registerDesktopProtocol();
|
||||
void bootstrap();
|
||||
app
|
||||
.whenReady()
|
||||
.then(() => {
|
||||
writeDesktopLogHeader("app ready");
|
||||
configureAppIdentity();
|
||||
configureApplicationMenu();
|
||||
registerDesktopProtocol();
|
||||
configureAutoUpdater();
|
||||
void bootstrap().catch((error) => {
|
||||
handleFatalStartupError("bootstrap", error);
|
||||
});
|
||||
|
||||
app.on("activate", () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
mainWindow = createWindow();
|
||||
}
|
||||
app.on("activate", () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
mainWindow = createWindow();
|
||||
}
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
handleFatalStartupError("whenReady", error);
|
||||
});
|
||||
});
|
||||
|
||||
app.on("window-all-closed", () => {
|
||||
if (process.platform !== "darwin") {
|
||||
@@ -659,14 +1201,20 @@ if (process.platform !== "win32") {
|
||||
process.on("SIGINT", () => {
|
||||
if (isQuitting) return;
|
||||
isQuitting = true;
|
||||
writeDesktopLogHeader("SIGINT received");
|
||||
clearUpdatePollTimer();
|
||||
stopBackend();
|
||||
restoreStdIoCapture?.();
|
||||
app.quit();
|
||||
});
|
||||
|
||||
process.on("SIGTERM", () => {
|
||||
if (isQuitting) return;
|
||||
isQuitting = true;
|
||||
writeDesktopLogHeader("SIGTERM received");
|
||||
clearUpdatePollTimer();
|
||||
stopBackend();
|
||||
restoreStdIoCapture?.();
|
||||
app.quit();
|
||||
});
|
||||
}
|
||||
@@ -6,6 +6,10 @@ const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
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_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
||||
|
||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
@@ -25,4 +29,18 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
ipcRenderer.removeListener(MENU_ACTION_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
|
||||
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
|
||||
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
|
||||
onUpdateState: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, state: unknown) => {
|
||||
if (typeof state !== "object" || state === null) return;
|
||||
listener(state as Parameters<typeof listener>[0]);
|
||||
};
|
||||
|
||||
ipcRenderer.on(UPDATE_STATE_CHANNEL, wrappedListener);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(UPDATE_STATE_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
} satisfies DesktopBridge);
|
||||
@@ -0,0 +1,74 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
const tempRoots: string[] = [];
|
||||
|
||||
function makeTempDir(): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-rotating-log-"));
|
||||
tempRoots.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempRoots.splice(0)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("RotatingFileSink", () => {
|
||||
it("rotates when writes exceed max bytes", () => {
|
||||
const dir = makeTempDir();
|
||||
const logPath = path.join(dir, "desktop-main.log");
|
||||
const sink = new RotatingFileSink({
|
||||
filePath: logPath,
|
||||
maxBytes: 10,
|
||||
maxFiles: 3,
|
||||
});
|
||||
|
||||
sink.write("12345");
|
||||
sink.write("67890");
|
||||
sink.write("abc");
|
||||
|
||||
expect(fs.readFileSync(path.join(dir, "desktop-main.log"), "utf8")).toBe("abc");
|
||||
expect(fs.readFileSync(path.join(dir, "desktop-main.log.1"), "utf8")).toBe("1234567890");
|
||||
});
|
||||
|
||||
it("retains only maxFiles backups", () => {
|
||||
const dir = makeTempDir();
|
||||
const logPath = path.join(dir, "server-child.log");
|
||||
const sink = new RotatingFileSink({
|
||||
filePath: logPath,
|
||||
maxBytes: 4,
|
||||
maxFiles: 2,
|
||||
});
|
||||
|
||||
sink.write("aaaa");
|
||||
sink.write("bbbb");
|
||||
sink.write("cccc");
|
||||
sink.write("dddd");
|
||||
|
||||
expect(fs.existsSync(path.join(dir, "server-child.log.1"))).toBe(true);
|
||||
expect(fs.existsSync(path.join(dir, "server-child.log.2"))).toBe(true);
|
||||
expect(fs.existsSync(path.join(dir, "server-child.log.3"))).toBe(false);
|
||||
});
|
||||
|
||||
it("prunes stale backups above maxFiles on startup", () => {
|
||||
const dir = makeTempDir();
|
||||
const logPath = path.join(dir, "desktop-main.log");
|
||||
fs.writeFileSync(path.join(dir, "desktop-main.log.1"), "first");
|
||||
fs.writeFileSync(path.join(dir, "desktop-main.log.4"), "stale");
|
||||
|
||||
const sink = new RotatingFileSink({
|
||||
filePath: logPath,
|
||||
maxBytes: 16,
|
||||
maxFiles: 2,
|
||||
});
|
||||
sink.write("hello");
|
||||
|
||||
expect(fs.existsSync(path.join(dir, "desktop-main.log.4"))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,130 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createInitialDesktopUpdateState,
|
||||
reduceDesktopUpdateStateOnCheckFailure,
|
||||
reduceDesktopUpdateStateOnCheckStart,
|
||||
reduceDesktopUpdateStateOnDownloadComplete,
|
||||
reduceDesktopUpdateStateOnDownloadFailure,
|
||||
reduceDesktopUpdateStateOnDownloadProgress,
|
||||
reduceDesktopUpdateStateOnDownloadStart,
|
||||
reduceDesktopUpdateStateOnInstallFailure,
|
||||
reduceDesktopUpdateStateOnNoUpdate,
|
||||
reduceDesktopUpdateStateOnUpdateAvailable,
|
||||
} from "./updateMachine";
|
||||
|
||||
describe("updateMachine", () => {
|
||||
it("clears transient errors when a check starts", () => {
|
||||
const state = reduceDesktopUpdateStateOnCheckStart(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "error",
|
||||
message: "network",
|
||||
errorContext: "check",
|
||||
canRetry: true,
|
||||
},
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(state.status).toBe("checking");
|
||||
expect(state.message).toBeNull();
|
||||
expect(state.errorContext).toBeNull();
|
||||
expect(state.canRetry).toBe(false);
|
||||
});
|
||||
|
||||
it("records a check failure without exposing an action", () => {
|
||||
const state = reduceDesktopUpdateStateOnCheckFailure(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "checking",
|
||||
},
|
||||
"network unavailable",
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(state.status).toBe("error");
|
||||
expect(state.errorContext).toBe("check");
|
||||
expect(state.canRetry).toBe(true);
|
||||
});
|
||||
|
||||
it("preserves available version on download failure for retry", () => {
|
||||
const state = reduceDesktopUpdateStateOnDownloadFailure(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
downloadPercent: 43,
|
||||
},
|
||||
"checksum mismatch",
|
||||
);
|
||||
|
||||
expect(state.status).toBe("available");
|
||||
expect(state.availableVersion).toBe("1.1.0");
|
||||
expect(state.errorContext).toBe("download");
|
||||
expect(state.canRetry).toBe(true);
|
||||
});
|
||||
|
||||
it("transitions to downloaded and then preserves install retry state", () => {
|
||||
const downloaded = reduceDesktopUpdateStateOnDownloadComplete(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
},
|
||||
"1.1.0",
|
||||
);
|
||||
const failedInstall = reduceDesktopUpdateStateOnInstallFailure(downloaded, "backend shutdown timed out");
|
||||
|
||||
expect(downloaded.status).toBe("downloaded");
|
||||
expect(downloaded.downloadedVersion).toBe("1.1.0");
|
||||
expect(failedInstall.status).toBe("downloaded");
|
||||
expect(failedInstall.errorContext).toBe("install");
|
||||
expect(failedInstall.canRetry).toBe(true);
|
||||
});
|
||||
|
||||
it("clears stale download state when no update is available", () => {
|
||||
const state = reduceDesktopUpdateStateOnNoUpdate(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "error",
|
||||
availableVersion: "1.1.0",
|
||||
downloadedVersion: "1.1.0",
|
||||
message: "old failure",
|
||||
errorContext: "download",
|
||||
canRetry: true,
|
||||
},
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(state.status).toBe("up-to-date");
|
||||
expect(state.availableVersion).toBeNull();
|
||||
expect(state.downloadedVersion).toBeNull();
|
||||
expect(state.message).toBeNull();
|
||||
expect(state.errorContext).toBeNull();
|
||||
});
|
||||
|
||||
it("tracks available, download start, and progress cleanly", () => {
|
||||
const available = reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "checking",
|
||||
},
|
||||
"1.1.0",
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
const downloading = reduceDesktopUpdateStateOnDownloadStart(available);
|
||||
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
|
||||
|
||||
expect(available.status).toBe("available");
|
||||
expect(downloading.status).toBe("downloading");
|
||||
expect(downloading.downloadPercent).toBe(0);
|
||||
expect(progress.downloadPercent).toBe(55.5);
|
||||
expect(progress.errorContext).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
|
||||
|
||||
export function createInitialDesktopUpdateState(currentVersion: string): DesktopUpdateState {
|
||||
return {
|
||||
enabled: false,
|
||||
status: "disabled",
|
||||
currentVersion,
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnCheckStart(
|
||||
state: DesktopUpdateState,
|
||||
checkedAt: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "checking",
|
||||
checkedAt,
|
||||
message: null,
|
||||
downloadPercent: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnCheckFailure(
|
||||
state: DesktopUpdateState,
|
||||
message: string,
|
||||
checkedAt: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "error",
|
||||
message,
|
||||
checkedAt,
|
||||
downloadPercent: null,
|
||||
errorContext: "check",
|
||||
canRetry: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
state: DesktopUpdateState,
|
||||
version: string,
|
||||
checkedAt: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "available",
|
||||
availableVersion: version,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnNoUpdate(
|
||||
state: DesktopUpdateState,
|
||||
checkedAt: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "up-to-date",
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnDownloadStart(
|
||||
state: DesktopUpdateState,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "downloading",
|
||||
downloadPercent: 0,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnDownloadFailure(
|
||||
state: DesktopUpdateState,
|
||||
message: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: nextStatusAfterDownloadFailure(state),
|
||||
message,
|
||||
downloadPercent: null,
|
||||
errorContext: "download",
|
||||
canRetry: getCanRetryAfterDownloadFailure(state),
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnDownloadProgress(
|
||||
state: DesktopUpdateState,
|
||||
percent: number,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "downloading",
|
||||
downloadPercent: percent,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnDownloadComplete(
|
||||
state: DesktopUpdateState,
|
||||
version: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "downloaded",
|
||||
availableVersion: version,
|
||||
downloadedVersion: version,
|
||||
downloadPercent: 100,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnInstallFailure(
|
||||
state: DesktopUpdateState,
|
||||
message: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "downloaded",
|
||||
message,
|
||||
errorContext: "install",
|
||||
canRetry: true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
getCanRetryAfterDownloadFailure,
|
||||
getAutoUpdateDisabledReason,
|
||||
nextStatusAfterDownloadFailure,
|
||||
shouldBroadcastDownloadProgress,
|
||||
} from "./updateState";
|
||||
|
||||
const baseState: DesktopUpdateState = {
|
||||
enabled: true,
|
||||
status: "idle",
|
||||
currentVersion: "1.0.0",
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
|
||||
describe("shouldBroadcastDownloadProgress", () => {
|
||||
it("broadcasts the first downloading progress update", () => {
|
||||
expect(
|
||||
shouldBroadcastDownloadProgress(
|
||||
{ ...baseState, status: "downloading", downloadPercent: null },
|
||||
1,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("skips progress updates within the same 10% bucket", () => {
|
||||
expect(
|
||||
shouldBroadcastDownloadProgress(
|
||||
{ ...baseState, status: "downloading", downloadPercent: 11.2 },
|
||||
18.7,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("broadcasts progress updates when a new 10% bucket is reached", () => {
|
||||
expect(
|
||||
shouldBroadcastDownloadProgress(
|
||||
{ ...baseState, status: "downloading", downloadPercent: 19.9 },
|
||||
20.1,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("broadcasts progress updates when a retry resets the download percentage", () => {
|
||||
expect(
|
||||
shouldBroadcastDownloadProgress(
|
||||
{ ...baseState, status: "downloading", downloadPercent: 50.4 },
|
||||
0.2,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAutoUpdateDisabledReason", () => {
|
||||
it("reports development builds as disabled", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment: true,
|
||||
isPackaged: false,
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
}),
|
||||
).toContain("packaged production builds");
|
||||
});
|
||||
|
||||
it("reports env-disabled auto updates", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment: false,
|
||||
isPackaged: true,
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: true,
|
||||
}),
|
||||
).toContain("T3CODE_DISABLE_AUTO_UPDATE");
|
||||
});
|
||||
|
||||
it("reports linux non-AppImage builds as disabled", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment: false,
|
||||
isPackaged: true,
|
||||
platform: "linux",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
}),
|
||||
).toContain("AppImage");
|
||||
});
|
||||
});
|
||||
|
||||
describe("nextStatusAfterDownloadFailure", () => {
|
||||
it("returns available when an update version is still known", () => {
|
||||
expect(
|
||||
nextStatusAfterDownloadFailure({
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
}),
|
||||
).toBe("available");
|
||||
});
|
||||
|
||||
it("returns error when no update version can be retried", () => {
|
||||
expect(
|
||||
nextStatusAfterDownloadFailure({
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: null,
|
||||
}),
|
||||
).toBe("error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getCanRetryAfterDownloadFailure", () => {
|
||||
it("returns true when an available version is still present", () => {
|
||||
expect(
|
||||
getCanRetryAfterDownloadFailure({
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when no version is available to retry", () => {
|
||||
expect(
|
||||
getCanRetryAfterDownloadFailure({
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
export function shouldBroadcastDownloadProgress(
|
||||
currentState: DesktopUpdateState,
|
||||
nextPercent: number,
|
||||
): boolean {
|
||||
if (currentState.status !== "downloading") {
|
||||
return true;
|
||||
}
|
||||
|
||||
const currentPercent = currentState.downloadPercent;
|
||||
if (currentPercent === null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const previousStep = Math.floor(currentPercent / 10);
|
||||
const nextStep = Math.floor(nextPercent / 10);
|
||||
return nextStep !== previousStep || nextPercent === 100;
|
||||
}
|
||||
|
||||
export function nextStatusAfterDownloadFailure(
|
||||
currentState: DesktopUpdateState,
|
||||
): DesktopUpdateState["status"] {
|
||||
return currentState.availableVersion ? "available" : "error";
|
||||
}
|
||||
|
||||
export function getCanRetryAfterDownloadFailure(currentState: DesktopUpdateState): boolean {
|
||||
return currentState.availableVersion !== null;
|
||||
}
|
||||
|
||||
export function getAutoUpdateDisabledReason(args: {
|
||||
isDevelopment: boolean;
|
||||
isPackaged: boolean;
|
||||
platform: NodeJS.Platform;
|
||||
appImage?: string | undefined;
|
||||
disabledByEnv: boolean;
|
||||
}): string | null {
|
||||
if (args.isDevelopment || !args.isPackaged) {
|
||||
return "Automatic updates are only available in packaged production builds.";
|
||||
}
|
||||
if (args.disabledByEnv) {
|
||||
return "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.";
|
||||
}
|
||||
if (args.platform === "linux" && !args.appImage) {
|
||||
return "Automatic updates on Linux require running the AppImage build.";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -12,7 +12,7 @@ export default defineConfig([
|
||||
...shared,
|
||||
entry: ["src/main.ts"],
|
||||
clean: true,
|
||||
noExternal: ["@t3tools/contracts"],
|
||||
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||
},
|
||||
{
|
||||
...shared,
|
||||
|
||||
+13
-10
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"bin": {
|
||||
"t3": "./dist/index.mjs"
|
||||
},
|
||||
@@ -8,10 +8,9 @@
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "./dist/index.mjs",
|
||||
"scripts": {
|
||||
"dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5733} bun run src/index.ts",
|
||||
"build": "tsdown && node scripts/bundle-client.ts",
|
||||
"dev": "bun run src/index.ts",
|
||||
"build": "node scripts/cli.ts build",
|
||||
"start": "node dist/index.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
@@ -27,15 +26,19 @@
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "0.75.1",
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/bun": "^1.3.9",
|
||||
"@types/node": "^24.10.13",
|
||||
"@types/bun": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"@types/ws": "^8.5.13",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0"
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.13 || ^23.4 || >=24.10"
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
/**
|
||||
* Copies the built web app into dist/client/ so the published npm package
|
||||
* includes the web UI. This runs as a post-build step.
|
||||
*/
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
|
||||
const webDist = path.resolve(import.meta.dirname, "../../web/dist");
|
||||
const target = path.resolve(import.meta.dirname, "../dist/client");
|
||||
|
||||
if (!fs.existsSync(webDist)) {
|
||||
console.log(
|
||||
"⚠ Web dist not found — skipping client bundle. Run `bun run --cwd apps/web build` first.",
|
||||
);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
fs.cpSync(webDist, target, { recursive: true });
|
||||
console.log("✓ Bundled web app into dist/client");
|
||||
@@ -0,0 +1,170 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Data, Effect, FileSystem, Logger, Option, Path } from "effect";
|
||||
import { Command, Flag } from "effect/unstable/cli";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
|
||||
import rootPackageJson from "../../../package.json" with { type: "json" };
|
||||
import serverPackageJson from "../package.json" with { type: "json" };
|
||||
|
||||
class CliError extends Data.TaggedError("CliError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
const RepoRoot = Effect.service(Path.Path).pipe(
|
||||
Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
|
||||
);
|
||||
|
||||
const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const child = yield* spawner.spawn(command);
|
||||
const exitCode = yield* child.exitCode;
|
||||
|
||||
if (exitCode !== 0) {
|
||||
return yield* new CliError({
|
||||
message: `Command exited with non-zero exit code (${exitCode})`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// build subcommand
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const buildCmd = Command.make(
|
||||
"build",
|
||||
{
|
||||
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
|
||||
},
|
||||
(config) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const serverDir = path.join(repoRoot, "apps/server");
|
||||
|
||||
yield* Effect.log("[cli] Running tsdown...");
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
})`bun tsdown`,
|
||||
);
|
||||
|
||||
const webDist = path.join(repoRoot, "apps/web/dist");
|
||||
const clientTarget = path.join(serverDir, "dist/client");
|
||||
|
||||
if (yield* fs.exists(webDist)) {
|
||||
yield* fs.copy(webDist, clientTarget);
|
||||
yield* Effect.log("[cli] Bundled web app into dist/client");
|
||||
} else {
|
||||
yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
|
||||
}
|
||||
}),
|
||||
).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// publish subcommand
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const publishCmd = Command.make(
|
||||
"publish",
|
||||
{
|
||||
tag: Flag.string("tag").pipe(Flag.withDefault("latest")),
|
||||
access: Flag.string("access").pipe(Flag.withDefault("public")),
|
||||
appVersion: Flag.string("app-version").pipe(Flag.optional),
|
||||
provenance: Flag.boolean("provenance").pipe(Flag.withDefault(false)),
|
||||
dryRun: Flag.boolean("dry-run").pipe(Flag.withDefault(false)),
|
||||
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
|
||||
},
|
||||
(config) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const serverDir = path.join(repoRoot, "apps/server");
|
||||
const packageJsonPath = path.join(serverDir, "package.json");
|
||||
const backupPath = `${packageJsonPath}.bak`;
|
||||
|
||||
// Assert build assets exist
|
||||
for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
|
||||
const abs = path.join(serverDir, relPath);
|
||||
if (!(yield* fs.exists(abs))) {
|
||||
return yield* new CliError({
|
||||
message: `Missing build asset: ${abs}. Run the build subcommand first.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
yield* Effect.acquireUseRelease(
|
||||
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
|
||||
Effect.gen(function* () {
|
||||
const original = yield* fs.readFileString(packageJsonPath);
|
||||
yield* fs.writeFileString(backupPath, original);
|
||||
|
||||
// Build package.json for publish
|
||||
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
|
||||
const pkg = {
|
||||
name: serverPackageJson.name,
|
||||
type: serverPackageJson.type,
|
||||
version,
|
||||
engines: serverPackageJson.engines,
|
||||
files: serverPackageJson.files,
|
||||
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
|
||||
};
|
||||
|
||||
// Resolve catalog: entries in production dependencies
|
||||
pkg.dependencies = resolveCatalogDependencies(
|
||||
pkg.dependencies,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"apps/server dependencies",
|
||||
);
|
||||
|
||||
yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
|
||||
yield* Effect.log("[cli] Resolved package.json for publish");
|
||||
}),
|
||||
// Use: npm publish
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const args = ["publish", "--access", config.access, "--tag", config.tag];
|
||||
if (config.provenance) args.push("--provenance");
|
||||
if (config.dryRun) args.push("--dry-run");
|
||||
|
||||
yield* Effect.log(`[cli] Running: npm ${args.join(" ")}`);
|
||||
yield* runCommand(
|
||||
ChildProcess.make("npm", [...args], {
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
}),
|
||||
);
|
||||
}),
|
||||
// Release: restore
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
yield* fs.rename(backupPath, packageJsonPath);
|
||||
if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
|
||||
}),
|
||||
);
|
||||
}),
|
||||
).pipe(Command.withDescription("Publish the server package to npm."));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// root command
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const cli = Command.make("cli").pipe(
|
||||
Command.withDescription("T3 server build & publish CLI."),
|
||||
Command.withSubcommands([buildCmd, publishCmd]),
|
||||
);
|
||||
|
||||
Command.run(cli, { version: "0.0.0" }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
@@ -1,17 +1,44 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Cause } from "effect";
|
||||
import { ManagedRuntime, ServiceMap } from "effect";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { ProviderSessionId } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
CodexAppServerManager,
|
||||
classifyCodexStderrLine,
|
||||
isRecoverableThreadResumeError,
|
||||
messageFromCodexProcessCause,
|
||||
normalizeCodexModelSlug,
|
||||
} from "./codexAppServerManager";
|
||||
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
|
||||
let runtime: ManagedRuntime.ManagedRuntime<NodeServices.NodeServices, never> | null = null;
|
||||
let services: ServiceMap.ServiceMap<NodeServices.NodeServices> | null = null;
|
||||
|
||||
beforeEach(async () => {
|
||||
runtime = ManagedRuntime.make(NodeServices.layer);
|
||||
services = await runtime.services();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
services = null;
|
||||
if (runtime) {
|
||||
await runtime.dispose();
|
||||
}
|
||||
runtime = null;
|
||||
});
|
||||
|
||||
function createManager() {
|
||||
if (!services) {
|
||||
throw new Error("Test runtime services not initialized.");
|
||||
}
|
||||
return new CodexAppServerManager(services);
|
||||
}
|
||||
|
||||
function createSendTurnHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
const manager = createManager();
|
||||
const context = {
|
||||
session: {
|
||||
sessionId: "sess_1",
|
||||
@@ -47,7 +74,7 @@ function createSendTurnHarness() {
|
||||
}
|
||||
|
||||
function createThreadControlHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
const manager = createManager();
|
||||
const context = {
|
||||
session: {
|
||||
sessionId: "sess_1",
|
||||
@@ -146,9 +173,15 @@ describe("isRecoverableThreadResumeError", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("messageFromCodexProcessCause", () => {
|
||||
it("extracts the underlying error message from an effect cause", () => {
|
||||
expect(messageFromCodexProcessCause(Cause.fail(new Error("boom")))).toBe("boom");
|
||||
});
|
||||
});
|
||||
|
||||
describe("startSession", () => {
|
||||
it("emits session/startFailed when resolving cwd throws before process launch", async () => {
|
||||
const manager = new CodexAppServerManager();
|
||||
const manager = createManager();
|
||||
const events: Array<{ method: string; kind: string; message?: string }> = [];
|
||||
manager.on("event", (event) => {
|
||||
events.push({
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { EventEmitter } from "node:events";
|
||||
import readline from "node:readline";
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
@@ -18,6 +16,10 @@ import {
|
||||
type ProviderSessionStartInput,
|
||||
type ProviderTurnStartResult,
|
||||
} from "@t3tools/contracts";
|
||||
import type * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Cause, Effect, Exit, ServiceMap, Scope, Stream } from "effect";
|
||||
import type { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { makeRuntimeCommand, spawnManagedCommand } from "./processRunner";
|
||||
|
||||
type PendingRequestKey = string;
|
||||
|
||||
@@ -40,8 +42,8 @@ interface PendingApprovalRequest {
|
||||
|
||||
interface CodexSessionContext {
|
||||
session: ProviderSession;
|
||||
child: ChildProcessWithoutNullStreams;
|
||||
output: readline.Interface;
|
||||
child: ChildProcessSpawner.ChildProcessHandle;
|
||||
scope: Scope.Closeable;
|
||||
pending: Map<PendingRequestKey, PendingRequest>;
|
||||
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
|
||||
nextRequestId: number;
|
||||
@@ -151,12 +153,32 @@ export function isRecoverableThreadResumeError(error: unknown): boolean {
|
||||
return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) => message.includes(snippet));
|
||||
}
|
||||
|
||||
export function messageFromCodexProcessCause(cause: Cause.Cause<unknown>): string {
|
||||
const squashed = Cause.squash(cause);
|
||||
return squashed instanceof Error ? squashed.message : "codex app-server process errored.";
|
||||
}
|
||||
|
||||
export interface CodexAppServerManagerEvents {
|
||||
event: [event: ProviderEvent];
|
||||
}
|
||||
|
||||
export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {
|
||||
private readonly sessions = new Map<ProviderSessionId, CodexSessionContext>();
|
||||
private readonly runPromise: <A, E>(
|
||||
effect: Effect.Effect<A, E, NodeServices.NodeServices>,
|
||||
options?: Effect.RunOptions | undefined,
|
||||
) => Promise<A>;
|
||||
|
||||
constructor(services?: ServiceMap.ServiceMap<NodeServices.NodeServices>) {
|
||||
super();
|
||||
this.runPromise = services
|
||||
? Effect.runPromiseWith(services)
|
||||
: ((effect, options) =>
|
||||
Effect.runPromise(
|
||||
effect as unknown as Effect.Effect<unknown, never>,
|
||||
options,
|
||||
)) as typeof this.runPromise;
|
||||
}
|
||||
|
||||
async startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
|
||||
const sessionId = ProviderSessionId.makeUnsafe(randomUUID());
|
||||
@@ -178,20 +200,23 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
|
||||
const codexBinaryPath = input.codexBinaryPath ?? "codex";
|
||||
const codexHomePath = input.codexHomePath;
|
||||
const child = spawn(codexBinaryPath, ["app-server"], {
|
||||
cwd: resolvedCwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
|
||||
},
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
const managedProcess = await this.runPromise(
|
||||
spawnManagedCommand(
|
||||
makeRuntimeCommand(codexBinaryPath, ["app-server"], {
|
||||
cwd: resolvedCwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
|
||||
},
|
||||
extendEnv: false,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
context = {
|
||||
session,
|
||||
child,
|
||||
output,
|
||||
child: managedProcess.handle,
|
||||
scope: managedProcess.scope,
|
||||
pending: new Map(),
|
||||
pendingApprovals: new Map(),
|
||||
nextRequestId: 1,
|
||||
@@ -199,7 +224,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
};
|
||||
|
||||
this.sessions.set(sessionId, context);
|
||||
this.attachProcessListeners(context);
|
||||
await this.attachProcessListeners(context);
|
||||
|
||||
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
|
||||
|
||||
@@ -214,7 +239,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
},
|
||||
});
|
||||
|
||||
this.writeMessage(context, { method: "initialized" });
|
||||
await this.writeMessage(context, { method: "initialized" });
|
||||
|
||||
const normalizedModel = normalizeCodexModelSlug(input.model);
|
||||
const sessionOverrides = {
|
||||
@@ -430,7 +455,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
context.pendingApprovals.delete(requestId);
|
||||
this.writeMessage(context, {
|
||||
await this.writeMessage(context, {
|
||||
id: pendingRequest.jsonRpcId,
|
||||
result: {
|
||||
decision,
|
||||
@@ -471,12 +496,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
context.pending.clear();
|
||||
context.pendingApprovals.clear();
|
||||
|
||||
context.output.close();
|
||||
|
||||
if (!context.child.killed) {
|
||||
context.child.kill();
|
||||
}
|
||||
void this.runPromise(Scope.close(context.scope, Exit.void)).catch(() => undefined);
|
||||
|
||||
this.updateSession(context, {
|
||||
status: "closed",
|
||||
@@ -515,47 +535,71 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return context;
|
||||
}
|
||||
|
||||
private attachProcessListeners(context: CodexSessionContext): void {
|
||||
context.output.on("line", (line) => {
|
||||
this.handleStdoutLine(context, line);
|
||||
});
|
||||
private async attachProcessListeners(context: CodexSessionContext): Promise<void> {
|
||||
await this.runPromise(
|
||||
Effect.gen(
|
||||
function* (this: CodexAppServerManager) {
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(Stream.splitLines(Stream.decodeText(context.child.stdout)), (line) =>
|
||||
Effect.sync(() => {
|
||||
this.handleStdoutLine(context, line);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
context.child.stderr.on("data", (chunk: Buffer) => {
|
||||
const raw = chunk.toString();
|
||||
const lines = raw.split(/\r?\n/g);
|
||||
for (const rawLine of lines) {
|
||||
const classified = classifyCodexStderrLine(rawLine);
|
||||
if (!classified) {
|
||||
continue;
|
||||
}
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(Stream.decodeText(context.child.stderr), (raw) =>
|
||||
Effect.sync(() => {
|
||||
const lines = raw.split(/\r?\n/g);
|
||||
for (const rawLine of lines) {
|
||||
const classified = classifyCodexStderrLine(rawLine);
|
||||
if (!classified) {
|
||||
continue;
|
||||
}
|
||||
|
||||
this.emitErrorEvent(context, "process/stderr", classified.message);
|
||||
}
|
||||
});
|
||||
this.emitErrorEvent(context, "process/stderr", classified.message);
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
context.child.on("error", (error) => {
|
||||
const message = error.message || "codex app-server process errored.";
|
||||
this.updateSession(context, {
|
||||
status: "error",
|
||||
lastError: message,
|
||||
});
|
||||
this.emitErrorEvent(context, "process/error", message);
|
||||
});
|
||||
yield* Effect.forkScoped(
|
||||
Effect.matchCauseEffect(context.child.exitCode, {
|
||||
onFailure: (cause) =>
|
||||
Effect.sync(() => {
|
||||
if (context.stopping) {
|
||||
return;
|
||||
}
|
||||
|
||||
context.child.on("exit", (code, signal) => {
|
||||
if (context.stopping) {
|
||||
return;
|
||||
}
|
||||
const message = messageFromCodexProcessCause(cause);
|
||||
this.updateSession(context, {
|
||||
status: "error",
|
||||
activeTurnId: undefined,
|
||||
lastError: message,
|
||||
});
|
||||
this.emitErrorEvent(context, "process/error", message);
|
||||
this.sessions.delete(context.session.sessionId);
|
||||
}),
|
||||
onSuccess: (code) =>
|
||||
Effect.sync(() => {
|
||||
if (context.stopping) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = `codex app-server exited (code=${code ?? "null"}, signal=${signal ?? "null"}).`;
|
||||
this.updateSession(context, {
|
||||
status: "closed",
|
||||
activeTurnId: undefined,
|
||||
lastError: code === 0 ? context.session.lastError : message,
|
||||
});
|
||||
this.emitLifecycleEvent(context, "session/exited", message);
|
||||
this.sessions.delete(context.session.sessionId);
|
||||
});
|
||||
const message = `codex app-server exited (code=${code}).`;
|
||||
this.updateSession(context, {
|
||||
status: "closed",
|
||||
activeTurnId: undefined,
|
||||
lastError: code === 0 ? context.session.lastError : message,
|
||||
});
|
||||
this.emitLifecycleEvent(context, "session/exited", message);
|
||||
this.sessions.delete(context.session.sessionId);
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}.bind(this),
|
||||
).pipe(Scope.provide(context.scope)),
|
||||
);
|
||||
}
|
||||
|
||||
private handleStdoutLine(context: CodexSessionContext, line: string): void {
|
||||
@@ -711,19 +755,31 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
if (request.method === "item/tool/requestUserInput") {
|
||||
this.writeMessage(context, {
|
||||
void this.writeMessage(context, {
|
||||
id: request.id,
|
||||
result: { answers: {} },
|
||||
}).catch((error) => {
|
||||
this.emitErrorEvent(
|
||||
context,
|
||||
"protocol/writeError",
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
this.writeMessage(context, {
|
||||
void this.writeMessage(context, {
|
||||
id: request.id,
|
||||
error: {
|
||||
code: -32601,
|
||||
message: `Unsupported server request: ${request.method}`,
|
||||
},
|
||||
}).catch((error) => {
|
||||
this.emitErrorEvent(
|
||||
context,
|
||||
"protocol/writeError",
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -766,23 +822,30 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
resolve,
|
||||
reject,
|
||||
});
|
||||
this.writeMessage(context, {
|
||||
void this.writeMessage(context, {
|
||||
method,
|
||||
id,
|
||||
params,
|
||||
}).catch((error) => {
|
||||
clearTimeout(timeout);
|
||||
context.pending.delete(String(id));
|
||||
reject(error instanceof Error ? error : new Error(String(error)));
|
||||
});
|
||||
});
|
||||
|
||||
return result as TResponse;
|
||||
}
|
||||
|
||||
private writeMessage(context: CodexSessionContext, message: unknown): void {
|
||||
private async writeMessage(context: CodexSessionContext, message: unknown): Promise<void> {
|
||||
const encoded = JSON.stringify(message);
|
||||
if (!context.child.stdin.writable) {
|
||||
if (context.stopping) {
|
||||
throw new Error("Cannot write to codex app-server stdin.");
|
||||
}
|
||||
|
||||
context.child.stdin.write(`${encoded}\n`);
|
||||
await this.runPromise(
|
||||
Stream.run(context.child.stdin)(Stream.make(new TextEncoder().encode(`${encoded}\n`))).pipe(
|
||||
Scope.provide(context.scope),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
/**
|
||||
* ServerConfig and NetService - Runtime configuration services.
|
||||
* ServerConfig - Runtime configuration services.
|
||||
*
|
||||
* Defines process-level server configuration and networking helpers used by
|
||||
* startup and runtime layers.
|
||||
*
|
||||
* @module ServerConfig
|
||||
*/
|
||||
import * as Net from "node:net";
|
||||
import { Data, Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
|
||||
import { Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
|
||||
|
||||
export const DEFAULT_PORT = 3773;
|
||||
|
||||
@@ -60,68 +59,6 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS
|
||||
);
|
||||
}
|
||||
|
||||
// Helpers
|
||||
|
||||
export class NetError extends Data.TaggedError("NetError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
/**
|
||||
* NetServiceShape - Networking helper operations used during startup.
|
||||
*/
|
||||
export interface NetServiceShape {
|
||||
/**
|
||||
* Resolve an available listening port, preferring the provided port first.
|
||||
*
|
||||
* Falls back to an ephemeral OS-assigned port when the preferred port is in use.
|
||||
*/
|
||||
readonly findAvailablePort: (preferred: number) => Effect.Effect<number, NetError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* NetService - Service tag for startup networking helpers.
|
||||
*/
|
||||
export class NetService extends ServiceMap.Service<NetService, NetServiceShape>()(
|
||||
"t3/config/NetService",
|
||||
) {
|
||||
static readonly layer = Layer.succeed(NetService, {
|
||||
findAvailablePort: (preferred) =>
|
||||
Effect.callback<number, NetError>((resume) => {
|
||||
let fallbackServer: Net.Server | null = null;
|
||||
const server = Net.createServer();
|
||||
server.listen(preferred, () => {
|
||||
server.close(() => resume(Effect.succeed(preferred)));
|
||||
});
|
||||
server.on("error", () => {
|
||||
const fallback = Net.createServer();
|
||||
fallback.listen(0, () => {
|
||||
const addr = fallback.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
fallback.close(() => {
|
||||
resume(
|
||||
port > 0
|
||||
? Effect.succeed(port)
|
||||
: Effect.fail(new NetError({ message: "Could not find an available port." })),
|
||||
);
|
||||
});
|
||||
});
|
||||
fallback.on("error", (cause) => {
|
||||
resume(
|
||||
Effect.fail(new NetError({ message: "Failed to find an available port", cause })),
|
||||
);
|
||||
});
|
||||
fallbackServer = fallback;
|
||||
});
|
||||
|
||||
return Effect.sync(() => {
|
||||
server.close();
|
||||
fallbackServer?.close();
|
||||
});
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export const resolveStaticDir = Effect.fn(function* () {
|
||||
const { join, resolve } = yield* Path.Path;
|
||||
const { exists } = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -189,7 +189,7 @@ function withFakeCodexEnv<A, E, R>(
|
||||
const CodexTextGenerationTestLayer = makeCodexTextGenerationTestLayer(process.cwd());
|
||||
|
||||
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
it.effect("generates and sanitizes commit messages", () =>
|
||||
it.effect("generates and sanitizes commit messages without branch by default", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
@@ -197,6 +197,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
" Add important change to the system with too much detail and a trailing period.\nsecondary line",
|
||||
body: "\n- added migration\n- updated tests\n",
|
||||
}),
|
||||
stdinMustNotContain: "branch must be a short semantic git branch fragment",
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
@@ -211,6 +212,34 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
expect(generated.subject.length).toBeLessThanOrEqual(72);
|
||||
expect(generated.subject.endsWith(".")).toBe(false);
|
||||
expect(generated.body).toBe("- added migration\n- updated tests");
|
||||
expect(generated.branch).toBeUndefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("generates commit message with branch when includeBranch is true", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
subject: "Add important change",
|
||||
body: "",
|
||||
branch: "fix/important-system-change",
|
||||
}),
|
||||
stdinMustContain: "branch must be a short semantic git branch fragment",
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/codex-effect",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
includeBranch: true,
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Add important change");
|
||||
expect(generated.branch).toBe("feature/fix/important-system-change");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { Effect, FileSystem, Layer, Path, Schema } from "effect";
|
||||
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import {
|
||||
type BranchNameGenerationInput,
|
||||
@@ -93,52 +95,15 @@ function sanitizePrTitle(raw: string): string {
|
||||
return "Update project changes";
|
||||
}
|
||||
|
||||
function sanitizeBranchName(raw: string): string {
|
||||
const normalized = raw
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/['"`]/g, "")
|
||||
.replace(/^[./\s_-]+|[./\s_-]+$/g, "");
|
||||
|
||||
const branchFragment = normalized
|
||||
.replace(/[^a-z0-9/_-]+/g, "-")
|
||||
.replace(/\/+/g, "/")
|
||||
.replace(/-+/g, "-")
|
||||
.replace(/^[./_-]+|[./_-]+$/g, "")
|
||||
.slice(0, 64)
|
||||
.replace(/[./_-]+$/g, "");
|
||||
|
||||
return branchFragment.length > 0 ? branchFragment : "update";
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
type MaterializedImageAttachments = {
|
||||
readonly imagePaths: ReadonlyArray<string>;
|
||||
};
|
||||
|
||||
const readStreamAsString = <E>(
|
||||
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";
|
||||
|
||||
const writeTempFile = (
|
||||
@@ -219,67 +184,59 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
);
|
||||
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
||||
|
||||
const runCodexCommand = Effect.gen(function* () {
|
||||
const command = ChildProcess.make(
|
||||
"codex",
|
||||
[
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
CODEX_MODEL,
|
||||
"--config",
|
||||
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
outputPath,
|
||||
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
||||
"-",
|
||||
],
|
||||
{
|
||||
cwd,
|
||||
stdin: {
|
||||
stream: Stream.make(new TextEncoder().encode(prompt)),
|
||||
const runCodexCommand = Effect.tryPromise({
|
||||
try: async () => {
|
||||
const result = await runProcess(
|
||||
"codex",
|
||||
[
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
CODEX_MODEL,
|
||||
"--config",
|
||||
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
outputPath,
|
||||
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
||||
"-",
|
||||
],
|
||||
{
|
||||
cwd,
|
||||
stdin: prompt,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: CODEX_TIMEOUT_MS,
|
||||
maxBufferBytes: 1_000_000,
|
||||
outputMode: "truncate",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const child = yield* commandSpawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCodexError(operation, cause, "Failed to spawn Codex CLI process"),
|
||||
),
|
||||
);
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
readStreamAsString(operation, child.stdout),
|
||||
readStreamAsString(operation, child.stderr),
|
||||
child.exitCode.pipe(
|
||||
Effect.map((value) => Number(value)),
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCodexError(operation, cause, "Failed to read Codex CLI exit code"),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
if (result.timedOut) {
|
||||
throw new TextGenerationError({ operation, detail: "Codex CLI request timed out." });
|
||||
}
|
||||
|
||||
if (exitCode !== 0) {
|
||||
const stderrDetail = stderr.trim();
|
||||
const stdoutDetail = stdout.trim();
|
||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||
return yield* new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
detail.length > 0
|
||||
? `Codex CLI command failed: ${detail}`
|
||||
: `Codex CLI command failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
const stdout = result.stdout;
|
||||
const stderr = result.stderr;
|
||||
const exitCode = result.code ?? 0;
|
||||
|
||||
if (exitCode !== 0) {
|
||||
const stderrDetail = stderr.trim();
|
||||
const stdoutDetail = stdout.trim();
|
||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||
throw new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
detail.length > 0
|
||||
? `Codex CLI command failed: ${detail}`
|
||||
: `Codex CLI command failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
},
|
||||
catch: (error) =>
|
||||
normalizeCodexError(operation, error, "Failed to execute Codex CLI process"),
|
||||
});
|
||||
|
||||
const cleanup = Effect.all(
|
||||
@@ -290,19 +247,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
yield* runCodexCommand.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(CODEX_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
|
||||
),
|
||||
onSome: () => Effect.void,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* runCodexCommand;
|
||||
|
||||
return yield* fileSystem.readFileString(outputPath).pipe(
|
||||
Effect.mapError(
|
||||
@@ -328,12 +273,19 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = (input) => {
|
||||
const wantsBranch = input.includeBranch === true;
|
||||
|
||||
const prompt = [
|
||||
"You write concise git commit messages.",
|
||||
"Return a JSON object with keys: subject, body.",
|
||||
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)"}`,
|
||||
@@ -345,20 +297,31 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
limitSection(input.stagedPatch, 40_000),
|
||||
].join("\n");
|
||||
|
||||
const outputSchemaJson = wantsBranch
|
||||
? Schema.Struct({
|
||||
subject: Schema.String,
|
||||
body: Schema.String,
|
||||
branch: Schema.String,
|
||||
})
|
||||
: Schema.Struct({
|
||||
subject: Schema.String,
|
||||
body: Schema.String,
|
||||
});
|
||||
|
||||
return runCodexJson({
|
||||
operation: "generateCommitMessage",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: Schema.Struct({
|
||||
subject: Schema.String,
|
||||
body: Schema.String,
|
||||
}),
|
||||
outputSchemaJson,
|
||||
}).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,
|
||||
),
|
||||
);
|
||||
@@ -408,7 +371,10 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
|
||||
const generateBranchName: TextGenerationShape["generateBranchName"] = (input) => {
|
||||
return Effect.gen(function* () {
|
||||
const { imagePaths } = yield* materializeImageAttachments("generateBranchName", input.attachments);
|
||||
const { imagePaths } = yield* materializeImageAttachments(
|
||||
"generateBranchName",
|
||||
input.attachments,
|
||||
);
|
||||
const attachmentLines = (input.attachments ?? []).map(
|
||||
(attachment) =>
|
||||
`- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
|
||||
@@ -446,7 +412,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
return {
|
||||
branch: sanitizeBranchName(generated.branch),
|
||||
branch: sanitizeBranchFragment(generated.branch),
|
||||
} satisfies BranchNameGenerationResult;
|
||||
});
|
||||
};
|
||||
|
||||
@@ -110,6 +110,7 @@ const makeIsolatedGitCore = (gitService: GitServiceShape) =>
|
||||
createBranch: (input) => core.createBranch(input),
|
||||
checkoutBranch: (input) => core.checkoutBranch(input),
|
||||
initRepo: (input) => core.initRepo(input),
|
||||
listLocalBranchNames: (cwd) => core.listLocalBranchNames(cwd),
|
||||
} satisfies GitCoreShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -1172,6 +1172,20 @@ const makeGitCore = Effect.gen(function* () {
|
||||
fallbackErrorMessage: "git init failed",
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const listLocalBranchNames: GitCoreShape["listLocalBranchNames"] = (cwd) =>
|
||||
runGitStdout("GitCore.listLocalBranchNames", cwd, [
|
||||
"branch",
|
||||
"--list",
|
||||
"--format=%(refname:short)",
|
||||
]).pipe(
|
||||
Effect.map((stdout) =>
|
||||
stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
status,
|
||||
statusDetails,
|
||||
@@ -1188,6 +1202,7 @@ const makeGitCore = Effect.gen(function* () {
|
||||
createBranch,
|
||||
checkoutBranch,
|
||||
initRepo,
|
||||
listLocalBranchNames,
|
||||
} satisfies GitCoreShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -32,7 +32,11 @@ interface FakeGitTextGeneration {
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
}) => Effect.Effect<{ subject: string; body: string }, TextGenerationError>;
|
||||
includeBranch?: boolean;
|
||||
}) => Effect.Effect<
|
||||
{ subject: string; body: string; branch?: string | undefined },
|
||||
TextGenerationError
|
||||
>;
|
||||
generatePrContent: (input: {
|
||||
cwd: string;
|
||||
baseBranch: string;
|
||||
@@ -104,10 +108,13 @@ function createBareRemote(): Effect.Effect<
|
||||
|
||||
function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): TextGenerationShape {
|
||||
const implementation: FakeGitTextGeneration = {
|
||||
generateCommitMessage: () =>
|
||||
generateCommitMessage: (input) =>
|
||||
Effect.succeed({
|
||||
subject: "Implement stacked git actions",
|
||||
body: "",
|
||||
...(input.includeBranch
|
||||
? { branch: "feature/implement-stacked-git-actions" }
|
||||
: {}),
|
||||
}),
|
||||
generatePrContent: () =>
|
||||
Effect.succeed({
|
||||
@@ -283,6 +290,7 @@ function runStackedAction(
|
||||
cwd: string;
|
||||
action: "commit" | "commit_push" | "commit_push_pr";
|
||||
commitMessage?: string;
|
||||
featureBranch?: boolean;
|
||||
},
|
||||
) {
|
||||
return manager.runStackedAction(input);
|
||||
@@ -475,6 +483,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("skipped_not_requested");
|
||||
@@ -495,12 +504,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
textGeneration: {
|
||||
generateCommitMessage: () =>
|
||||
generateCommitMessage: (input) =>
|
||||
Effect.sync(() => {
|
||||
generatedCount += 1;
|
||||
return {
|
||||
subject: "this should not be used",
|
||||
body: "",
|
||||
...(input.includeBranch ? { branch: "feature/unused" } : {}),
|
||||
};
|
||||
}),
|
||||
},
|
||||
@@ -511,6 +521,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
commitMessage: "feat: custom summary line\n\n- details from user",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.commit.subject).toBe("feat: custom summary line");
|
||||
expect(generatedCount).toBe(0);
|
||||
@@ -527,6 +538,101 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates feature branch, commits, and pushes with featureBranch option", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nfeature-branch\n");
|
||||
let generatedCount = 0;
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) =>
|
||||
Effect.sync(() => {
|
||||
generatedCount += 1;
|
||||
return {
|
||||
subject: "Implement stacked git actions",
|
||||
body: "",
|
||||
...(input.includeBranch
|
||||
? { branch: "feature/implement-stacked-git-actions" }
|
||||
: {}),
|
||||
};
|
||||
}),
|
||||
},
|
||||
});
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit_push",
|
||||
featureBranch: true,
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("created");
|
||||
expect(result.branch.name).toBe("feature/implement-stacked-git-actions");
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("pushed");
|
||||
expect(
|
||||
yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "HEAD"]).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
),
|
||||
).toBe("feature/implement-stacked-git-actions");
|
||||
|
||||
const mainSha = yield* runGit(repoDir, ["rev-parse", "main"]).pipe(
|
||||
Effect.map((r) => r.stdout.trim()),
|
||||
);
|
||||
const mergeBase = yield* runGit(repoDir, ["merge-base", "main", "HEAD"]).pipe(
|
||||
Effect.map((r) => r.stdout.trim()),
|
||||
);
|
||||
expect(mergeBase).toBe(mainSha);
|
||||
expect(generatedCount).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("featureBranch uses custom commit message and derives branch name", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom-feature\n");
|
||||
let generatedCount = 0;
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) =>
|
||||
Effect.sync(() => {
|
||||
generatedCount += 1;
|
||||
return {
|
||||
subject: "unused",
|
||||
body: "",
|
||||
...(input.includeBranch ? { branch: "feature/unused" } : {}),
|
||||
};
|
||||
}),
|
||||
},
|
||||
});
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
featureBranch: true,
|
||||
commitMessage: "feat: custom summary line\n\n- details from user",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("created");
|
||||
expect(result.branch.name).toBe("feature/feat-custom-summary-line");
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.commit.subject).toBe("feat: custom summary line");
|
||||
expect(generatedCount).toBe(0);
|
||||
|
||||
const mainSha = yield* runGit(repoDir, ["rev-parse", "main"]).pipe(
|
||||
Effect.map((r) => r.stdout.trim()),
|
||||
);
|
||||
const mergeBase = yield* runGit(repoDir, ["merge-base", "main", result.branch.name!]).pipe(
|
||||
Effect.map((r) => r.stdout.trim()),
|
||||
);
|
||||
expect(mergeBase).toBe(mainSha);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips commit when there are no uncommitted changes", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
@@ -538,12 +644,32 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.commit.status).toBe("skipped_no_changes");
|
||||
expect(result.push.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("skipped_not_requested");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("featureBranch returns error when worktree is clean", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
|
||||
const { manager } = yield* makeManager();
|
||||
const errorMessage = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
featureBranch: true,
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.map((error) => error.message),
|
||||
);
|
||||
|
||||
expect(errorMessage).toContain("no changes to commit");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("commits and pushes with upstream auto-setup when needed", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
@@ -559,6 +685,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit_push",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("pushed");
|
||||
expect(result.push.setUpstream).toBe(true);
|
||||
@@ -603,6 +730,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("pushed");
|
||||
expect(result.push.setUpstream).toBe(true);
|
||||
@@ -635,6 +763,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit_push",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.commit.status).toBe("skipped_no_changes");
|
||||
expect(result.push.status).toBe("skipped_up_to_date");
|
||||
}),
|
||||
@@ -669,6 +798,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("opened_existing");
|
||||
expect(result.pr.number).toBe(42);
|
||||
expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
|
||||
@@ -709,6 +839,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("created");
|
||||
expect(result.pr.number).toBe(88);
|
||||
expect(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import { resolveAutoFeatureBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { GitManagerError } from "../Errors.ts";
|
||||
import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
|
||||
@@ -85,9 +86,14 @@ function limitContext(value: string, maxChars: number): string {
|
||||
return `${value.slice(0, maxChars)}\n\n[truncated]`;
|
||||
}
|
||||
|
||||
function sanitizeCommitMessage(generated: { subject: string; body: string }): {
|
||||
function sanitizeCommitMessage(generated: {
|
||||
subject: string;
|
||||
body: string;
|
||||
branch?: string | undefined;
|
||||
}): {
|
||||
subject: string;
|
||||
body: string;
|
||||
branch?: string | undefined;
|
||||
} {
|
||||
const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||
const subject = rawSubject.replace(/[.]+$/g, "").trim();
|
||||
@@ -95,9 +101,25 @@ function sanitizeCommitMessage(generated: { subject: string; body: string }): {
|
||||
return {
|
||||
subject: safeSubject,
|
||||
body: generated.body.trim(),
|
||||
...(generated.branch !== undefined ? { branch: generated.branch } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
interface CommitAndBranchSuggestion {
|
||||
subject: string;
|
||||
body: string;
|
||||
branch?: string | undefined;
|
||||
commitMessage: string;
|
||||
}
|
||||
|
||||
function formatCommitMessage(subject: string, body: string): string {
|
||||
const trimmedBody = body.trim();
|
||||
if (trimmedBody.length === 0) {
|
||||
return subject;
|
||||
}
|
||||
return `${subject}\n\n${trimmedBody}`;
|
||||
}
|
||||
|
||||
function parseCustomCommitMessage(raw: string): { subject: string; body: string } | null {
|
||||
const normalized = raw.replace(/\r\n/g, "\n").trim();
|
||||
if (normalized.length === 0) {
|
||||
@@ -253,30 +275,72 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
return "main";
|
||||
});
|
||||
|
||||
const runCommitStep = (cwd: string, branch: string | null, commitMessage?: string) =>
|
||||
const resolveCommitAndBranchSuggestion = (input: {
|
||||
cwd: string;
|
||||
branch: string | null;
|
||||
commitMessage?: string;
|
||||
/** When true, also produce a semantic feature branch name. */
|
||||
includeBranch?: boolean;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* gitCore.prepareCommitContext(cwd);
|
||||
const context = yield* gitCore.prepareCommitContext(input.cwd);
|
||||
if (!context) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const customCommit = parseCustomCommitMessage(input.commitMessage ?? "");
|
||||
if (customCommit) {
|
||||
return {
|
||||
subject: customCommit.subject,
|
||||
body: customCommit.body,
|
||||
...(input.includeBranch
|
||||
? { branch: sanitizeFeatureBranchName(customCommit.subject) }
|
||||
: {}),
|
||||
commitMessage: formatCommitMessage(customCommit.subject, customCommit.body),
|
||||
};
|
||||
}
|
||||
|
||||
const generated = yield* textGeneration
|
||||
.generateCommitMessage({
|
||||
cwd: input.cwd,
|
||||
branch: input.branch,
|
||||
stagedSummary: limitContext(context.stagedSummary, 8_000),
|
||||
stagedPatch: limitContext(context.stagedPatch, 50_000),
|
||||
...(input.includeBranch ? { includeBranch: true } : {}),
|
||||
})
|
||||
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
|
||||
|
||||
return {
|
||||
subject: generated.subject,
|
||||
body: generated.body,
|
||||
...(generated.branch !== undefined ? { branch: generated.branch } : {}),
|
||||
commitMessage: formatCommitMessage(generated.subject, generated.body),
|
||||
};
|
||||
});
|
||||
|
||||
const runCommitStep = (
|
||||
cwd: string,
|
||||
branch: string | null,
|
||||
commitMessage?: string,
|
||||
preResolvedSuggestion?: CommitAndBranchSuggestion,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const suggestion =
|
||||
preResolvedSuggestion ??
|
||||
(yield* resolveCommitAndBranchSuggestion({
|
||||
cwd,
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
}));
|
||||
if (!suggestion) {
|
||||
return { status: "skipped_no_changes" as const };
|
||||
}
|
||||
|
||||
let generated = parseCustomCommitMessage(commitMessage ?? "");
|
||||
if (!generated) {
|
||||
generated = yield* textGeneration
|
||||
.generateCommitMessage({
|
||||
cwd,
|
||||
branch,
|
||||
stagedSummary: limitContext(context.stagedSummary, 8_000),
|
||||
stagedPatch: limitContext(context.stagedPatch, 50_000),
|
||||
})
|
||||
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
|
||||
}
|
||||
|
||||
const { commitSha } = yield* gitCore.commit(cwd, generated.subject, generated.body);
|
||||
const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body);
|
||||
return {
|
||||
status: "created" as const,
|
||||
commitSha,
|
||||
subject: generated.subject,
|
||||
subject: suggestion.subject,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -381,34 +445,88 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
};
|
||||
});
|
||||
|
||||
const runFeatureBranchStep = (cwd: string, branch: string | null, commitMessage?: string) =>
|
||||
Effect.gen(function* () {
|
||||
const suggestion = yield* resolveCommitAndBranchSuggestion({
|
||||
cwd,
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
includeBranch: true,
|
||||
});
|
||||
if (!suggestion) {
|
||||
return yield* gitManagerError(
|
||||
"runFeatureBranchStep",
|
||||
"Cannot create a feature branch because there are no changes to commit.",
|
||||
);
|
||||
}
|
||||
|
||||
const preferredBranch = suggestion.branch ?? sanitizeFeatureBranchName(suggestion.subject);
|
||||
const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd);
|
||||
const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch);
|
||||
|
||||
yield* gitCore.createBranch({ cwd, branch: resolvedBranch });
|
||||
yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch }));
|
||||
|
||||
return {
|
||||
branchStep: { status: "created" as const, name: resolvedBranch },
|
||||
resolvedCommitMessage: suggestion.commitMessage,
|
||||
resolvedCommitSuggestion: suggestion,
|
||||
};
|
||||
});
|
||||
|
||||
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(
|
||||
function* (input) {
|
||||
const wantsPush = input.action !== "commit";
|
||||
const wantsPr = input.action === "commit_push_pr";
|
||||
|
||||
const initialStatus = yield* gitCore.statusDetails(input.cwd);
|
||||
if (wantsPush && !initialStatus.branch) {
|
||||
if (!input.featureBranch && wantsPush && !initialStatus.branch) {
|
||||
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
|
||||
}
|
||||
if (wantsPr && !initialStatus.branch) {
|
||||
if (!input.featureBranch && wantsPr && !initialStatus.branch) {
|
||||
return yield* gitManagerError(
|
||||
"runStackedAction",
|
||||
"Cannot create a pull request from detached HEAD.",
|
||||
);
|
||||
}
|
||||
|
||||
const commit = yield* runCommitStep(input.cwd, initialStatus.branch, input.commitMessage);
|
||||
let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
|
||||
let commitMessageForStep = input.commitMessage;
|
||||
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
|
||||
|
||||
if (input.featureBranch) {
|
||||
const result = yield* runFeatureBranchStep(
|
||||
input.cwd,
|
||||
initialStatus.branch,
|
||||
input.commitMessage,
|
||||
);
|
||||
branchStep = result.branchStep;
|
||||
commitMessageForStep = result.resolvedCommitMessage;
|
||||
preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
|
||||
} else {
|
||||
branchStep = { status: "skipped_not_requested" as const };
|
||||
}
|
||||
|
||||
const currentBranch = branchStep.name ?? initialStatus.branch;
|
||||
|
||||
const commit = yield* runCommitStep(
|
||||
input.cwd,
|
||||
currentBranch,
|
||||
commitMessageForStep,
|
||||
preResolvedCommitSuggestion,
|
||||
);
|
||||
|
||||
const push = wantsPush
|
||||
? yield* gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
|
||||
? yield* gitCore.pushCurrentBranch(input.cwd, currentBranch)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
const pr = wantsPr
|
||||
? yield* runPrStep(input.cwd, initialStatus.branch)
|
||||
? yield* runPrStep(input.cwd, currentBranch)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
return {
|
||||
action: input.action,
|
||||
branch: branchStep,
|
||||
commit,
|
||||
push,
|
||||
pr,
|
||||
|
||||
@@ -3,7 +3,7 @@ import { it, assert } from "@effect/vitest";
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
|
||||
import { GitCommandError } from "../Errors.ts";
|
||||
import { GitServiceLive } from "./GitService.ts";
|
||||
import { GitServiceLive, normalizeGitProcessResult } from "./GitService.ts";
|
||||
import { GitService } from "../Services/GitService.ts";
|
||||
|
||||
const layer = it.layer(Layer.provideMerge(GitServiceLive, NodeServices.layer));
|
||||
@@ -56,4 +56,31 @@ layer("GitServiceLive", (it) => {
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it("normalizeGitProcessResult fails when git exits without a code", () => {
|
||||
try {
|
||||
void normalizeGitProcessResult(
|
||||
{
|
||||
operation: "GitProcess.test.signal",
|
||||
cwd: process.cwd(),
|
||||
args: ["status"],
|
||||
},
|
||||
{},
|
||||
{
|
||||
code: null,
|
||||
signal: "SIGTERM",
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
timedOut: false,
|
||||
},
|
||||
);
|
||||
assert.fail("Expected normalizeGitProcessResult to throw.");
|
||||
} catch (error) {
|
||||
assert.equal(Schema.is(GitCommandError)(error), true);
|
||||
if (!Schema.is(GitCommandError)(error)) {
|
||||
return;
|
||||
}
|
||||
assert.equal(error.detail, "git status terminated by signal SIGTERM.");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,13 @@
|
||||
/**
|
||||
* Git process helpers - Effect-native git execution with typed errors.
|
||||
* Git process helpers - runtime-aware git execution with typed errors.
|
||||
*
|
||||
* Centralizes child-process git invocation for server modules. This module
|
||||
* only executes git commands and reports structured failures.
|
||||
*
|
||||
* @module GitServiceLive
|
||||
*/
|
||||
import { Effect, Layer, Option, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import { GitCommandError } from "../Errors.ts";
|
||||
import {
|
||||
ExecuteGitInput,
|
||||
@@ -39,37 +39,60 @@ function toGitCommandError(
|
||||
});
|
||||
}
|
||||
|
||||
const collectOutput = Effect.fn(function* <E>(
|
||||
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
maxOutputBytes: number,
|
||||
): Effect.fn.Return<string, GitCommandError> {
|
||||
const decoder = new TextDecoder();
|
||||
let bytes = 0;
|
||||
let text = "";
|
||||
export function normalizeGitProcessResult(
|
||||
commandInput: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
input: Pick<ExecuteGitInput, "allowNonZeroExit">,
|
||||
result: {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly code: number | null;
|
||||
readonly signal: NodeJS.Signals | null;
|
||||
readonly timedOut: boolean;
|
||||
},
|
||||
): ExecuteGitResult {
|
||||
if (result.timedOut) {
|
||||
throw new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* Stream.runForEach(stream, (chunk) =>
|
||||
Effect.gen(function* () {
|
||||
bytes += chunk.byteLength;
|
||||
if (bytes > maxOutputBytes) {
|
||||
return yield* new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: quoteGitCommand(input.args),
|
||||
cwd: input.cwd,
|
||||
detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`,
|
||||
});
|
||||
}
|
||||
text += decoder.decode(chunk, { stream: true });
|
||||
}),
|
||||
).pipe(Effect.mapError(toGitCommandError(input, "output stream failed.")));
|
||||
if (result.code === null) {
|
||||
throw new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail:
|
||||
result.signal !== null
|
||||
? `${quoteGitCommand(commandInput.args)} terminated by signal ${result.signal}.`
|
||||
: `${quoteGitCommand(commandInput.args)} terminated before reporting an exit code.`,
|
||||
});
|
||||
}
|
||||
|
||||
text += decoder.decode();
|
||||
return text;
|
||||
});
|
||||
const exitCode = result.code;
|
||||
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||
const trimmedStderr = result.stderr.trim();
|
||||
throw new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail:
|
||||
trimmedStderr.length > 0
|
||||
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
|
||||
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const makeGitService = Effect.gen(function* () {
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
return {
|
||||
code: exitCode,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
} satisfies ExecuteGitResult;
|
||||
}
|
||||
|
||||
const makeGitService = Effect.sync(() => {
|
||||
const execute: GitServiceShape["execute"] = Effect.fnUntraced(function* (input) {
|
||||
const commandInput = {
|
||||
...input,
|
||||
@@ -78,62 +101,21 @@ const makeGitService = Effect.gen(function* () {
|
||||
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
|
||||
const commandEffect = Effect.gen(function* () {
|
||||
const child = yield* commandSpawner
|
||||
.spawn(
|
||||
ChildProcess.make("git", commandInput.args, {
|
||||
cwd: commandInput.cwd,
|
||||
...(input.env ? { env: input.env } : {}),
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn.")));
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectOutput(commandInput, child.stdout, maxOutputBytes),
|
||||
collectOutput(commandInput, child.stderr, maxOutputBytes),
|
||||
child.exitCode.pipe(
|
||||
Effect.map((value) => Number(value)),
|
||||
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||
const trimmedStderr = stderr.trim();
|
||||
return yield* new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
return yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
const result = await runProcess("git", commandInput.args, {
|
||||
cwd: commandInput.cwd,
|
||||
detail:
|
||||
trimmedStderr.length > 0
|
||||
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
|
||||
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
|
||||
...(input.env ? { env: input.env } : {}),
|
||||
timeoutMs,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: maxOutputBytes,
|
||||
outputMode: "error",
|
||||
});
|
||||
}
|
||||
|
||||
return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
|
||||
return normalizeGitProcessResult(commandInput, input, result);
|
||||
},
|
||||
catch: toGitCommandError(commandInput, "failed to run."),
|
||||
});
|
||||
|
||||
return yield* commandEffect.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(timeoutMs),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -157,6 +157,11 @@ export interface GitCoreShape {
|
||||
* Initialize a repository in the provided directory.
|
||||
*/
|
||||
readonly initRepo: (input: GitInitInput) => Effect.Effect<void, GitCommandError>;
|
||||
|
||||
/**
|
||||
* List local branch names (short format).
|
||||
*/
|
||||
readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -29,6 +29,7 @@ export interface GitManagerShape {
|
||||
|
||||
/**
|
||||
* Run a stacked Git action (`commit`, `commit_push`, `commit_push_pr`).
|
||||
* When `featureBranch` is set, creates and checks out a feature branch first.
|
||||
*/
|
||||
readonly runStackedAction: (
|
||||
input: GitRunStackedActionInput,
|
||||
|
||||
@@ -17,11 +17,15 @@ export interface CommitMessageGenerationInput {
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
/** When true, the model also returns a semantic branch name for the change. */
|
||||
includeBranch?: boolean;
|
||||
}
|
||||
|
||||
export interface CommitMessageGenerationResult {
|
||||
subject: string;
|
||||
body: string;
|
||||
/** Only present when `includeBranch` was set on the input. */
|
||||
branch?: string | undefined;
|
||||
}
|
||||
|
||||
export interface PrContentGenerationInput {
|
||||
|
||||
@@ -8,7 +8,7 @@ import { OpenLive } from "./open";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
import { version } from "../package.json" with { type: "json" };
|
||||
import { ServerLive } from "./wsServer";
|
||||
import { NetService } from "./config";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
const RuntimeLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(CliConfig.layer),
|
||||
|
||||
@@ -6,9 +6,10 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Command from "effect/unstable/cli/Command";
|
||||
import { beforeEach } from "vitest";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
import { CliConfig, t3Cli, type CliConfigShape } from "./main";
|
||||
import { NetService, ServerConfig, type ServerConfigShape } from "./config";
|
||||
import { ServerConfig, type ServerConfigShape } from "./config";
|
||||
import { Open, type OpenShape } from "./open";
|
||||
import { Server, type ServerShape } from "./wsServer";
|
||||
|
||||
@@ -33,6 +34,9 @@ const testLayer = Layer.mergeAll(
|
||||
resolveStaticDir: Effect.undefined,
|
||||
} satisfies CliConfigShape),
|
||||
Layer.succeed(NetService, {
|
||||
canListenOnHost: () => Effect.succeed(true),
|
||||
isPortAvailableOnLoopback: () => Effect.succeed(true),
|
||||
reserveLoopbackPort: () => Effect.succeed(0),
|
||||
findAvailablePort,
|
||||
}),
|
||||
Layer.succeed(Server, {
|
||||
|
||||
@@ -8,10 +8,10 @@
|
||||
*/
|
||||
import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceMap } from "effect";
|
||||
import { Command, Flag } from "effect/unstable/cli";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
import {
|
||||
DEFAULT_PORT,
|
||||
NetService,
|
||||
resolveStaticDir,
|
||||
ServerConfig,
|
||||
type RuntimeMode,
|
||||
@@ -21,6 +21,7 @@ import { fixPath, resolveStateDir } from "./os-jank";
|
||||
import { Open } from "./open";
|
||||
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
|
||||
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
|
||||
import { ProviderHealthLive } from "./provider/Layers/ProviderHealth";
|
||||
import { Server } from "./wsServer";
|
||||
|
||||
export class StartupError extends Data.TaggedError("StartupError")<{
|
||||
@@ -197,6 +198,7 @@ const LayerLive = (input: CliInput) =>
|
||||
Layer.empty.pipe(
|
||||
Layer.provideMerge(makeServerRuntimeServicesLayer()),
|
||||
Layer.provideMerge(makeServerProviderLayer()),
|
||||
Layer.provideMerge(ProviderHealthLive),
|
||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||
Layer.provideMerge(ServerConfigLive(input)),
|
||||
);
|
||||
|
||||
+201
-13
@@ -7,6 +7,7 @@ import { assert, describe, it } from "@effect/vitest";
|
||||
import {
|
||||
isCommandAvailable,
|
||||
launchDetached,
|
||||
resolveBrowserLaunch,
|
||||
resolveAvailableEditors,
|
||||
resolveEditorLaunch,
|
||||
} from "./open";
|
||||
@@ -18,7 +19,7 @@ describe("resolveEditorLaunch", () => {
|
||||
Effect.gen(function* () {
|
||||
const cursorLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "cursor" },
|
||||
"darwin",
|
||||
{ platform: "darwin" },
|
||||
);
|
||||
assert.deepEqual(cursorLaunch, {
|
||||
command: "cursor",
|
||||
@@ -27,7 +28,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const vscodeLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode" },
|
||||
"darwin",
|
||||
{ platform: "darwin" },
|
||||
);
|
||||
assert.deepEqual(vscodeLaunch, {
|
||||
command: "code",
|
||||
@@ -36,7 +37,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const zedLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "zed" },
|
||||
"darwin",
|
||||
{ platform: "darwin" },
|
||||
);
|
||||
assert.deepEqual(zedLaunch, {
|
||||
command: "zed",
|
||||
@@ -49,7 +50,7 @@ describe("resolveEditorLaunch", () => {
|
||||
Effect.gen(function* () {
|
||||
const lineOnly = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
|
||||
"darwin",
|
||||
{ platform: "darwin" },
|
||||
);
|
||||
assert.deepEqual(lineOnly, {
|
||||
command: "cursor",
|
||||
@@ -58,7 +59,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const lineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
|
||||
"darwin",
|
||||
{ platform: "darwin" },
|
||||
);
|
||||
assert.deepEqual(lineAndColumn, {
|
||||
command: "cursor",
|
||||
@@ -67,7 +68,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
||||
"darwin",
|
||||
{ platform: "darwin" },
|
||||
);
|
||||
assert.deepEqual(vscodeLineAndColumn, {
|
||||
command: "code",
|
||||
@@ -76,7 +77,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const zedLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
|
||||
"darwin",
|
||||
{ platform: "darwin" },
|
||||
);
|
||||
assert.deepEqual(zedLineAndColumn, {
|
||||
command: "zed",
|
||||
@@ -89,7 +90,7 @@ describe("resolveEditorLaunch", () => {
|
||||
Effect.gen(function* () {
|
||||
const launch1 = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||
"darwin",
|
||||
{ platform: "darwin" },
|
||||
);
|
||||
assert.deepEqual(launch1, {
|
||||
command: "open",
|
||||
@@ -98,7 +99,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const launch2 = yield* resolveEditorLaunch(
|
||||
{ cwd: "C:\\workspace", editor: "file-manager" },
|
||||
"win32",
|
||||
{ platform: "win32" },
|
||||
);
|
||||
assert.deepEqual(launch2, {
|
||||
command: "explorer",
|
||||
@@ -107,7 +108,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const launch3 = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||
"linux",
|
||||
{ platform: "linux" },
|
||||
);
|
||||
assert.deepEqual(launch3, {
|
||||
command: "xdg-open",
|
||||
@@ -115,6 +116,112 @@ describe("resolveEditorLaunch", () => {
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers linux editor shims in wsl-hosted mode when available", () =>
|
||||
Effect.gen(function* () {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-linux-editor-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "code"), "#!/bin/sh\n", { mode: 0o755 });
|
||||
const launch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/home/julius/project/src/open.ts:71:5", editor: "vscode" },
|
||||
{
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
},
|
||||
);
|
||||
assert.deepEqual(launch, {
|
||||
command: "code",
|
||||
args: ["--goto", "/home/julius/project/src/open.ts:71:5"],
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to windows editor executables in wsl-hosted mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-win-editor-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "code.exe"), "MZ", { mode: 0o755 });
|
||||
const launch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/home/julius/project/src/open.ts:71:5", editor: "vscode" },
|
||||
{
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
translateWslPathToWindows: (target) =>
|
||||
target.replace(
|
||||
"/home/julius/project",
|
||||
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project",
|
||||
),
|
||||
},
|
||||
);
|
||||
assert.deepEqual(launch, {
|
||||
command: "code.exe",
|
||||
args: [
|
||||
"--goto",
|
||||
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project/src/open.ts:71:5",
|
||||
],
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("translates file-manager targets for wsl-hosted mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-file-manager-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "explorer.exe"), "MZ", { mode: 0o755 });
|
||||
const launch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/home/julius/project/src/open.ts:71:5", editor: "file-manager" },
|
||||
{
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
translateWslPathToWindows: (target) =>
|
||||
target.replace(
|
||||
"/home/julius/project",
|
||||
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project",
|
||||
),
|
||||
},
|
||||
);
|
||||
assert.deepEqual(launch, {
|
||||
command: "explorer.exe",
|
||||
args: ["\\\\wsl.localhost\\Ubuntu\\home\\julius\\project/src/open.ts"],
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("launchDetached", () => {
|
||||
@@ -210,13 +317,94 @@ describe("resolveAvailableEditors", () => {
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "cursor.CMD"), "@echo off\r\n", "utf8");
|
||||
fs.writeFileSync(path.join(dir, "explorer.EXE"), "MZ", "utf8");
|
||||
const editors = resolveAvailableEditors("win32", {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
const editors = resolveAvailableEditors({
|
||||
platform: "win32",
|
||||
env: {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
},
|
||||
});
|
||||
assert.deepEqual(editors, ["cursor", "file-manager"]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts windows editor executables in wsl-hosted mode", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-editors-wsl-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "code.exe"), "MZ", { mode: 0o755 });
|
||||
fs.writeFileSync(path.join(dir, "explorer.exe"), "MZ", { mode: 0o755 });
|
||||
const editors = resolveAvailableEditors({
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
});
|
||||
assert.deepEqual(editors, ["vscode", "file-manager"]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveBrowserLaunch", () => {
|
||||
it("prefers wslview in wsl-hosted mode", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-browser-wsl-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "wslview"), "#!/bin/sh\n", { mode: 0o755 });
|
||||
const launch = resolveBrowserLaunch("http://localhost:3773", {
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
});
|
||||
assert.deepEqual(launch, {
|
||||
command: "wslview",
|
||||
args: ["http://localhost:3773"],
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back to explorer.exe in wsl-hosted mode", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-browser-wsl-explorer-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "explorer.exe"), "MZ", { mode: 0o755 });
|
||||
const launch = resolveBrowserLaunch("http://localhost:3773", {
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
});
|
||||
assert.deepEqual(launch, {
|
||||
command: "explorer.exe",
|
||||
args: ["http://localhost:3773"],
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
+236
-35
@@ -6,12 +6,13 @@
|
||||
*
|
||||
* @module Open
|
||||
*/
|
||||
import { spawn } from "node:child_process";
|
||||
import { accessSync, constants, statSync } from "node:fs";
|
||||
import { extname, join } from "node:path";
|
||||
|
||||
import { EDITORS, type EditorId } from "@t3tools/contracts";
|
||||
import { EDITORS, type EditorId, type ServerRuntimeEnvironment } from "@t3tools/contracts";
|
||||
import { ServiceMap, Schema, Effect, Layer } from "effect";
|
||||
import { spawnDetachedProcess, spawnProcessSync } from "./processRunner";
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
|
||||
// ==============================
|
||||
// Definitions
|
||||
@@ -37,7 +38,24 @@ interface CommandAvailabilityOptions {
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
}
|
||||
|
||||
interface ResolveOpenOptions extends CommandAvailabilityOptions {
|
||||
readonly runtimeEnvironment?: ServerRuntimeEnvironment;
|
||||
readonly translateWslPathToWindows?: (target: string) => string;
|
||||
}
|
||||
|
||||
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
|
||||
const WINDOWS_ABSOLUTE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
|
||||
const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
|
||||
|
||||
function detectRuntimeEnvironment(options: ResolveOpenOptions): ServerRuntimeEnvironment {
|
||||
return (
|
||||
options.runtimeEnvironment ??
|
||||
detectServerRuntimeEnvironment({
|
||||
...(options.platform !== undefined ? { platform: options.platform } : {}),
|
||||
...(options.env !== undefined ? { env: options.env } : {}),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {
|
||||
return (editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target);
|
||||
@@ -160,14 +178,20 @@ export function isCommandAvailable(
|
||||
}
|
||||
|
||||
export function resolveAvailableEditors(
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
options: ResolveOpenOptions = {},
|
||||
): ReadonlyArray<EditorId> {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
|
||||
const available: EditorId[] = [];
|
||||
|
||||
for (const editor of EDITORS) {
|
||||
const command = editor.command ?? fileManagerCommandForPlatform(platform);
|
||||
if (isCommandAvailable(command, { platform, env })) {
|
||||
const launch = resolveOpenCommand(editor.id, {
|
||||
platform,
|
||||
env,
|
||||
runtimeEnvironment,
|
||||
});
|
||||
if (launch.some((entry) => isCommandAvailable(entry, { platform, env }))) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
}
|
||||
@@ -201,51 +225,223 @@ export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
|
||||
// Implementations
|
||||
// ==============================
|
||||
|
||||
function splitPathAndPosition(value: string): {
|
||||
path: string;
|
||||
line: string | undefined;
|
||||
column: string | undefined;
|
||||
} {
|
||||
let path = value;
|
||||
let column: string | undefined;
|
||||
let line: string | undefined;
|
||||
|
||||
const columnMatch = path.match(/:(\d+)$/);
|
||||
if (!columnMatch?.[1]) {
|
||||
return { path, line: undefined, column: undefined };
|
||||
}
|
||||
|
||||
column = columnMatch[1];
|
||||
path = path.slice(0, -columnMatch[0].length);
|
||||
|
||||
const lineMatch = path.match(/:(\d+)$/);
|
||||
if (lineMatch?.[1]) {
|
||||
line = lineMatch[1];
|
||||
path = path.slice(0, -lineMatch[0].length);
|
||||
} else {
|
||||
line = column;
|
||||
column = undefined;
|
||||
}
|
||||
|
||||
return { path, line, column };
|
||||
}
|
||||
|
||||
function stripLineColumnSuffix(value: string): string {
|
||||
const { path } = splitPathAndPosition(value);
|
||||
return path;
|
||||
}
|
||||
|
||||
function formatPathWithPosition(input: {
|
||||
readonly path: string;
|
||||
readonly line?: string;
|
||||
readonly column?: string;
|
||||
}): string {
|
||||
if (!input.line) {
|
||||
return input.path;
|
||||
}
|
||||
return `${input.path}:${input.line}${input.column ? `:${input.column}` : ""}`;
|
||||
}
|
||||
|
||||
function isWindowsPath(value: string): boolean {
|
||||
return WINDOWS_ABSOLUTE_PATH_PATTERN.test(value) || WINDOWS_UNC_PATH_PATTERN.test(value);
|
||||
}
|
||||
|
||||
function defaultTranslateWslPathToWindows(target: string): string {
|
||||
const parsed = splitPathAndPosition(target);
|
||||
if (parsed.path.length === 0 || !parsed.path.startsWith("/") || isWindowsPath(parsed.path)) {
|
||||
return target;
|
||||
}
|
||||
|
||||
const result = spawnProcessSync("wslpath", ["-w", parsed.path], {
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
if (result.error) {
|
||||
throw result.error;
|
||||
}
|
||||
if (result.status !== 0) {
|
||||
const detail = result.stderr.trim() || result.stdout.trim() || "wslpath failed";
|
||||
throw new Error(detail);
|
||||
}
|
||||
|
||||
const translatedPath = result.stdout.trim();
|
||||
if (translatedPath.length === 0) {
|
||||
throw new Error("wslpath returned an empty path");
|
||||
}
|
||||
|
||||
return formatPathWithPosition({
|
||||
path: translatedPath,
|
||||
...(parsed.line ? { line: parsed.line } : {}),
|
||||
...(parsed.column ? { column: parsed.column } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function resolveOpenCommand(
|
||||
editorId: EditorId,
|
||||
options: ResolveOpenOptions,
|
||||
): ReadonlyArray<string> {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
|
||||
const editorDef = EDITORS.find((editor) => editor.id === editorId);
|
||||
if (!editorDef) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (editorId === "file-manager") {
|
||||
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted") {
|
||||
return ["explorer.exe", "xdg-open"];
|
||||
}
|
||||
return [fileManagerCommandForPlatform(platform)];
|
||||
}
|
||||
|
||||
if (!editorDef.command) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted") {
|
||||
return [editorDef.command, `${editorDef.command}.exe`];
|
||||
}
|
||||
|
||||
return [editorDef.command];
|
||||
}
|
||||
|
||||
export function resolveBrowserLaunch(
|
||||
target: string,
|
||||
options: ResolveOpenOptions = {},
|
||||
): EditorLaunch | null {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
|
||||
|
||||
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted") {
|
||||
if (isCommandAvailable("wslview", { platform, env })) {
|
||||
return { command: "wslview", args: [target] };
|
||||
}
|
||||
if (isCommandAvailable("explorer.exe", { platform, env })) {
|
||||
return { command: "explorer.exe", args: [target] };
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export const resolveEditorLaunch = Effect.fnUntraced(function* (
|
||||
input: OpenInEditorInput,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
options: ResolveOpenOptions = {},
|
||||
): Effect.fn.Return<EditorLaunch, OpenError> {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
|
||||
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
|
||||
if (!editorDef) {
|
||||
return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
const translateWslPathToWindows = options.translateWslPathToWindows ?? defaultTranslateWslPathToWindows;
|
||||
|
||||
if (editorDef.command) {
|
||||
return shouldUseGotoFlag(editorDef.id, input.cwd)
|
||||
? { command: editorDef.command, args: ["--goto", input.cwd] }
|
||||
: { command: editorDef.command, args: [input.cwd] };
|
||||
const candidateCommands = resolveOpenCommand(editorDef.id, {
|
||||
platform,
|
||||
env,
|
||||
runtimeEnvironment,
|
||||
});
|
||||
const command =
|
||||
candidateCommands.find((entry) => isCommandAvailable(entry, { platform, env })) ??
|
||||
candidateCommands[0];
|
||||
if (!command) {
|
||||
return yield* new OpenError({ message: `Editor command not found: ${editorDef.command}` });
|
||||
}
|
||||
|
||||
const usesWindowsPath = runtimeEnvironment.windowsInteropMode === "wsl-hosted" && command.endsWith(".exe");
|
||||
const target = usesWindowsPath
|
||||
? yield* Effect.try({
|
||||
try: () => translateWslPathToWindows(input.cwd),
|
||||
catch: (cause) =>
|
||||
new OpenError({
|
||||
message: "Failed to translate WSL path for Windows editor launch",
|
||||
cause,
|
||||
}),
|
||||
})
|
||||
: input.cwd;
|
||||
|
||||
return shouldUseGotoFlag(editorDef.id, target)
|
||||
? { command, args: ["--goto", target] }
|
||||
: { command, args: [target] };
|
||||
}
|
||||
|
||||
if (editorDef.id !== "file-manager") {
|
||||
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
|
||||
const candidateCommands = resolveOpenCommand(editorDef.id, {
|
||||
platform,
|
||||
env,
|
||||
runtimeEnvironment,
|
||||
});
|
||||
const command =
|
||||
candidateCommands.find((entry) => isCommandAvailable(entry, { platform, env })) ??
|
||||
candidateCommands[0];
|
||||
if (!command) {
|
||||
return yield* new OpenError({ message: "Editor command not found: file-manager" });
|
||||
}
|
||||
|
||||
let target = stripLineColumnSuffix(input.cwd);
|
||||
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted" && command === "explorer.exe") {
|
||||
target = yield* Effect.try({
|
||||
try: () => stripLineColumnSuffix(translateWslPathToWindows(target)),
|
||||
catch: (cause) =>
|
||||
new OpenError({
|
||||
message: "Failed to translate WSL path for Windows file manager launch",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
return { command, args: [target] };
|
||||
});
|
||||
|
||||
export const launchDetached = (launch: EditorLaunch) =>
|
||||
Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn(launch.command, [...launch.args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
});
|
||||
} catch (error) {
|
||||
return resume(
|
||||
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
|
||||
);
|
||||
}
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
throw new OpenError({ message: `Editor command not found: ${launch.command}` });
|
||||
}
|
||||
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
};
|
||||
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (cause) =>
|
||||
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
|
||||
);
|
||||
await spawnDetachedProcess(launch.command, [...launch.args]);
|
||||
},
|
||||
catch: (cause) =>
|
||||
Schema.is(OpenError)(cause)
|
||||
? cause
|
||||
: new OpenError({ message: "failed to spawn detached process", cause }),
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
@@ -255,11 +451,16 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
return {
|
||||
openBrowser: (target) =>
|
||||
Effect.tryPromise({
|
||||
openBrowser: (target) => {
|
||||
const launch = resolveBrowserLaunch(target);
|
||||
if (launch) {
|
||||
return launchDetached(launch);
|
||||
}
|
||||
return Effect.tryPromise({
|
||||
try: () => open.default(target),
|
||||
catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
|
||||
}),
|
||||
});
|
||||
},
|
||||
openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
|
||||
} satisfies OpenShape;
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { runProcess } from "./processRunner";
|
||||
import { runProcess, spawnDetachedProcess, spawnProcessSync } from "./processRunner";
|
||||
|
||||
describe("runProcess", () => {
|
||||
it("fails when output exceeds max buffer in default mode", async () => {
|
||||
@@ -20,4 +20,20 @@ describe("runProcess", () => {
|
||||
expect(result.stdoutTruncated).toBe(true);
|
||||
expect(result.stderrTruncated).toBe(false);
|
||||
});
|
||||
|
||||
it("runs sync commands through the shared spawn strategy", () => {
|
||||
const result = spawnProcessSync("node", ["-e", "process.stdout.write('ok')"], {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.status).toBe(0);
|
||||
expect(result.stdout).toBe("ok");
|
||||
});
|
||||
|
||||
it("spawns detached commands through the shared spawn strategy", async () => {
|
||||
await expect(
|
||||
spawnDetachedProcess(process.execPath, ["-e", "process.exit(0)"]),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,44 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import {
|
||||
type ChildProcess as ChildProcessHandle,
|
||||
type ChildProcessWithoutNullStreams,
|
||||
spawn,
|
||||
spawnSync,
|
||||
type StdioOptions,
|
||||
} from "node:child_process";
|
||||
|
||||
import type { ServerRuntimeEnvironment } from "@t3tools/contracts";
|
||||
import { Effect, Exit, Scope } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
|
||||
interface ProcessSpawnBaseOptions {
|
||||
cwd?: string | undefined;
|
||||
env?: NodeJS.ProcessEnv | undefined;
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
shell?: boolean | undefined;
|
||||
}
|
||||
|
||||
interface RuntimeShellOptions {
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
shell?: boolean | string | undefined;
|
||||
}
|
||||
|
||||
interface ProcessSpawnOptions extends ProcessSpawnBaseOptions {
|
||||
stdio?: StdioOptions | undefined;
|
||||
detached?: boolean | undefined;
|
||||
}
|
||||
|
||||
interface RuntimeCommandOptions extends ChildProcess.CommandOptions {
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
}
|
||||
|
||||
interface ProcessSpawnSyncOptions extends ProcessSpawnBaseOptions {
|
||||
stdio?: StdioOptions | undefined;
|
||||
detached?: boolean | undefined;
|
||||
encoding?: BufferEncoding | undefined;
|
||||
input?: string | undefined;
|
||||
}
|
||||
|
||||
export interface ProcessRunOptions {
|
||||
cwd?: string | undefined;
|
||||
@@ -8,6 +48,8 @@ export interface ProcessRunOptions {
|
||||
allowNonZeroExit?: boolean | undefined;
|
||||
maxBufferBytes?: number | undefined;
|
||||
outputMode?: "error" | "truncate" | undefined;
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
shell?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface ProcessRunResult {
|
||||
@@ -24,6 +66,127 @@ function commandLabel(command: string, args: readonly string[]): string {
|
||||
return [command, ...args].join(" ");
|
||||
}
|
||||
|
||||
function resolveRuntimeEnvironment(
|
||||
runtimeEnvironment: ServerRuntimeEnvironment | undefined,
|
||||
): ServerRuntimeEnvironment {
|
||||
return runtimeEnvironment ?? detectServerRuntimeEnvironment();
|
||||
}
|
||||
|
||||
function shouldUseShell(options: RuntimeShellOptions): boolean | string {
|
||||
if (options.shell !== undefined) {
|
||||
return options.shell;
|
||||
}
|
||||
|
||||
return resolveRuntimeEnvironment(options.runtimeEnvironment).platform === "windows";
|
||||
}
|
||||
|
||||
function toSpawnOptions(options: ProcessSpawnOptions) {
|
||||
return {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
shell: shouldUseShell(options),
|
||||
...(options.stdio !== undefined ? { stdio: options.stdio } : {}),
|
||||
...(options.detached !== undefined ? { detached: options.detached } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function toRuntimeCommandOptions(
|
||||
options: RuntimeCommandOptions = {},
|
||||
): ChildProcess.CommandOptions {
|
||||
const { runtimeEnvironment: _, ...rest } = options;
|
||||
return {
|
||||
...rest,
|
||||
shell: options.shell ?? shouldUseShell(options),
|
||||
};
|
||||
}
|
||||
|
||||
export function makeRuntimeCommand(
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options: RuntimeCommandOptions = {},
|
||||
): ChildProcess.StandardCommand {
|
||||
return ChildProcess.make(command, [...args], toRuntimeCommandOptions(options));
|
||||
}
|
||||
|
||||
interface ManagedChildProcess {
|
||||
readonly scope: Scope.Closeable;
|
||||
readonly handle: ChildProcessSpawner.ChildProcessHandle;
|
||||
}
|
||||
|
||||
export const spawnManagedCommand = (command: ChildProcess.Command) =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* Scope.make("sequential");
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const handle = yield* spawner.spawn(command).pipe(
|
||||
Scope.provide(scope),
|
||||
Effect.tapError(() => Scope.close(scope, Exit.void)),
|
||||
);
|
||||
|
||||
return {
|
||||
scope,
|
||||
handle,
|
||||
} satisfies ManagedChildProcess;
|
||||
});
|
||||
|
||||
function spawnProcess(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: ProcessSpawnOptions = {},
|
||||
): ChildProcessHandle {
|
||||
return spawn(command, args, toSpawnOptions(options));
|
||||
}
|
||||
|
||||
function spawnPipedProcess(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: Omit<ProcessSpawnOptions, "stdio" | "detached"> = {},
|
||||
): ChildProcessWithoutNullStreams {
|
||||
return spawnProcess(command, args, {
|
||||
...options,
|
||||
stdio: "pipe",
|
||||
}) as ChildProcessWithoutNullStreams;
|
||||
}
|
||||
|
||||
export function spawnProcessSync(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: ProcessSpawnSyncOptions = {},
|
||||
) {
|
||||
return spawnSync(command, args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
shell: shouldUseShell(options),
|
||||
encoding: options.encoding ?? "utf8",
|
||||
...(options.stdio !== undefined ? { stdio: options.stdio } : {}),
|
||||
...(options.detached !== undefined ? { detached: options.detached } : {}),
|
||||
...(options.input !== undefined ? { input: options.input } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
export function spawnDetachedProcess(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: Omit<ProcessSpawnOptions, "stdio" | "detached"> = {},
|
||||
): Promise<void> {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const child = spawnProcess(command, args, {
|
||||
...options,
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
});
|
||||
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resolve();
|
||||
};
|
||||
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (error) => {
|
||||
reject(normalizeSpawnError(command, args, error));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeSpawnError(command: string, args: readonly string[], error: unknown): Error {
|
||||
if (!(error instanceof Error)) {
|
||||
return new Error(`Failed to run ${commandLabel(command, args)}.`);
|
||||
@@ -37,11 +200,26 @@ 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,
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment,
|
||||
): boolean {
|
||||
if (resolveRuntimeEnvironment(runtimeEnvironment).platform !== "windows") return false;
|
||||
if (code === 9009) return true;
|
||||
return /is not recognized as an internal or external command/i.test(stderr);
|
||||
}
|
||||
|
||||
function normalizeExitError(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
result: ProcessRunResult,
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment,
|
||||
): Error {
|
||||
if (isWindowsCommandNotFound(result.code, result.stderr, runtimeEnvironment)) {
|
||||
return new Error(`Command not found: ${command}`);
|
||||
}
|
||||
|
||||
const reason = result.timedOut
|
||||
? "timed out"
|
||||
: `failed (code=${result.code ?? "null"}, signal=${result.signal ?? "null"})`;
|
||||
@@ -70,6 +248,42 @@ function normalizeBufferError(
|
||||
|
||||
const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
|
||||
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
|
||||
* entire process tree instead.
|
||||
*/
|
||||
function killProcessTree(
|
||||
child: ChildProcessHandle,
|
||||
options: {
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
signal?: NodeJS.Signals | undefined;
|
||||
} = {},
|
||||
): void {
|
||||
const signal = options.signal ?? "SIGTERM";
|
||||
if (
|
||||
resolveRuntimeEnvironment(options.runtimeEnvironment).platform === "windows" &&
|
||||
child.pid !== undefined
|
||||
) {
|
||||
try {
|
||||
const result = spawnProcessSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
|
||||
stdio: "ignore",
|
||||
shell: false,
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
});
|
||||
if (!result.error && result.status === 0) {
|
||||
return;
|
||||
}
|
||||
if (result.error) {
|
||||
throw result.error;
|
||||
}
|
||||
} catch {
|
||||
// fallback to direct kill
|
||||
}
|
||||
}
|
||||
child.kill(signal);
|
||||
}
|
||||
|
||||
function appendChunkWithinLimit(
|
||||
target: string,
|
||||
currentBytes: number,
|
||||
@@ -108,11 +322,7 @@ export async function runProcess(
|
||||
const outputMode = options.outputMode ?? "error";
|
||||
|
||||
return new Promise<ProcessRunResult>((resolve, reject) => {
|
||||
const child = spawn(command, args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const child = spawnPipedProcess(command, args, options);
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
@@ -126,9 +336,15 @@ export async function runProcess(
|
||||
|
||||
const timeoutTimer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
child.kill("SIGTERM");
|
||||
killProcessTree(child, {
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
signal: "SIGTERM",
|
||||
});
|
||||
forceKillTimer = setTimeout(() => {
|
||||
child.kill("SIGKILL");
|
||||
killProcessTree(child, {
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
signal: "SIGKILL",
|
||||
});
|
||||
}, 1_000);
|
||||
}, timeoutMs);
|
||||
|
||||
@@ -143,7 +359,10 @@ export async function runProcess(
|
||||
};
|
||||
|
||||
const fail = (error: Error): void => {
|
||||
child.kill("SIGTERM");
|
||||
killProcessTree(child, {
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
signal: "SIGTERM",
|
||||
});
|
||||
finalize(() => {
|
||||
reject(error);
|
||||
});
|
||||
@@ -216,7 +435,7 @@ export async function runProcess(
|
||||
|
||||
finalize(() => {
|
||||
if (!options.allowNonZeroExit && (timedOut || (code !== null && code !== 0))) {
|
||||
reject(normalizeExitError(command, args, result));
|
||||
reject(normalizeExitError(command, args, result, options.runtimeEnvironment));
|
||||
return;
|
||||
}
|
||||
resolve(result);
|
||||
|
||||
@@ -15,7 +15,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { afterAll, assert, it, vi } from "@effect/vitest";
|
||||
import { assertFailure } from "@effect/vitest/utils";
|
||||
|
||||
import { Effect, Fiber, Layer, Stream } from "effect";
|
||||
import { Effect, Fiber, Layer, Option, Stream } from "effect";
|
||||
|
||||
import {
|
||||
CodexAppServerManager,
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ProviderAdapterValidationError } from "../Errors.ts";
|
||||
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
|
||||
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
@@ -121,10 +122,21 @@ class FakeCodexManager extends CodexAppServerManager {
|
||||
}
|
||||
}
|
||||
|
||||
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
|
||||
upsert: () => Effect.void,
|
||||
getProvider: () =>
|
||||
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
getThreadId: () => Effect.succeed(Option.none()),
|
||||
remove: () => Effect.void,
|
||||
listSessionIds: () => Effect.succeed([]),
|
||||
});
|
||||
|
||||
const validationManager = new FakeCodexManager();
|
||||
const validationLayer = it.layer(
|
||||
makeCodexAdapterLive({ manager: validationManager }).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
@@ -159,6 +171,7 @@ sessionErrorManager.sendTurnImpl.mockImplementation(async () => {
|
||||
const sessionErrorLayer = it.layer(
|
||||
makeCodexAdapterLive({ manager: sessionErrorManager }).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
@@ -195,6 +208,7 @@ const lifecycleManager = new FakeCodexManager();
|
||||
const lifecycleLayer = it.layer(
|
||||
makeCodexAdapterLive({ manager: lifecycleManager }).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, FileSystem, Layer, Queue, Schema, Stream } from "effect";
|
||||
import { Effect, FileSystem, Layer, Option, Queue, Schema, Stream } from "effect";
|
||||
|
||||
import {
|
||||
ProviderAdapterProcessError,
|
||||
@@ -28,10 +28,12 @@ import {
|
||||
type ProviderAdapterError,
|
||||
} from "../Errors.ts";
|
||||
import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import { CodexAppServerManager } from "../../codexAppServerManager.ts";
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
const PROVIDER = "codex" as const;
|
||||
|
||||
@@ -39,6 +41,7 @@ export interface CodexAdapterLiveOptions {
|
||||
readonly manager?: CodexAppServerManager;
|
||||
readonly makeManager?: () => CodexAppServerManager;
|
||||
readonly nativeEventLogPath?: string;
|
||||
readonly nativeEventLogger?: EventNdjsonLogger;
|
||||
}
|
||||
|
||||
function toMessage(cause: unknown, fallback: string): string {
|
||||
@@ -430,10 +433,15 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const services = yield* Effect.services<NodeServices.NodeServices>();
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogPath !== undefined
|
||||
? makeEventNdjsonLogger(options.nativeEventLogPath)
|
||||
: undefined;
|
||||
options?.nativeEventLogger ??
|
||||
(options?.nativeEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
|
||||
stream: "native",
|
||||
})
|
||||
: undefined);
|
||||
|
||||
const manager = yield* Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
@@ -443,7 +451,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
if (options?.makeManager) {
|
||||
return options.makeManager();
|
||||
}
|
||||
return new CodexAppServerManager();
|
||||
return new CodexAppServerManager(services);
|
||||
}),
|
||||
(manager) =>
|
||||
Effect.sync(() => {
|
||||
@@ -495,9 +503,11 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
new Error(`Invalid attachment id '${attachment.id}'.`),
|
||||
);
|
||||
}
|
||||
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
|
||||
Effect.mapError((cause) => toRequestError(input.sessionId, "turn/start", cause)),
|
||||
);
|
||||
const bytes = yield* fileSystem
|
||||
.readFile(attachmentPath)
|
||||
.pipe(
|
||||
Effect.mapError((cause) => toRequestError(input.sessionId, "turn/start", cause)),
|
||||
);
|
||||
return {
|
||||
type: "image" as const,
|
||||
url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`,
|
||||
@@ -580,13 +590,29 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
const listener = (event: ProviderEvent) => {
|
||||
nativeEventLogger?.write({
|
||||
observedAt: new Date().toISOString(),
|
||||
event,
|
||||
const writeNativeEvent = (event: ProviderEvent) =>
|
||||
Effect.gen(function* () {
|
||||
if (!nativeEventLogger) {
|
||||
return;
|
||||
}
|
||||
const orchestrationThreadId = yield* Effect.catch(
|
||||
directory
|
||||
.getThreadId(event.sessionId)
|
||||
.pipe(
|
||||
Effect.map((threadIdOption) =>
|
||||
Option.isSome(threadIdOption) ? threadIdOption.value : null,
|
||||
),
|
||||
),
|
||||
() => Effect.succeed(null),
|
||||
);
|
||||
yield* nativeEventLogger.write(event, orchestrationThreadId);
|
||||
});
|
||||
Queue.offerAllUnsafe(runtimeEventQueue, mapToRuntimeEvents(event));
|
||||
};
|
||||
|
||||
const listener = (event: ProviderEvent) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeNativeEvent(event);
|
||||
yield* Queue.offerAll(runtimeEventQueue, mapToRuntimeEvents(event));
|
||||
}).pipe(Effect.runPromiseWith(services));
|
||||
manager.on("event", listener);
|
||||
return listener;
|
||||
}),
|
||||
|
||||
@@ -2,36 +2,165 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect } from "effect";
|
||||
|
||||
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
|
||||
function parseLogLine(line: string) {
|
||||
const match = /^\[([^\]]+)\] ([A-Z]+): (.+)$/.exec(line);
|
||||
assert.notEqual(match, null);
|
||||
if (!match) {
|
||||
throw new Error(`invalid log line: ${line}`);
|
||||
}
|
||||
const observedAt = match[1];
|
||||
const stream = match[2];
|
||||
const payload = match[3];
|
||||
if (!observedAt || !stream || payload === undefined) {
|
||||
throw new Error(`invalid log line: ${line}`);
|
||||
}
|
||||
return {
|
||||
observedAt,
|
||||
stream,
|
||||
payload,
|
||||
};
|
||||
}
|
||||
|
||||
describe("EventNdjsonLogger", () => {
|
||||
it("writes NDJSON records to disk", () => {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
|
||||
const filePath = path.join(tempDir, "provider-native.ndjson");
|
||||
it.effect("writes effect-style lines to thread-scoped files", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = path.join(tempDir, "provider-native.ndjson");
|
||||
|
||||
try {
|
||||
const logger = makeEventNdjsonLogger(filePath);
|
||||
expect(logger).toBeDefined();
|
||||
if (!logger) {
|
||||
return;
|
||||
try {
|
||||
const logger = yield* makeEventNdjsonLogger(basePath, { stream: "native" });
|
||||
assert.notEqual(logger, undefined);
|
||||
if (!logger) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* logger.write(
|
||||
{ threadId: "provider-thread-1", id: "evt-1" },
|
||||
ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
yield* logger.write(
|
||||
{ type: "turn.completed", threadId: "provider-thread-2", id: "evt-2" },
|
||||
ThreadId.makeUnsafe("thread-2"),
|
||||
);
|
||||
yield* logger.close();
|
||||
|
||||
const threadOnePath = path.join(tempDir, "thread-1.log");
|
||||
const threadTwoPath = path.join(tempDir, "thread-2.log");
|
||||
assert.equal(fs.existsSync(threadOnePath), true);
|
||||
assert.equal(fs.existsSync(threadTwoPath), true);
|
||||
|
||||
const first = parseLogLine(fs.readFileSync(threadOnePath, "utf8").trim());
|
||||
const second = parseLogLine(fs.readFileSync(threadTwoPath, "utf8").trim());
|
||||
|
||||
assert.equal(Number.isNaN(Date.parse(first.observedAt)), false);
|
||||
assert.equal(first.stream, "NTIVE");
|
||||
assert.equal(first.payload, '{"threadId":"provider-thread-1","id":"evt-1"}');
|
||||
|
||||
assert.equal(Number.isNaN(Date.parse(second.observedAt)), false);
|
||||
assert.equal(second.stream, "NTIVE");
|
||||
assert.equal(
|
||||
second.payload,
|
||||
'{"type":"turn.completed","threadId":"provider-thread-2","id":"evt-2"}',
|
||||
);
|
||||
} finally {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
logger.write({ type: "native", payload: { id: "evt-1" } });
|
||||
logger.write({ type: "canonical", payload: { id: "evt-2" } });
|
||||
logger.close();
|
||||
it.effect(
|
||||
"falls back to a global segment when orchestration thread id is missing or invalid",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = path.join(tempDir, "provider-canonical.ndjson");
|
||||
|
||||
const raw = fs.readFileSync(filePath, "utf8").trim();
|
||||
const lines = raw.split("\n");
|
||||
expect(lines.length).toBe(2);
|
||||
try {
|
||||
const logger = yield* makeEventNdjsonLogger(basePath, { stream: "orchestration" });
|
||||
assert.notEqual(logger, undefined);
|
||||
if (!logger) {
|
||||
return;
|
||||
}
|
||||
|
||||
const first = JSON.parse(lines[0] ?? "{}");
|
||||
const second = JSON.parse(lines[1] ?? "{}");
|
||||
expect(first).toEqual({ type: "native", payload: { id: "evt-1" } });
|
||||
expect(second).toEqual({ type: "canonical", payload: { id: "evt-2" } });
|
||||
} finally {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
yield* logger.write({ id: "evt-no-thread" }, null);
|
||||
yield* logger.write({ id: "evt-invalid-thread" }, "!!!" as unknown as ThreadId);
|
||||
yield* logger.close();
|
||||
|
||||
const globalPath = path.join(tempDir, "_global.log");
|
||||
assert.equal(fs.existsSync(globalPath), true);
|
||||
const lines = fs
|
||||
.readFileSync(globalPath, "utf8")
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => parseLogLine(line));
|
||||
assert.equal(lines.length, 2);
|
||||
assert.equal(Number.isNaN(Date.parse(lines[0]?.observedAt ?? "")), false);
|
||||
assert.equal(Number.isNaN(Date.parse(lines[1]?.observedAt ?? "")), false);
|
||||
assert.equal(lines[0]?.stream, "CANON");
|
||||
assert.equal(lines[0]?.payload, '{"id":"evt-no-thread"}');
|
||||
assert.equal(lines[1]?.stream, "CANON");
|
||||
assert.equal(lines[1]?.payload, '{"id":"evt-invalid-thread"}');
|
||||
} finally {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rotates per-thread files when max size is exceeded", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = path.join(tempDir, "provider-native.ndjson");
|
||||
|
||||
try {
|
||||
const logger = yield* makeEventNdjsonLogger(basePath, {
|
||||
stream: "native",
|
||||
maxBytes: 120,
|
||||
maxFiles: 2,
|
||||
});
|
||||
assert.notEqual(logger, undefined);
|
||||
if (!logger) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (let index = 0; index < 10; index += 1) {
|
||||
yield* logger.write(
|
||||
{
|
||||
threadId: "provider-thread-rotate",
|
||||
id: `evt-${index}`,
|
||||
payload: "x".repeat(40),
|
||||
},
|
||||
ThreadId.makeUnsafe("thread-rotate"),
|
||||
);
|
||||
}
|
||||
yield* logger.close();
|
||||
|
||||
const fileStem = "thread-rotate.log";
|
||||
const matchingFiles = fs
|
||||
.readdirSync(tempDir)
|
||||
.filter((entry) => entry === fileStem || entry.startsWith(`${fileStem}.`))
|
||||
.toSorted();
|
||||
|
||||
assert.equal(
|
||||
matchingFiles.some((entry) => entry === `${fileStem}.1`),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
matchingFiles.some((entry) => entry === fileStem || entry === `${fileStem}.2`),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
matchingFiles.some((entry) => entry === `${fileStem}.3`),
|
||||
false,
|
||||
);
|
||||
} finally {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,66 +1,257 @@
|
||||
/**
|
||||
* Provider event NDJSON logger helper.
|
||||
* Provider event logger helper.
|
||||
*
|
||||
* Best-effort writer for observability logs. Failures are downgraded to warnings
|
||||
* so provider runtime behavior is unaffected.
|
||||
* Best-effort writer for observability logs. Each record is formatted as a
|
||||
* single effect-style text line in a thread-scoped file. Failures are
|
||||
* downgraded to warnings so provider runtime behavior is unaffected.
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { createLogger } from "../../logger.ts";
|
||||
import type { ThreadId } from "@t3tools/contracts";
|
||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import { Effect, Exit, Logger, Scope } from "effect";
|
||||
|
||||
const logger = createLogger("provider-observability");
|
||||
import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts";
|
||||
|
||||
const DEFAULT_MAX_BYTES = 10 * 1024 * 1024;
|
||||
const DEFAULT_MAX_FILES = 10;
|
||||
const DEFAULT_BATCH_WINDOW_MS = 200;
|
||||
const GLOBAL_THREAD_SEGMENT = "_global";
|
||||
const LOG_SCOPE = "provider-observability";
|
||||
|
||||
export type EventNdjsonStream = "native" | "canonical" | "orchestration";
|
||||
|
||||
export interface EventNdjsonLogger {
|
||||
readonly filePath: string;
|
||||
write: (record: unknown) => void;
|
||||
close: () => void;
|
||||
write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void>;
|
||||
close: () => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
function stringifyRecord(record: unknown): string | undefined {
|
||||
try {
|
||||
return JSON.stringify(record);
|
||||
} catch (error) {
|
||||
logger.warn("failed to serialize provider event log record", { error });
|
||||
return undefined;
|
||||
export interface EventNdjsonLoggerOptions {
|
||||
readonly stream: EventNdjsonStream;
|
||||
readonly maxBytes?: number;
|
||||
readonly maxFiles?: number;
|
||||
readonly batchWindowMs?: number;
|
||||
}
|
||||
|
||||
interface ThreadWriter {
|
||||
writeMessage: (message: string) => Effect.Effect<void>;
|
||||
close: () => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
function logWarning(message: string, context: Record<string, unknown>): Effect.Effect<void> {
|
||||
return Effect.logWarning(message, context).pipe(Effect.annotateLogs({ scope: LOG_SCOPE }));
|
||||
}
|
||||
|
||||
function resolveThreadSegment(raw: string | null | undefined): string {
|
||||
const normalized = typeof raw === "string" ? toSafeThreadAttachmentSegment(raw) : null;
|
||||
return normalized ?? GLOBAL_THREAD_SEGMENT;
|
||||
}
|
||||
|
||||
function formatLoggerMessage(message: unknown): string {
|
||||
if (Array.isArray(message)) {
|
||||
return message.map((part) => (typeof part === "string" ? part : String(part))).join(" ");
|
||||
}
|
||||
return typeof message === "string" ? message : String(message);
|
||||
}
|
||||
|
||||
function makeLineLogger(streamLabel: string): Logger.Logger<unknown, string> {
|
||||
return Logger.make(
|
||||
({ date, message }) =>
|
||||
`[${date.toISOString()}] ${streamLabel}: ${formatLoggerMessage(message)}\n`,
|
||||
);
|
||||
}
|
||||
|
||||
function resolveStreamLabel(stream: EventNdjsonStream): string {
|
||||
switch (stream) {
|
||||
case "native":
|
||||
return "NTIVE";
|
||||
case "canonical":
|
||||
case "orchestration":
|
||||
default:
|
||||
return "CANON";
|
||||
}
|
||||
}
|
||||
|
||||
export function makeEventNdjsonLogger(filePath: string): EventNdjsonLogger | undefined {
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
fs.appendFileSync(filePath, "", { encoding: "utf8", flag: "a" });
|
||||
} catch (error) {
|
||||
logger.warn("failed to create provider event log directory", { filePath, error });
|
||||
return undefined;
|
||||
}
|
||||
function toLogMessage(event: unknown): Effect.Effect<string | undefined> {
|
||||
return Effect.gen(function* () {
|
||||
const serialized = yield* Effect.sync(() => {
|
||||
try {
|
||||
return { ok: true as const, value: JSON.stringify(event) };
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
let broken = false;
|
||||
if (!serialized.ok) {
|
||||
yield* logWarning("failed to serialize provider event log record", {
|
||||
error: serialized.error,
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (typeof serialized.value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return serialized.value;
|
||||
});
|
||||
}
|
||||
|
||||
function makeThreadWriter(input: {
|
||||
readonly filePath: string;
|
||||
readonly maxBytes: number;
|
||||
readonly maxFiles: number;
|
||||
readonly batchWindowMs: number;
|
||||
readonly streamLabel: string;
|
||||
}): Effect.Effect<ThreadWriter | undefined> {
|
||||
return Effect.gen(function* () {
|
||||
const sinkResult = yield* Effect.sync(() => {
|
||||
try {
|
||||
return {
|
||||
ok: true as const,
|
||||
sink: new RotatingFileSink({
|
||||
filePath: input.filePath,
|
||||
maxBytes: input.maxBytes,
|
||||
maxFiles: input.maxFiles,
|
||||
throwOnError: true,
|
||||
}),
|
||||
};
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
});
|
||||
|
||||
if (!sinkResult.ok) {
|
||||
yield* logWarning("failed to initialize provider thread log file", {
|
||||
filePath: input.filePath,
|
||||
error: sinkResult.error,
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const sink = sinkResult.sink;
|
||||
const scope = yield* Scope.make();
|
||||
const lineLogger = makeLineLogger(input.streamLabel);
|
||||
const batchedLogger = yield* Logger.batched(lineLogger, {
|
||||
window: input.batchWindowMs,
|
||||
flush: (messages) =>
|
||||
Effect.gen(function* () {
|
||||
const flushResult = yield* Effect.sync(() => {
|
||||
try {
|
||||
for (const message of messages) {
|
||||
sink.write(message);
|
||||
}
|
||||
return { ok: true as const };
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
});
|
||||
|
||||
if (!flushResult.ok) {
|
||||
yield* logWarning("provider event log batch flush failed", {
|
||||
filePath: input.filePath,
|
||||
error: flushResult.error,
|
||||
});
|
||||
}
|
||||
}),
|
||||
}).pipe(Effect.provideService(Scope.Scope, scope));
|
||||
|
||||
const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });
|
||||
|
||||
return {
|
||||
writeMessage(message: string) {
|
||||
return Effect.log(message).pipe(Effect.provide(loggerLayer));
|
||||
},
|
||||
close() {
|
||||
return Scope.close(scope, Exit.void);
|
||||
},
|
||||
} satisfies ThreadWriter;
|
||||
});
|
||||
}
|
||||
|
||||
export function makeEventNdjsonLogger(
|
||||
filePath: string,
|
||||
options: EventNdjsonLoggerOptions,
|
||||
): Effect.Effect<EventNdjsonLogger | undefined> {
|
||||
return Effect.gen(function* () {
|
||||
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
|
||||
const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
|
||||
const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS;
|
||||
const streamLabel = resolveStreamLabel(options.stream);
|
||||
|
||||
const directoryReady = yield* Effect.sync(() => {
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
return true;
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
});
|
||||
if (directoryReady !== true) {
|
||||
yield* logWarning("failed to create provider event log directory", {
|
||||
filePath,
|
||||
error: directoryReady.error,
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const threadWriters = new Map<string, ThreadWriter>();
|
||||
const failedSegments = new Set<string>();
|
||||
|
||||
const resolveThreadWriter = (threadSegment: string): Effect.Effect<ThreadWriter | undefined> =>
|
||||
Effect.gen(function* () {
|
||||
if (failedSegments.has(threadSegment)) {
|
||||
return undefined;
|
||||
}
|
||||
const existing = threadWriters.get(threadSegment);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
const writer = yield* makeThreadWriter({
|
||||
filePath: path.join(path.dirname(filePath), `${threadSegment}.log`),
|
||||
maxBytes,
|
||||
maxFiles,
|
||||
batchWindowMs,
|
||||
streamLabel,
|
||||
});
|
||||
if (!writer) {
|
||||
failedSegments.add(threadSegment);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
threadWriters.set(threadSegment, writer);
|
||||
return writer;
|
||||
});
|
||||
|
||||
return {
|
||||
filePath,
|
||||
write(record: unknown) {
|
||||
if (broken) {
|
||||
return;
|
||||
}
|
||||
const serialized = stringifyRecord(record);
|
||||
if (!serialized) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
fs.appendFileSync(filePath, `${serialized}\n`, { encoding: "utf8", flag: "a" });
|
||||
} catch (error) {
|
||||
broken = true;
|
||||
logger.warn("provider event log write failed", { filePath, error });
|
||||
}
|
||||
write(event: unknown, threadId: ThreadId | null) {
|
||||
return Effect.gen(function* () {
|
||||
const threadSegment = resolveThreadSegment(threadId);
|
||||
const message = yield* toLogMessage(event);
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
|
||||
const writer = yield* resolveThreadWriter(threadSegment);
|
||||
if (!writer) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* writer.writeMessage(message);
|
||||
});
|
||||
},
|
||||
close() {
|
||||
// no-op for sync append logger
|
||||
return Effect.gen(function* () {
|
||||
for (const writer of threadWriters.values()) {
|
||||
yield* writer.close();
|
||||
}
|
||||
threadWriters.clear();
|
||||
});
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
logger.warn("failed to create provider event log file", { filePath, error });
|
||||
return undefined;
|
||||
}
|
||||
} satisfies EventNdjsonLogger;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect } from "effect";
|
||||
|
||||
import { checkCodexProviderStatus, parseAuthStatusFromOutput } from "./ProviderHealth";
|
||||
|
||||
// ── Test helpers ────────────────────────────────────────────────────
|
||||
|
||||
function mockRunner(
|
||||
handler: (args: ReadonlyArray<string>) => {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
code: number | null;
|
||||
timedOut?: boolean;
|
||||
},
|
||||
) {
|
||||
return (args: ReadonlyArray<string>) => Promise.resolve(handler(args));
|
||||
}
|
||||
|
||||
function failingRunner(description: string) {
|
||||
return () => Promise.reject(new Error(description));
|
||||
}
|
||||
|
||||
// ── Tests ───────────────────────────────────────────────────────────
|
||||
|
||||
it.effect("returns ready when codex is installed and authenticated", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus(
|
||||
mockRunner((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}`);
|
||||
}),
|
||||
);
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when codex is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus(failingRunner("spawn codex ENOENT"));
|
||||
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.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns unauthenticated when auth probe reports login required", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus(
|
||||
mockRunner((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}`);
|
||||
}),
|
||||
);
|
||||
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.",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"returns unauthenticated when login status output includes 'not logged in'",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus(
|
||||
mockRunner((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}`);
|
||||
}),
|
||||
);
|
||||
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.",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns warning when login status command is unsupported", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus(
|
||||
mockRunner((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}`);
|
||||
}),
|
||||
);
|
||||
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.",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when codex version probe times out", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus(
|
||||
mockRunner((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") {
|
||||
return { stdout: "", stderr: "", code: null, timedOut: true };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
);
|
||||
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 is installed but failed to run. Timed out while running command.");
|
||||
}),
|
||||
);
|
||||
|
||||
it("parseAuthStatusFromOutput: timed out auth check is warning", () => {
|
||||
const parsed = parseAuthStatusFromOutput({ stdout: "", stderr: "", code: null, timedOut: true });
|
||||
assert.strictEqual(parsed.status, "warning");
|
||||
assert.strictEqual(parsed.authStatus, "unknown");
|
||||
assert.strictEqual(parsed.message, "Timed out while checking Codex authentication status.");
|
||||
});
|
||||
|
||||
// ── Pure function tests ─────────────────────────────────────────────
|
||||
|
||||
it("parseAuthStatusFromOutput: 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("parseAuthStatusFromOutput: 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("parseAuthStatusFromOutput: 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");
|
||||
});
|
||||
@@ -0,0 +1,311 @@
|
||||
/**
|
||||
* 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 the shared process runner to run CLI probes natively.
|
||||
*
|
||||
* @module ProviderHealthLive
|
||||
*/
|
||||
import type {
|
||||
ServerProviderAuthStatus,
|
||||
ServerProviderStatus,
|
||||
ServerProviderStatusState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, Effect, Layer, Result } from "effect";
|
||||
|
||||
import { runProcess } from "../../processRunner";
|
||||
import { ProviderHealth, type ProviderHealthShape } from "../Services/ProviderHealth";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 4_000;
|
||||
const CODEX_PROVIDER = "codex" as const;
|
||||
|
||||
class ProviderHealthCommandError extends Data.TaggedError("ProviderHealthCommandError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
// ── Pure helpers ────────────────────────────────────────────────────
|
||||
|
||||
export interface CommandResult {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly code: number | null;
|
||||
readonly timedOut?: boolean;
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
if (
|
||||
error &&
|
||||
typeof error === "object" &&
|
||||
"message" in error &&
|
||||
typeof (error as { message?: unknown }).message === "string"
|
||||
) {
|
||||
return (error as { message: string }).message;
|
||||
}
|
||||
|
||||
return String(error);
|
||||
}
|
||||
|
||||
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 {
|
||||
const lower = errorMessage(error).toLowerCase();
|
||||
return (
|
||||
lower.includes("command not found: codex") ||
|
||||
lower.includes("spawn codex enoent") ||
|
||||
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 === null) {
|
||||
return "Command was terminated before reporting an exit code.";
|
||||
}
|
||||
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;
|
||||
} {
|
||||
if (result.timedOut) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Timed out while checking Codex authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
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 type RunProviderHealthCommand = (
|
||||
args: ReadonlyArray<string>,
|
||||
) => Promise<CommandResult>;
|
||||
|
||||
const defaultRunCodexCommand: RunProviderHealthCommand = async (args) => {
|
||||
const result = await runProcess("codex", [...args], {
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: DEFAULT_TIMEOUT_MS,
|
||||
maxBufferBytes: 262_144,
|
||||
outputMode: "truncate",
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
code: result.code,
|
||||
timedOut: result.timedOut,
|
||||
} satisfies CommandResult;
|
||||
};
|
||||
|
||||
// ── Health check ────────────────────────────────────────────────────
|
||||
|
||||
export const checkCodexProviderStatus = (
|
||||
runCodexCommand: RunProviderHealthCommand = defaultRunCodexCommand,
|
||||
): Effect.Effect<ServerProviderStatus> =>
|
||||
Effect.gen(function* () {
|
||||
const checkedAt = new Date().toISOString();
|
||||
|
||||
// Probe 1: `codex --version` — is the CLI reachable?
|
||||
const versionProbe = yield* Effect.tryPromise({
|
||||
try: () => runCodexCommand(["--version"]),
|
||||
catch: (error) =>
|
||||
new ProviderHealthCommandError({
|
||||
message: errorMessage(error),
|
||||
...(error !== undefined ? { cause: error } : {}),
|
||||
}),
|
||||
}).pipe(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: ${errorMessage(error)}.`,
|
||||
};
|
||||
}
|
||||
|
||||
const version = versionProbe.success;
|
||||
if (version.timedOut || 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.",
|
||||
};
|
||||
}
|
||||
|
||||
// Probe 2: `codex login status` — is the user authenticated?
|
||||
const authProbe = yield* Effect.tryPromise({
|
||||
try: () => runCodexCommand(["login", "status"]),
|
||||
catch: (error) =>
|
||||
new ProviderHealthCommandError({
|
||||
message: errorMessage(error),
|
||||
...(error !== undefined ? { cause: error } : {}),
|
||||
}),
|
||||
}).pipe(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:
|
||||
errorMessage(error).length > 0
|
||||
? `Could not verify Codex authentication status: ${errorMessage(error)}.`
|
||||
: "Could not verify Codex authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
const parsed = parseAuthStatusFromOutput(authProbe.success);
|
||||
return {
|
||||
provider: CODEX_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 codexStatus = yield* checkCodexProviderStatus();
|
||||
return {
|
||||
getStatuses: Effect.succeed([codexStatus]),
|
||||
} satisfies ProviderHealthShape;
|
||||
}),
|
||||
);
|
||||
@@ -30,10 +30,11 @@ import {
|
||||
ProviderSessionDirectory,
|
||||
type ProviderSessionBinding,
|
||||
} from "../Services/ProviderSessionDirectory.ts";
|
||||
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
|
||||
export interface ProviderServiceLiveOptions {
|
||||
readonly canonicalEventLogPath?: string;
|
||||
readonly canonicalEventLogger?: EventNdjsonLogger;
|
||||
}
|
||||
|
||||
const ProviderRollbackConversationInput = Schema.Struct({
|
||||
@@ -108,9 +109,12 @@ function readPersistedCwd(
|
||||
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const canonicalEventLogger =
|
||||
options?.canonicalEventLogPath !== undefined
|
||||
? makeEventNdjsonLogger(options.canonicalEventLogPath)
|
||||
: undefined;
|
||||
options?.canonicalEventLogger ??
|
||||
(options?.canonicalEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, {
|
||||
stream: "canonical",
|
||||
})
|
||||
: undefined);
|
||||
|
||||
const registry = yield* ProviderAdapterRegistry;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
@@ -140,12 +144,20 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
canonicalizeRuntimeEventSession(event).pipe(
|
||||
Effect.tap((canonicalEvent) =>
|
||||
Effect.sync(() => {
|
||||
canonicalEventLogger?.write({
|
||||
observedAt: new Date().toISOString(),
|
||||
event: canonicalEvent,
|
||||
});
|
||||
}),
|
||||
canonicalEventLogger
|
||||
? Effect.flatMap(
|
||||
Effect.catch(
|
||||
directory.getThreadId(canonicalEvent.sessionId).pipe(
|
||||
Effect.map((threadIdOption) =>
|
||||
Option.isSome(threadIdOption) ? threadIdOption.value : null,
|
||||
),
|
||||
),
|
||||
() => Effect.succeed<ThreadId | null>(null),
|
||||
),
|
||||
(orchestrationThreadId) =>
|
||||
canonicalEventLogger.write(canonicalEvent, orchestrationThreadId),
|
||||
)
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
|
||||
Effect.asVoid,
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* ProviderHealth - Provider readiness snapshot service.
|
||||
*
|
||||
* Owns startup-time provider health checks (install/auth reachability) and
|
||||
* exposes the cached 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 provider health statuses computed at server startup.
|
||||
*/
|
||||
readonly getStatuses: Effect.Effect<ReadonlyArray<ServerProviderStatus>>;
|
||||
}
|
||||
|
||||
export class ProviderHealth extends ServiceMap.Service<ProviderHealth, ProviderHealthShape>()(
|
||||
"t3/provider/Services/ProviderHealth",
|
||||
) {}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
|
||||
describe("detectServerRuntimeEnvironment", () => {
|
||||
it("detects native windows mode", () => {
|
||||
expect(
|
||||
detectServerRuntimeEnvironment({
|
||||
platform: "win32",
|
||||
env: {},
|
||||
osRelease: "10.0.26100",
|
||||
}),
|
||||
).toEqual({
|
||||
platform: "windows",
|
||||
pathStyle: "windows",
|
||||
isWsl: false,
|
||||
windowsInteropMode: "windows-native",
|
||||
wslDistroName: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("detects wsl-hosted mode from environment variables", () => {
|
||||
expect(
|
||||
detectServerRuntimeEnvironment({
|
||||
platform: "linux",
|
||||
env: {
|
||||
WSL_DISTRO_NAME: "Ubuntu-24.04",
|
||||
WSL_INTEROP: "/run/WSL/123_interop",
|
||||
},
|
||||
osRelease: "6.6.87.2-microsoft-standard-WSL2",
|
||||
}),
|
||||
).toEqual({
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu-24.04",
|
||||
});
|
||||
});
|
||||
|
||||
it("detects wsl-hosted mode from os release when env is unavailable", () => {
|
||||
expect(
|
||||
detectServerRuntimeEnvironment({
|
||||
platform: "linux",
|
||||
env: {},
|
||||
osRelease: "5.15.167.4-microsoft-standard-WSL2",
|
||||
}),
|
||||
).toEqual({
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves non-wsl posix hosts outside the windows interop modes", () => {
|
||||
expect(
|
||||
detectServerRuntimeEnvironment({
|
||||
platform: "darwin",
|
||||
env: {},
|
||||
osRelease: "24.3.0",
|
||||
}),
|
||||
).toEqual({
|
||||
platform: "macos",
|
||||
pathStyle: "posix",
|
||||
isWsl: false,
|
||||
windowsInteropMode: null,
|
||||
wslDistroName: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import os from "node:os";
|
||||
|
||||
import type { ServerRuntimeEnvironment } from "@t3tools/contracts";
|
||||
|
||||
interface DetectServerRuntimeEnvironmentOptions {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly osRelease?: string;
|
||||
}
|
||||
|
||||
function normalizePlatform(platform: NodeJS.Platform): ServerRuntimeEnvironment["platform"] {
|
||||
switch (platform) {
|
||||
case "win32":
|
||||
return "windows";
|
||||
case "darwin":
|
||||
return "macos";
|
||||
default:
|
||||
return "linux";
|
||||
}
|
||||
}
|
||||
|
||||
function detectWsl(options: {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly osRelease: string;
|
||||
}): boolean {
|
||||
if (options.platform !== "linux") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (options.env.WSL_DISTRO_NAME || options.env.WSL_INTEROP) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return options.osRelease.toLowerCase().includes("microsoft");
|
||||
}
|
||||
|
||||
export function detectServerRuntimeEnvironment(
|
||||
options: DetectServerRuntimeEnvironmentOptions = {},
|
||||
): ServerRuntimeEnvironment {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const osRelease = options.osRelease ?? os.release();
|
||||
const normalizedPlatform = normalizePlatform(platform);
|
||||
const isWsl = detectWsl({ platform, env, osRelease });
|
||||
|
||||
return {
|
||||
platform: normalizedPlatform,
|
||||
pathStyle: normalizedPlatform === "windows" ? "windows" : "posix",
|
||||
isWsl,
|
||||
windowsInteropMode: normalizedPlatform === "windows" ? "windows-native" : isWsl ? "wsl-hosted" : null,
|
||||
wslDistroName: isWsl ? env.WSL_DISTRO_NAME?.trim() || null : null,
|
||||
};
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRe
|
||||
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
|
||||
import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory";
|
||||
import { ProviderService } from "./provider/Services/ProviderService";
|
||||
import { makeEventNdjsonLogger } from "./provider/Layers/EventNdjsonLogger";
|
||||
|
||||
import { TerminalManagerLive } from "./terminal/Layers/Manager";
|
||||
import { KeybindingsLive } from "./keybindings";
|
||||
@@ -37,21 +38,31 @@ import { NodePtyAdapterLive } from "./terminal/Layers/NodePTY";
|
||||
export function makeServerProviderLayer(): Layer.Layer<
|
||||
ProviderService,
|
||||
ProviderUnsupportedError,
|
||||
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem
|
||||
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem | NodeServices.NodeServices
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const { stateDir } = yield* ServerConfig;
|
||||
const providerLogsDir = path.join(stateDir, "logs", "providers");
|
||||
const codexAdapterLayer = makeCodexAdapterLive({
|
||||
nativeEventLogPath: path.join(providerLogsDir, "provider-native.ndjson"),
|
||||
const providerLogsDir = path.join(stateDir, "logs", "provider");
|
||||
const providerEventLogPath = path.join(providerLogsDir, "events.log");
|
||||
const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
stream: "native",
|
||||
});
|
||||
const canonicalEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
stream: "canonical",
|
||||
});
|
||||
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(Layer.provide(codexAdapterLayer));
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
return makeProviderServiceLive({
|
||||
canonicalEventLogPath: path.join(providerLogsDir, "provider-canonical.ndjson"),
|
||||
}).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer));
|
||||
const codexAdapterLayer = makeCodexAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
|
||||
Layer.provide(codexAdapterLayer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
);
|
||||
return makeProviderServiceLive(
|
||||
canonicalEventLogger ? { canonicalEventLogger } : undefined,
|
||||
).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer));
|
||||
}).pipe(Layer.unwrap);
|
||||
}
|
||||
|
||||
@@ -94,7 +105,11 @@ export function makeServerRuntimeServicesLayer() {
|
||||
);
|
||||
|
||||
const terminalLayer = TerminalManagerLive.pipe(
|
||||
Layer.provide(typeof Bun !== "undefined" ? BunPtyAdapterLive : NodePtyAdapterLive),
|
||||
Layer.provide(
|
||||
typeof Bun !== "undefined" && process.platform !== "win32"
|
||||
? BunPtyAdapterLive
|
||||
: NodePtyAdapterLive,
|
||||
),
|
||||
);
|
||||
|
||||
const gitManagerLayer = GitManagerLive.pipe(
|
||||
|
||||
@@ -4,6 +4,7 @@ import path from "node:path";
|
||||
|
||||
import {
|
||||
DEFAULT_TERMINAL_ID,
|
||||
type ServerRuntimeEnvironment,
|
||||
type TerminalEvent,
|
||||
type TerminalOpenInput,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -16,7 +17,11 @@ import {
|
||||
type PtyProcess,
|
||||
type PtySpawnInput,
|
||||
} from "../Services/PTY";
|
||||
import { TerminalManagerRuntime } from "./Manager";
|
||||
import {
|
||||
resolveShellCandidates,
|
||||
TerminalManagerRuntime,
|
||||
validateTerminalCwdForRuntime,
|
||||
} from "./Manager";
|
||||
import { Effect, Encoding } from "effect";
|
||||
|
||||
class FakePtyProcess implements PtyProcess {
|
||||
@@ -172,6 +177,7 @@ describe("TerminalManager", () => {
|
||||
options: {
|
||||
shellResolver?: () => string;
|
||||
subprocessChecker?: (terminalPid: number) => Promise<boolean>;
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment;
|
||||
subprocessPollIntervalMs?: number;
|
||||
processKillGraceMs?: number;
|
||||
maxRetainedInactiveSessions?: number;
|
||||
@@ -186,6 +192,7 @@ describe("TerminalManager", () => {
|
||||
ptyAdapter,
|
||||
historyLineLimit,
|
||||
shellResolver: options.shellResolver ?? (() => "/bin/bash"),
|
||||
...(options.runtimeEnvironment ? { runtimeEnvironment: options.runtimeEnvironment } : {}),
|
||||
...(options.subprocessChecker ? { subprocessChecker: options.subprocessChecker } : {}),
|
||||
...(options.subprocessPollIntervalMs
|
||||
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
|
||||
@@ -669,4 +676,93 @@ describe("TerminalManager", () => {
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("resolves Windows shell candidates from runtime environment instead of host assumptions", () => {
|
||||
const runtimeEnvironment: ServerRuntimeEnvironment = {
|
||||
platform: "windows",
|
||||
pathStyle: "windows",
|
||||
isWsl: false,
|
||||
windowsInteropMode: "windows-native",
|
||||
wslDistroName: null,
|
||||
};
|
||||
|
||||
const candidates = resolveShellCandidates(() => "/bin/bash -l", runtimeEnvironment);
|
||||
|
||||
expect(candidates.map((candidate) => candidate.shell)).toContain("cmd.exe");
|
||||
expect(candidates.map((candidate) => candidate.shell)).toContain("powershell.exe");
|
||||
expect(candidates.map((candidate) => candidate.shell)).not.toContain("/bin/sh");
|
||||
});
|
||||
|
||||
it("resolves POSIX shell candidates for wsl-hosted runtime even when the requested shell is Windows-style", () => {
|
||||
const runtimeEnvironment: ServerRuntimeEnvironment = {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
};
|
||||
|
||||
const candidates = resolveShellCandidates(() => "powershell.exe", runtimeEnvironment);
|
||||
|
||||
expect(candidates.map((candidate) => candidate.shell)).toContain("powershell.exe");
|
||||
expect(candidates.map((candidate) => candidate.shell)).toContain("/bin/bash");
|
||||
expect(candidates.map((candidate) => candidate.shell)).toContain("sh");
|
||||
});
|
||||
|
||||
it("rejects POSIX cwd values for windows-native terminal runtimes", async () => {
|
||||
const runtimeEnvironment: ServerRuntimeEnvironment = {
|
||||
platform: "windows",
|
||||
pathStyle: "windows",
|
||||
isWsl: false,
|
||||
windowsInteropMode: "windows-native",
|
||||
wslDistroName: null,
|
||||
};
|
||||
const { manager, ptyAdapter } = makeManager(5, { runtimeEnvironment });
|
||||
|
||||
await expect(manager.open(openInput({ cwd: "/home/julius/project" }))).rejects.toThrow(
|
||||
"Terminal cwd does not match Windows runtime path style",
|
||||
);
|
||||
expect(ptyAdapter.spawnInputs).toHaveLength(0);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("rejects Windows cwd values for wsl-hosted terminal runtimes", async () => {
|
||||
const runtimeEnvironment: ServerRuntimeEnvironment = {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
};
|
||||
const { manager, ptyAdapter } = makeManager(5, { runtimeEnvironment });
|
||||
|
||||
await expect(manager.open(openInput({ cwd: "C:\\Users\\julius\\project" }))).rejects.toThrow(
|
||||
"Terminal cwd does not match POSIX runtime path style",
|
||||
);
|
||||
expect(ptyAdapter.spawnInputs).toHaveLength(0);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("validates cwd compatibility as a pure runtime helper", () => {
|
||||
expect(
|
||||
validateTerminalCwdForRuntime("/repo", {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(
|
||||
validateTerminalCwdForRuntime("\\\\wsl.localhost\\Ubuntu\\repo", {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
}),
|
||||
).toContain("POSIX runtime path style");
|
||||
});
|
||||
});
|
||||
@@ -9,12 +9,14 @@ import {
|
||||
TerminalOpenInput,
|
||||
TerminalResizeInput,
|
||||
TerminalWriteInput,
|
||||
type ServerRuntimeEnvironment,
|
||||
type TerminalEvent,
|
||||
type TerminalSessionSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Encoding, Layer, Path, Schema } from "effect";
|
||||
|
||||
import { createLogger } from "../../logger";
|
||||
import { detectServerRuntimeEnvironment } from "../../runtimeEnvironment";
|
||||
import { PtyAdapter, PtyAdapterShape, type PtyExitEvent, type PtyProcess } from "../Services/PTY";
|
||||
import { runProcess } from "../../processRunner";
|
||||
import { ServerConfig } from "../../config";
|
||||
@@ -35,6 +37,8 @@ const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128;
|
||||
const DEFAULT_OPEN_COLS = 120;
|
||||
const DEFAULT_OPEN_ROWS = 30;
|
||||
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
|
||||
const WINDOWS_ABSOLUTE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
|
||||
const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
|
||||
|
||||
const decodeTerminalOpenInput = Schema.decodeUnknownSync(TerminalOpenInput);
|
||||
const decodeTerminalWriteInput = Schema.decodeUnknownSync(TerminalWriteInput);
|
||||
@@ -44,19 +48,22 @@ const decodeTerminalCloseInput = Schema.decodeUnknownSync(TerminalCloseInput);
|
||||
|
||||
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
|
||||
|
||||
function defaultShellResolver(): string {
|
||||
if (process.platform === "win32") {
|
||||
function defaultShellResolver(runtimeEnvironment: ServerRuntimeEnvironment): string {
|
||||
if (runtimeEnvironment.platform === "windows") {
|
||||
return process.env.ComSpec ?? "cmd.exe";
|
||||
}
|
||||
return process.env.SHELL ?? "bash";
|
||||
}
|
||||
|
||||
function normalizeShellCommand(value: string | undefined): string | null {
|
||||
function normalizeShellCommand(
|
||||
value: string | undefined,
|
||||
runtimeEnvironment: ServerRuntimeEnvironment,
|
||||
): string | null {
|
||||
if (!value) return null;
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) return null;
|
||||
|
||||
if (process.platform === "win32") {
|
||||
if (runtimeEnvironment.platform === "windows") {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
@@ -65,10 +72,13 @@ function normalizeShellCommand(value: string | undefined): string | null {
|
||||
return firstToken.replace(/^['"]|['"]$/g, "");
|
||||
}
|
||||
|
||||
function shellCandidateFromCommand(command: string | null): ShellCandidate | null {
|
||||
function shellCandidateFromCommand(
|
||||
command: string | null,
|
||||
runtimeEnvironment: ServerRuntimeEnvironment,
|
||||
): ShellCandidate | null {
|
||||
if (!command || command.length === 0) return null;
|
||||
const shellName = path.basename(command).toLowerCase();
|
||||
if (process.platform !== "win32" && shellName === "zsh") {
|
||||
if (runtimeEnvironment.platform !== "windows" && shellName === "zsh") {
|
||||
return { shell: command, args: ["-o", "nopromptsp"] };
|
||||
}
|
||||
return { shell: command };
|
||||
@@ -92,27 +102,36 @@ function uniqueShellCandidates(candidates: Array<ShellCandidate | null>): ShellC
|
||||
return ordered;
|
||||
}
|
||||
|
||||
function resolveShellCandidates(shellResolver: () => string): ShellCandidate[] {
|
||||
const requested = shellCandidateFromCommand(normalizeShellCommand(shellResolver()));
|
||||
export function resolveShellCandidates(
|
||||
shellResolver: () => string,
|
||||
runtimeEnvironment: ServerRuntimeEnvironment = detectServerRuntimeEnvironment(),
|
||||
): ShellCandidate[] {
|
||||
const requested = shellCandidateFromCommand(
|
||||
normalizeShellCommand(shellResolver(), runtimeEnvironment),
|
||||
runtimeEnvironment,
|
||||
);
|
||||
|
||||
if (process.platform === "win32") {
|
||||
if (runtimeEnvironment.platform === "windows") {
|
||||
return uniqueShellCandidates([
|
||||
requested,
|
||||
shellCandidateFromCommand(process.env.ComSpec ?? null),
|
||||
shellCandidateFromCommand("powershell.exe"),
|
||||
shellCandidateFromCommand("cmd.exe"),
|
||||
shellCandidateFromCommand(process.env.ComSpec ?? null, runtimeEnvironment),
|
||||
shellCandidateFromCommand("powershell.exe", runtimeEnvironment),
|
||||
shellCandidateFromCommand("cmd.exe", runtimeEnvironment),
|
||||
]);
|
||||
}
|
||||
|
||||
return uniqueShellCandidates([
|
||||
requested,
|
||||
shellCandidateFromCommand(normalizeShellCommand(process.env.SHELL)),
|
||||
shellCandidateFromCommand("/bin/zsh"),
|
||||
shellCandidateFromCommand("/bin/bash"),
|
||||
shellCandidateFromCommand("/bin/sh"),
|
||||
shellCandidateFromCommand("zsh"),
|
||||
shellCandidateFromCommand("bash"),
|
||||
shellCandidateFromCommand("sh"),
|
||||
shellCandidateFromCommand(
|
||||
normalizeShellCommand(process.env.SHELL, runtimeEnvironment),
|
||||
runtimeEnvironment,
|
||||
),
|
||||
shellCandidateFromCommand("/bin/zsh", runtimeEnvironment),
|
||||
shellCandidateFromCommand("/bin/bash", runtimeEnvironment),
|
||||
shellCandidateFromCommand("/bin/sh", runtimeEnvironment),
|
||||
shellCandidateFromCommand("zsh", runtimeEnvironment),
|
||||
shellCandidateFromCommand("bash", runtimeEnvironment),
|
||||
shellCandidateFromCommand("sh", runtimeEnvironment),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -178,6 +197,13 @@ async function checkWindowsSubprocessActivity(terminalPid: number): Promise<bool
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 32_768,
|
||||
outputMode: "truncate",
|
||||
runtimeEnvironment: {
|
||||
platform: "windows",
|
||||
pathStyle: "windows",
|
||||
isWsl: false,
|
||||
windowsInteropMode: "windows-native",
|
||||
wslDistroName: null,
|
||||
},
|
||||
},
|
||||
);
|
||||
return result.code === 0;
|
||||
@@ -230,14 +256,37 @@ async function checkPosixSubprocessActivity(terminalPid: number): Promise<boolea
|
||||
}
|
||||
}
|
||||
|
||||
async function defaultSubprocessChecker(terminalPid: number): Promise<boolean> {
|
||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
||||
return false;
|
||||
function createDefaultSubprocessChecker(runtimeEnvironment: ServerRuntimeEnvironment) {
|
||||
return async (terminalPid: number): Promise<boolean> => {
|
||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
||||
return false;
|
||||
}
|
||||
if (runtimeEnvironment.platform === "windows") {
|
||||
return checkWindowsSubprocessActivity(terminalPid);
|
||||
}
|
||||
return checkPosixSubprocessActivity(terminalPid);
|
||||
};
|
||||
}
|
||||
|
||||
function isWindowsPath(value: string): boolean {
|
||||
return WINDOWS_ABSOLUTE_PATH_PATTERN.test(value) || WINDOWS_UNC_PATH_PATTERN.test(value);
|
||||
}
|
||||
|
||||
export function validateTerminalCwdForRuntime(
|
||||
cwd: string,
|
||||
runtimeEnvironment: ServerRuntimeEnvironment = detectServerRuntimeEnvironment(),
|
||||
): string | null {
|
||||
if (runtimeEnvironment.pathStyle === "windows") {
|
||||
if (cwd.startsWith("/")) {
|
||||
return `Terminal cwd does not match Windows runtime path style: ${cwd}`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (process.platform === "win32") {
|
||||
return checkWindowsSubprocessActivity(terminalPid);
|
||||
|
||||
if (isWindowsPath(cwd)) {
|
||||
return `Terminal cwd does not match POSIX runtime path style: ${cwd}`;
|
||||
}
|
||||
return checkPosixSubprocessActivity(terminalPid);
|
||||
return null;
|
||||
}
|
||||
|
||||
function capHistory(history: string, maxLines: number): string {
|
||||
@@ -316,6 +365,7 @@ interface TerminalManagerOptions {
|
||||
ptyAdapter: PtyAdapterShape;
|
||||
shellResolver?: () => string;
|
||||
subprocessChecker?: TerminalSubprocessChecker;
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment;
|
||||
subprocessPollIntervalMs?: number;
|
||||
processKillGraceMs?: number;
|
||||
maxRetainedInactiveSessions?: number;
|
||||
@@ -333,6 +383,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
private readonly threadLocks = new Map<string, Promise<void>>();
|
||||
private readonly persistDebounceMs: number;
|
||||
private readonly subprocessChecker: TerminalSubprocessChecker;
|
||||
private readonly runtimeEnvironment: ServerRuntimeEnvironment;
|
||||
private readonly subprocessPollIntervalMs: number;
|
||||
private readonly processKillGraceMs: number;
|
||||
private readonly maxRetainedInactiveSessions: number;
|
||||
@@ -343,12 +394,15 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
|
||||
constructor(options: TerminalManagerOptions) {
|
||||
super();
|
||||
this.runtimeEnvironment = options.runtimeEnvironment ?? detectServerRuntimeEnvironment();
|
||||
this.logsDir = options.logsDir ?? path.resolve(process.cwd(), ".logs", "terminals");
|
||||
this.historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
|
||||
this.ptyAdapter = options.ptyAdapter;
|
||||
this.shellResolver = options.shellResolver ?? defaultShellResolver;
|
||||
this.shellResolver =
|
||||
options.shellResolver ?? (() => defaultShellResolver(this.runtimeEnvironment));
|
||||
this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS;
|
||||
this.subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
|
||||
this.subprocessChecker =
|
||||
options.subprocessChecker ?? createDefaultSubprocessChecker(this.runtimeEnvironment);
|
||||
this.subprocessPollIntervalMs =
|
||||
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
|
||||
this.processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;
|
||||
@@ -589,7 +643,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
let ptyProcess: PtyProcess | null = null;
|
||||
let startedShell: string | null = null;
|
||||
try {
|
||||
const shellCandidates = resolveShellCandidates(this.shellResolver);
|
||||
const shellCandidates = resolveShellCandidates(this.shellResolver, this.runtimeEnvironment);
|
||||
const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv);
|
||||
let lastSpawnError: unknown = null;
|
||||
|
||||
@@ -1051,6 +1105,11 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
}
|
||||
|
||||
private async assertValidCwd(cwd: string): Promise<void> {
|
||||
const runtimePathError = validateTerminalCwdForRuntime(cwd, this.runtimeEnvironment);
|
||||
if (runtimePathError) {
|
||||
throw new Error(runtimePathError);
|
||||
}
|
||||
|
||||
let stats: fs.Stats;
|
||||
try {
|
||||
stats = await fs.promises.stat(cwd);
|
||||
@@ -1173,10 +1232,11 @@ export const TerminalManagerLive = Layer.effect(
|
||||
const { stateDir } = yield* ServerConfig;
|
||||
const { join } = yield* Path.Path;
|
||||
const logsDir = join(stateDir, "logs", "terminals");
|
||||
const runtimeEnvironment = detectServerRuntimeEnvironment();
|
||||
|
||||
const ptyAdapter = yield* PtyAdapter;
|
||||
const runtime = yield* Effect.acquireRelease(
|
||||
Effect.sync(() => new TerminalManagerRuntime({ logsDir, ptyAdapter })),
|
||||
Effect.sync(() => new TerminalManagerRuntime({ logsDir, ptyAdapter, runtimeEnvironment })),
|
||||
(r) => Effect.sync(() => r.dispose()),
|
||||
);
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
WS_METHODS,
|
||||
type WebSocketResponse,
|
||||
type ProviderRuntimeEvent,
|
||||
type ServerProviderStatus,
|
||||
type KeybindingsConfig,
|
||||
type ResolvedKeybindingsConfig,
|
||||
type WsPush,
|
||||
@@ -43,12 +44,14 @@ import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/
|
||||
import { makeSqlitePersistenceLive, SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
|
||||
import { SqlClient, SqlError } from "effect/unstable/sql";
|
||||
import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService";
|
||||
import { ProviderHealth, type ProviderHealthShape } from "./provider/Services/ProviderHealth";
|
||||
import { Open, type OpenShape } from "./open";
|
||||
import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts";
|
||||
import type { GitCoreShape } from "./git/Services/GitCore.ts";
|
||||
import { GitCore } from "./git/Services/GitCore.ts";
|
||||
import { GitCommandError, GitManagerError } from "./git/Errors.ts";
|
||||
import { MigrationError } from "@effect/sql-sqlite-bun/SqliteMigrator";
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
|
||||
interface PendingMessages {
|
||||
queue: unknown[];
|
||||
@@ -69,6 +72,22 @@ const defaultOpenService: OpenShape = {
|
||||
openInEditor: () => Effect.void,
|
||||
};
|
||||
|
||||
const defaultProviderStatuses: ReadonlyArray<ServerProviderStatus> = [
|
||||
{
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
available: true,
|
||||
authStatus: "authenticated",
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
];
|
||||
|
||||
const defaultProviderHealthService: ProviderHealthShape = {
|
||||
getStatuses: Effect.succeed(defaultProviderStatuses),
|
||||
};
|
||||
|
||||
const defaultRuntimeEnvironment = detectServerRuntimeEnvironment();
|
||||
|
||||
class MockTerminalManager implements TerminalManagerShape {
|
||||
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
|
||||
private readonly listeners = new Set<(event: TerminalEvent) => void>();
|
||||
@@ -377,6 +396,7 @@ describe("WebSocket Server", () => {
|
||||
stateDir?: string;
|
||||
staticDir?: string;
|
||||
providerLayer?: Layer.Layer<ProviderService, never>;
|
||||
providerHealth?: ProviderHealthShape;
|
||||
open?: OpenShape;
|
||||
gitManager?: GitManagerShape;
|
||||
gitCore?: Pick<
|
||||
@@ -394,6 +414,10 @@ describe("WebSocket Server", () => {
|
||||
const scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
const persistenceLayer = options.persistenceLayer ?? SqlitePersistenceMemory;
|
||||
const providerLayer = options.providerLayer ?? makeServerProviderLayer();
|
||||
const providerHealthLayer = Layer.succeed(
|
||||
ProviderHealth,
|
||||
options.providerHealth ?? defaultProviderHealthService,
|
||||
);
|
||||
const openLayer = Layer.succeed(Open, options.open ?? defaultOpenService);
|
||||
const serverConfigLayer = Layer.succeed(ServerConfig, {
|
||||
mode: "web",
|
||||
@@ -428,6 +452,7 @@ describe("WebSocket Server", () => {
|
||||
);
|
||||
const dependenciesLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(runtimeLayer),
|
||||
Layer.provideMerge(providerHealthLayer),
|
||||
Layer.provideMerge(openLayer),
|
||||
Layer.provideMerge(serverConfigLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
@@ -736,7 +761,9 @@ describe("WebSocket Server", () => {
|
||||
keybindingsConfigPath: keybindingsPath,
|
||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
});
|
||||
@@ -761,7 +788,9 @@ describe("WebSocket Server", () => {
|
||||
keybindingsConfigPath: keybindingsPath,
|
||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
|
||||
@@ -796,7 +825,9 @@ describe("WebSocket Server", () => {
|
||||
message: expect.stringContaining("expected JSON array"),
|
||||
},
|
||||
],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
expect(fs.readFileSync(keybindingsPath, "utf8")).toBe("{ not-json");
|
||||
@@ -830,7 +861,9 @@ describe("WebSocket Server", () => {
|
||||
keybindingsConfigPath: string;
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
issues: Array<{ kind: string; index?: number; message: string }>;
|
||||
providers: ReadonlyArray<ServerProviderStatus>;
|
||||
availableEditors: unknown;
|
||||
runtimeEnvironment: unknown;
|
||||
};
|
||||
expect(result.cwd).toBe("/my/workspace");
|
||||
expect(result.keybindingsConfigPath).toBe(keybindingsPath);
|
||||
@@ -849,7 +882,9 @@ describe("WebSocket Server", () => {
|
||||
expect(result.keybindings).toHaveLength(DEFAULT_RESOLVED_KEYBINDINGS.length);
|
||||
expect(result.keybindings.some((entry) => entry.command === "terminal.toggle")).toBe(true);
|
||||
expect(result.keybindings.some((entry) => entry.command === "terminal.new")).toBe(true);
|
||||
expect(result.providers).toEqual(defaultProviderStatuses);
|
||||
expectAvailableEditors(result.availableEditors);
|
||||
expect(result.runtimeEnvironment).toEqual(defaultRuntimeEnvironment);
|
||||
});
|
||||
|
||||
it("pushes server.configUpdated issues when keybindings file changes", async () => {
|
||||
@@ -877,6 +912,7 @@ describe("WebSocket Server", () => {
|
||||
);
|
||||
expect(malformedPush.data).toEqual({
|
||||
issues: [{ kind: "keybindings.malformed-config", message: expect.any(String) }],
|
||||
providers: defaultProviderStatuses,
|
||||
});
|
||||
|
||||
fs.writeFileSync(keybindingsPath, "[]", "utf8");
|
||||
@@ -887,7 +923,7 @@ describe("WebSocket Server", () => {
|
||||
Array.isArray((push.data as { issues?: unknown[] }).issues) &&
|
||||
(push.data as { issues: unknown[] }).issues.length === 0,
|
||||
);
|
||||
expect(successPush.data).toEqual({ issues: [] });
|
||||
expect(successPush.data).toEqual({ issues: [], providers: defaultProviderStatuses });
|
||||
});
|
||||
|
||||
it("routes shell.openInEditor through the injected open service", async () => {
|
||||
@@ -947,7 +983,9 @@ describe("WebSocket Server", () => {
|
||||
keybindingsConfigPath: keybindingsPath,
|
||||
keybindings: compileKeybindings(persistedConfig),
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
});
|
||||
@@ -994,7 +1032,9 @@ describe("WebSocket Server", () => {
|
||||
keybindingsConfigPath: keybindingsPath,
|
||||
keybindings: compileKeybindings(persistedConfig),
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors(
|
||||
(configResponse.result as { availableEditors: unknown }).availableEditors,
|
||||
|
||||
@@ -52,12 +52,14 @@ import { OrchestrationEngineService } from "./orchestration/Services/Orchestrati
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor";
|
||||
import { ProviderService } from "./provider/Services/ProviderService";
|
||||
import { ProviderHealth } from "./provider/Services/ProviderHealth";
|
||||
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
|
||||
import { clamp } from "effect/Number";
|
||||
import { Open, resolveAvailableEditors } from "./open";
|
||||
import { ServerConfig } from "./config";
|
||||
import { GitCore } from "./git/Services/GitCore.ts";
|
||||
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
import {
|
||||
ATTACHMENTS_ROUTE_PREFIX,
|
||||
normalizeAttachmentRelativePath,
|
||||
@@ -154,7 +156,8 @@ export type ServerCoreRuntimeServices =
|
||||
| ProjectionSnapshotQuery
|
||||
| CheckpointDiffQuery
|
||||
| OrchestrationReactor
|
||||
| ProviderService;
|
||||
| ProviderService
|
||||
| ProviderHealth;
|
||||
|
||||
export type ServerRuntimeServices =
|
||||
| ServerCoreRuntimeServices
|
||||
@@ -194,10 +197,12 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
autoBootstrapProjectFromCwd,
|
||||
} = serverConfig;
|
||||
const availableEditors = resolveAvailableEditors();
|
||||
const runtimeEnvironment = detectServerRuntimeEnvironment();
|
||||
|
||||
const gitManager = yield* GitManager;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
const keybindingsManager = yield* Keybindings;
|
||||
const providerHealth = yield* ProviderHealth;
|
||||
const git = yield* GitCore;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -212,6 +217,8 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
),
|
||||
);
|
||||
|
||||
const providerStatuses = yield* providerHealth.getStatuses;
|
||||
|
||||
const clients = yield* Ref.make(new Set<WebSocket>());
|
||||
const logger = createLogger("ws");
|
||||
|
||||
@@ -537,7 +544,10 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
broadcastPush({
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.serverConfigUpdated,
|
||||
data: event,
|
||||
data: {
|
||||
issues: event.issues,
|
||||
providers: providerStatuses,
|
||||
},
|
||||
}),
|
||||
).pipe(Effect.forkIn(subscriptionsScope));
|
||||
|
||||
@@ -735,7 +745,9 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
keybindingsConfigPath,
|
||||
keybindings: keybindingsConfig.keybindings,
|
||||
issues: keybindingsConfig.issues,
|
||||
providers: providerStatuses,
|
||||
availableEditors,
|
||||
runtimeEnvironment,
|
||||
};
|
||||
|
||||
case WS_METHODS.serverUpsertKeybinding: {
|
||||
|
||||
@@ -21,5 +21,5 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"include": ["src", "tsdown.config.ts", "scripts", "integration"]
|
||||
"include": ["src", "tsdown.config.ts", "scripts", "integration", "../../scripts/lib"]
|
||||
}
|
||||
@@ -3,10 +3,13 @@ import { defineConfig } from "tsdown";
|
||||
export default defineConfig({
|
||||
entry: ["src/index.ts"],
|
||||
format: ["esm", "cjs"],
|
||||
checks: {
|
||||
legacyCjs: false,
|
||||
},
|
||||
outDir: "dist",
|
||||
sourcemap: true,
|
||||
clean: true,
|
||||
noExternal: ["@t3tools/contracts"],
|
||||
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||
inlineOnly: false,
|
||||
banner: {
|
||||
js: "#!/usr/bin/env node\n",
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"prepare": "effect-language-service patch",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests"
|
||||
@@ -15,6 +16,7 @@
|
||||
"@lexical/react": "^0.41.0",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
"@tanstack/react-router": "^1.160.2",
|
||||
@@ -41,7 +43,8 @@
|
||||
"@vitejs/plugin-react": "^5.1.4",
|
||||
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "^5.7.3",
|
||||
"vite": "^8.0.0-beta.12"
|
||||
"typescript": "catalog:",
|
||||
"vite": "^8.0.0-beta.12",
|
||||
"vitest": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { getAppModelOptions, normalizeCustomModelSlugs } from "./appSettings";
|
||||
import { getAppModelOptions, getSlashModelOptions, normalizeCustomModelSlugs } from "./appSettings";
|
||||
|
||||
describe("normalizeCustomModelSlugs", () => {
|
||||
it("normalizes aliases, removes built-ins, and deduplicates values", () => {
|
||||
@@ -40,3 +40,17 @@ describe("getAppModelOptions", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("getSlashModelOptions", () => {
|
||||
it("includes saved custom model slugs for /model command suggestions", () => {
|
||||
const options = getSlashModelOptions(["custom/internal-model"], "", "gpt-5.3-codex");
|
||||
|
||||
expect(options.some((option) => option.slug === "custom/internal-model")).toBe(true);
|
||||
});
|
||||
|
||||
it("filters slash-model suggestions across built-in and custom model names", () => {
|
||||
const options = getSlashModelOptions(["openai/gpt-oss-120b"], "oss", "gpt-5.3-codex");
|
||||
|
||||
expect(options.map((option) => option.slug)).toEqual(["openai/gpt-oss-120b"]);
|
||||
});
|
||||
});
|
||||
@@ -105,6 +105,24 @@ export function getAppModelOptions(
|
||||
return options;
|
||||
}
|
||||
|
||||
export function getSlashModelOptions(
|
||||
customModels: readonly string[],
|
||||
query: string,
|
||||
selectedModel?: string | null,
|
||||
): AppModelOption[] {
|
||||
const normalizedQuery = query.trim().toLowerCase();
|
||||
const options = getAppModelOptions(customModels, selectedModel);
|
||||
if (!normalizedQuery) {
|
||||
return options;
|
||||
}
|
||||
|
||||
return options.filter((option) => {
|
||||
const searchSlug = option.slug.toLowerCase();
|
||||
const searchName = option.name.toLowerCase();
|
||||
return searchSlug.includes(normalizedQuery) || searchName.includes(normalizedQuery);
|
||||
});
|
||||
}
|
||||
|
||||
function emitChange(): void {
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
|
||||
@@ -3,8 +3,77 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
resolveDraftEnvModeAfterBranchChange,
|
||||
resolveBranchToolbarValue,
|
||||
} from "./BranchToolbar.logic";
|
||||
|
||||
describe("resolveDraftEnvModeAfterBranchChange", () => {
|
||||
it("switches to local mode when returning from an existing worktree to the main worktree", () => {
|
||||
expect(
|
||||
resolveDraftEnvModeAfterBranchChange({
|
||||
nextWorktreePath: null,
|
||||
currentWorktreePath: "/repo/.t3/worktrees/feature-a",
|
||||
effectiveEnvMode: "worktree",
|
||||
}),
|
||||
).toBe("local");
|
||||
});
|
||||
|
||||
it("keeps new-worktree mode when selecting a base branch before worktree creation", () => {
|
||||
expect(
|
||||
resolveDraftEnvModeAfterBranchChange({
|
||||
nextWorktreePath: null,
|
||||
currentWorktreePath: null,
|
||||
effectiveEnvMode: "worktree",
|
||||
}),
|
||||
).toBe("worktree");
|
||||
});
|
||||
|
||||
it("uses worktree mode when selecting a branch already attached to a worktree", () => {
|
||||
expect(
|
||||
resolveDraftEnvModeAfterBranchChange({
|
||||
nextWorktreePath: "/repo/.t3/worktrees/feature-a",
|
||||
currentWorktreePath: null,
|
||||
effectiveEnvMode: "local",
|
||||
}),
|
||||
).toBe("worktree");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveBranchToolbarValue", () => {
|
||||
it("defaults new-worktree mode to current git branch when no explicit base branch is set", () => {
|
||||
expect(
|
||||
resolveBranchToolbarValue({
|
||||
envMode: "worktree",
|
||||
activeWorktreePath: null,
|
||||
activeThreadBranch: null,
|
||||
currentGitBranch: "main",
|
||||
}),
|
||||
).toBe("main");
|
||||
});
|
||||
|
||||
it("keeps an explicitly selected worktree base branch", () => {
|
||||
expect(
|
||||
resolveBranchToolbarValue({
|
||||
envMode: "worktree",
|
||||
activeWorktreePath: null,
|
||||
activeThreadBranch: "feature/base",
|
||||
currentGitBranch: "main",
|
||||
}),
|
||||
).toBe("feature/base");
|
||||
});
|
||||
|
||||
it("shows the actual checked-out branch when not selecting a new worktree base", () => {
|
||||
expect(
|
||||
resolveBranchToolbarValue({
|
||||
envMode: "local",
|
||||
activeWorktreePath: null,
|
||||
activeThreadBranch: "feature/base",
|
||||
currentGitBranch: "main",
|
||||
}),
|
||||
).toBe("main");
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveLocalBranchNameFromRemoteRef", () => {
|
||||
it("strips the remote prefix from a remote ref", () => {
|
||||
expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo");
|
||||
|
||||
@@ -1,5 +1,46 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
|
||||
export type EnvMode = "local" | "worktree";
|
||||
|
||||
export function resolveEffectiveEnvMode(input: {
|
||||
activeWorktreePath: string | null;
|
||||
hasServerThread: boolean;
|
||||
draftThreadEnvMode: EnvMode | undefined;
|
||||
}): EnvMode {
|
||||
const { activeWorktreePath, hasServerThread, draftThreadEnvMode } = input;
|
||||
return activeWorktreePath || (!hasServerThread && draftThreadEnvMode === "worktree")
|
||||
? "worktree"
|
||||
: "local";
|
||||
}
|
||||
|
||||
export function resolveDraftEnvModeAfterBranchChange(input: {
|
||||
nextWorktreePath: string | null;
|
||||
currentWorktreePath: string | null;
|
||||
effectiveEnvMode: EnvMode;
|
||||
}): EnvMode {
|
||||
const { nextWorktreePath, currentWorktreePath, effectiveEnvMode } = input;
|
||||
if (nextWorktreePath) {
|
||||
return "worktree";
|
||||
}
|
||||
if (effectiveEnvMode === "worktree" && !currentWorktreePath) {
|
||||
return "worktree";
|
||||
}
|
||||
return "local";
|
||||
}
|
||||
|
||||
export function resolveBranchToolbarValue(input: {
|
||||
envMode: EnvMode;
|
||||
activeWorktreePath: string | null;
|
||||
activeThreadBranch: string | null;
|
||||
currentGitBranch: string | null;
|
||||
}): string | null {
|
||||
const { envMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
|
||||
if (envMode === "worktree" && !activeWorktreePath) {
|
||||
return activeThreadBranch ?? currentGitBranch;
|
||||
}
|
||||
return currentGitBranch ?? activeThreadBranch;
|
||||
}
|
||||
|
||||
export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
|
||||
const firstSeparatorIndex = branchName.indexOf("/");
|
||||
if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
|
||||
|
||||
@@ -1,40 +1,27 @@
|
||||
import type { GitBranch, ThreadId } from "@t3tools/contracts";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useOptimistic, useState, useTransition } from "react";
|
||||
import type { ThreadId } from "@t3tools/contracts";
|
||||
import { useCallback } from "react";
|
||||
|
||||
import { newCommandId } from "../lib/utils";
|
||||
import { gitBranchesQueryOptions, invalidateGitQueries } from "../lib/gitReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { useStore } from "../store";
|
||||
import {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
EnvMode,
|
||||
resolveDraftEnvModeAfterBranchChange,
|
||||
resolveEffectiveEnvMode,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Combobox,
|
||||
ComboboxEmpty,
|
||||
ComboboxInput,
|
||||
ComboboxItem,
|
||||
ComboboxList,
|
||||
ComboboxPopup,
|
||||
ComboboxTrigger,
|
||||
} from "./ui/combobox";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { toastManager } from "./ui/toast";
|
||||
|
||||
interface BranchToolbarProps {
|
||||
threadId: ThreadId;
|
||||
envMode: "local" | "worktree";
|
||||
onEnvModeChange: (mode: "local" | "worktree") => void;
|
||||
onEnvModeChange: (mode: EnvMode) => void;
|
||||
envLocked: boolean;
|
||||
onComposerFocusRequest?: () => void;
|
||||
}
|
||||
|
||||
export default function BranchToolbar({
|
||||
threadId,
|
||||
envMode,
|
||||
onEnvModeChange,
|
||||
envLocked,
|
||||
onComposerFocusRequest,
|
||||
@@ -42,13 +29,8 @@ export default function BranchToolbar({
|
||||
const threads = useStore((store) => store.threads);
|
||||
const projects = useStore((store) => store.projects);
|
||||
const setThreadBranchAction = useStore((store) => store.setThreadBranch);
|
||||
const setThreadErrorAction = useStore((store) => store.setError);
|
||||
const draftThread = useComposerDraftStore((store) => store.getDraftThread(threadId));
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
|
||||
const [branchQuery, setBranchQuery] = useState("");
|
||||
|
||||
const serverThread = threads.find((thread) => thread.id === threadId);
|
||||
const activeProjectId = serverThread?.projectId ?? draftThread?.projectId ?? null;
|
||||
@@ -58,184 +40,64 @@ export default function BranchToolbar({
|
||||
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
|
||||
const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null;
|
||||
const hasServerThread = serverThread !== undefined;
|
||||
const effectiveEnvMode: "local" | "worktree" =
|
||||
activeWorktreePath || (!hasServerThread && draftThread?.envMode === "worktree")
|
||||
? "worktree"
|
||||
: envMode;
|
||||
const effectiveEnvMode = resolveEffectiveEnvMode({
|
||||
activeWorktreePath,
|
||||
hasServerThread,
|
||||
draftThreadEnvMode: draftThread?.envMode,
|
||||
});
|
||||
|
||||
// ── Queries ───────────────────────────────────────────────────────────
|
||||
|
||||
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
|
||||
|
||||
const branches = dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []);
|
||||
const currentGitBranch = branches.find((branch) => branch.current)?.name ?? null;
|
||||
const canonicalActiveBranch =
|
||||
effectiveEnvMode === "worktree" && !activeWorktreePath
|
||||
? activeThreadBranch
|
||||
: (currentGitBranch ?? activeThreadBranch);
|
||||
const branchNames = branches.map((branch) => branch.name);
|
||||
const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
|
||||
const trimmedBranchQuery = branchQuery.trim();
|
||||
const canCreateBranch = effectiveEnvMode === "local" && trimmedBranchQuery.length > 0;
|
||||
const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
|
||||
const createBranchItemValue = canCreateBranch
|
||||
? `__create_new_branch__:${trimmedBranchQuery}`
|
||||
: null;
|
||||
const branchPickerItems =
|
||||
createBranchItemValue && !hasExactBranchMatch
|
||||
? [...branchNames, createBranchItemValue]
|
||||
: branchNames;
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
|
||||
canonicalActiveBranch,
|
||||
(_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
|
||||
);
|
||||
const [isBranchActionPending, startBranchActionTransition] = useTransition();
|
||||
const runBranchAction = (action: () => Promise<void>) => {
|
||||
startBranchActionTransition(async () => {
|
||||
await action().catch(() => undefined);
|
||||
await invalidateGitQueries(queryClient).catch(() => undefined);
|
||||
});
|
||||
};
|
||||
|
||||
const setThreadError = (error: string | null) => {
|
||||
if (!activeThreadId) return;
|
||||
setThreadErrorAction(activeThreadId, error);
|
||||
};
|
||||
|
||||
const setThreadBranch = (branch: string | null, worktreePath: string | null) => {
|
||||
if (!activeThreadId) return;
|
||||
const api = readNativeApi();
|
||||
// If the effective cwd is about to change, stop the running session so the
|
||||
// next message creates a new one with the correct cwd.
|
||||
const sessionId = serverThread?.session?.sessionId;
|
||||
if (sessionId && worktreePath !== activeWorktreePath && api) {
|
||||
void api.orchestration
|
||||
.dispatchCommand({
|
||||
type: "thread.session.stop",
|
||||
const setThreadBranch = useCallback(
|
||||
(branch: string | null, worktreePath: string | null) => {
|
||||
if (!activeThreadId) return;
|
||||
const api = readNativeApi();
|
||||
// If the effective cwd is about to change, stop the running session so the
|
||||
// next message creates a new one with the correct cwd.
|
||||
const sessionId = serverThread?.session?.sessionId;
|
||||
if (sessionId && worktreePath !== activeWorktreePath && api) {
|
||||
void api.orchestration
|
||||
.dispatchCommand({
|
||||
type: "thread.session.stop",
|
||||
commandId: newCommandId(),
|
||||
threadId: activeThreadId,
|
||||
createdAt: new Date().toISOString(),
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
if (api && hasServerThread) {
|
||||
void api.orchestration.dispatchCommand({
|
||||
type: "thread.meta.update",
|
||||
commandId: newCommandId(),
|
||||
threadId: activeThreadId,
|
||||
createdAt: new Date().toISOString(),
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
if (api && hasServerThread) {
|
||||
void api.orchestration.dispatchCommand({
|
||||
type: "thread.meta.update",
|
||||
commandId: newCommandId(),
|
||||
threadId: activeThreadId,
|
||||
branch,
|
||||
worktreePath,
|
||||
});
|
||||
}
|
||||
if (hasServerThread) {
|
||||
setThreadBranchAction(activeThreadId, branch, worktreePath);
|
||||
return;
|
||||
}
|
||||
const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({
|
||||
nextWorktreePath: worktreePath,
|
||||
currentWorktreePath: activeWorktreePath,
|
||||
effectiveEnvMode,
|
||||
});
|
||||
setDraftThreadContext(threadId, {
|
||||
branch,
|
||||
worktreePath,
|
||||
envMode: nextDraftEnvMode,
|
||||
});
|
||||
}
|
||||
if (hasServerThread) {
|
||||
setThreadBranchAction(activeThreadId, branch, worktreePath);
|
||||
return;
|
||||
}
|
||||
setDraftThreadContext(threadId, {
|
||||
branch,
|
||||
worktreePath,
|
||||
envMode: effectiveEnvMode,
|
||||
});
|
||||
};
|
||||
|
||||
const selectBranch = (branch: GitBranch) => {
|
||||
const api = readNativeApi();
|
||||
if (!api || !activeThreadId || !branchCwd || isBranchActionPending) return;
|
||||
|
||||
// For new worktree mode, selecting a branch picks the base branch.
|
||||
if (effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath) {
|
||||
setThreadBranch(branch.name, null);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
return;
|
||||
}
|
||||
|
||||
// If the branch already lives in a worktree, redirect there instead of
|
||||
// trying to checkout (which git would reject with "already used by worktree").
|
||||
if (branch.worktreePath) {
|
||||
const isMainWorktree = branch.worktreePath === activeProject?.cwd;
|
||||
// Main worktree → switch back to local (project cwd, worktreePath=null).
|
||||
// Secondary worktree → point the thread at that worktree path.
|
||||
setThreadBranch(branch.name, isMainWorktree ? null : branch.worktreePath);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedBranchName = branch.isRemote
|
||||
? deriveLocalBranchNameFromRemoteRef(branch.name)
|
||||
: branch.name;
|
||||
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
|
||||
runBranchAction(async () => {
|
||||
setOptimisticBranch(selectedBranchName);
|
||||
try {
|
||||
await api.git.checkout({ cwd: branchCwd, branch: branch.name });
|
||||
await invalidateGitQueries(queryClient);
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to checkout branch.",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let nextBranchName = selectedBranchName;
|
||||
if (branch.isRemote) {
|
||||
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
|
||||
if (status?.branch) {
|
||||
nextBranchName = status.branch;
|
||||
}
|
||||
}
|
||||
|
||||
setOptimisticBranch(nextBranchName);
|
||||
setThreadBranch(nextBranchName, activeWorktreePath);
|
||||
});
|
||||
};
|
||||
|
||||
const createBranch = (rawName: string) => {
|
||||
const name = rawName.trim();
|
||||
const api = readNativeApi();
|
||||
if (!api || !activeThreadId || !branchCwd || !name || isBranchActionPending) return;
|
||||
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
|
||||
runBranchAction(async () => {
|
||||
setOptimisticBranch(name);
|
||||
|
||||
try {
|
||||
await api.git.createBranch({ cwd: branchCwd, branch: name });
|
||||
try {
|
||||
await api.git.checkout({ cwd: branchCwd, branch: name });
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to checkout branch.",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to create branch.",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setOptimisticBranch(name);
|
||||
setThreadBranch(name, activeWorktreePath);
|
||||
setBranchQuery("");
|
||||
});
|
||||
};
|
||||
},
|
||||
[
|
||||
activeThreadId,
|
||||
serverThread?.session?.sessionId,
|
||||
activeWorktreePath,
|
||||
hasServerThread,
|
||||
setThreadBranchAction,
|
||||
setDraftThreadContext,
|
||||
threadId,
|
||||
effectiveEnvMode,
|
||||
],
|
||||
);
|
||||
|
||||
if (!activeThreadId || !activeProject) return null;
|
||||
|
||||
@@ -259,96 +121,16 @@ export default function BranchToolbar({
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Combobox
|
||||
items={branchPickerItems}
|
||||
autoHighlight
|
||||
onOpenChange={(open) => {
|
||||
setIsBranchMenuOpen(open);
|
||||
if (!open) setBranchQuery("");
|
||||
else void invalidateGitQueries(queryClient);
|
||||
}}
|
||||
open={isBranchMenuOpen}
|
||||
value={resolvedActiveBranch}
|
||||
>
|
||||
<ComboboxTrigger
|
||||
render={<Button variant="ghost" size="xs" />}
|
||||
className="text-muted-foreground/70 hover:text-foreground/80"
|
||||
disabled={branchesQuery.isLoading || isBranchActionPending}
|
||||
>
|
||||
<span className="max-w-[240px] truncate">
|
||||
{resolvedActiveBranch
|
||||
? effectiveEnvMode === "worktree" && !activeWorktreePath
|
||||
? `From ${resolvedActiveBranch}`
|
||||
: resolvedActiveBranch
|
||||
: "Select branch"}
|
||||
</span>
|
||||
<ChevronDownIcon />
|
||||
</ComboboxTrigger>
|
||||
<ComboboxPopup align="end" side="top" className="w-64">
|
||||
<div className="border-b p-1">
|
||||
<ComboboxInput
|
||||
className="[&_input]:font-sans rounded-md"
|
||||
inputClassName="ring-0"
|
||||
placeholder="Search branches..."
|
||||
showTrigger={false}
|
||||
size="sm"
|
||||
value={branchQuery}
|
||||
onChange={(event) => setBranchQuery(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<ComboboxEmpty>No branches found.</ComboboxEmpty>
|
||||
|
||||
<ComboboxList className="max-h-56">
|
||||
{(itemValue) => {
|
||||
if (createBranchItemValue && itemValue === createBranchItemValue) {
|
||||
return (
|
||||
<ComboboxItem
|
||||
hideIndicator
|
||||
key={itemValue}
|
||||
value={itemValue}
|
||||
onClick={() => createBranch(trimmedBranchQuery)}
|
||||
>
|
||||
<span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
|
||||
</ComboboxItem>
|
||||
);
|
||||
}
|
||||
|
||||
const branch = branchByName.get(itemValue);
|
||||
if (!branch) return null;
|
||||
|
||||
const hasSecondaryWorktree =
|
||||
branch.worktreePath && branch.worktreePath !== activeProject.cwd;
|
||||
const badge = branch.current
|
||||
? "current"
|
||||
: hasSecondaryWorktree
|
||||
? "worktree"
|
||||
: branch.isRemote
|
||||
? "remote"
|
||||
: branch.isDefault
|
||||
? "default"
|
||||
: null;
|
||||
return (
|
||||
<ComboboxItem
|
||||
hideIndicator
|
||||
key={itemValue}
|
||||
value={itemValue}
|
||||
className={
|
||||
itemValue === resolvedActiveBranch ? "bg-accent text-foreground" : undefined
|
||||
}
|
||||
onClick={() => selectBranch(branch)}
|
||||
>
|
||||
<div className="flex w-full items-center justify-between gap-2">
|
||||
<span className="truncate">{itemValue}</span>
|
||||
{badge && (
|
||||
<span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>
|
||||
)}
|
||||
</div>
|
||||
</ComboboxItem>
|
||||
);
|
||||
}}
|
||||
</ComboboxList>
|
||||
</ComboboxPopup>
|
||||
</Combobox>
|
||||
<BranchToolbarBranchSelector
|
||||
activeProjectCwd={activeProject.cwd}
|
||||
activeThreadBranch={activeThreadBranch}
|
||||
activeWorktreePath={activeWorktreePath}
|
||||
branchCwd={branchCwd}
|
||||
effectiveEnvMode={effectiveEnvMode}
|
||||
envLocked={envLocked}
|
||||
onSetThreadBranch={setThreadBranch}
|
||||
{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useOptimistic,
|
||||
useRef,
|
||||
useState,
|
||||
useTransition,
|
||||
} from "react";
|
||||
|
||||
import { gitBranchesQueryOptions, gitQueryKeys, invalidateGitQueries } from "../lib/gitReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
EnvMode,
|
||||
resolveBranchToolbarValue,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Combobox,
|
||||
ComboboxEmpty,
|
||||
ComboboxInput,
|
||||
ComboboxItem,
|
||||
ComboboxList,
|
||||
ComboboxPopup,
|
||||
ComboboxTrigger,
|
||||
} from "./ui/combobox";
|
||||
import { toastManager } from "./ui/toast";
|
||||
|
||||
interface BranchToolbarBranchSelectorProps {
|
||||
activeProjectCwd: string;
|
||||
activeThreadBranch: string | null;
|
||||
activeWorktreePath: string | null;
|
||||
branchCwd: string | null;
|
||||
effectiveEnvMode: EnvMode;
|
||||
envLocked: boolean;
|
||||
onSetThreadBranch: (branch: string | null, worktreePath: string | null) => void;
|
||||
onComposerFocusRequest?: () => void;
|
||||
}
|
||||
|
||||
function toBranchActionErrorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : "An error occurred.";
|
||||
}
|
||||
|
||||
function getBranchTriggerLabel(input: {
|
||||
activeWorktreePath: string | null;
|
||||
effectiveEnvMode: EnvMode;
|
||||
resolvedActiveBranch: string | null;
|
||||
}): string {
|
||||
const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch } = input;
|
||||
if (!resolvedActiveBranch) {
|
||||
return "Select branch";
|
||||
}
|
||||
if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
|
||||
return `From ${resolvedActiveBranch}`;
|
||||
}
|
||||
return resolvedActiveBranch;
|
||||
}
|
||||
|
||||
export function BranchToolbarBranchSelector({
|
||||
activeProjectCwd,
|
||||
activeThreadBranch,
|
||||
activeWorktreePath,
|
||||
branchCwd,
|
||||
effectiveEnvMode,
|
||||
envLocked,
|
||||
onSetThreadBranch,
|
||||
onComposerFocusRequest,
|
||||
}: BranchToolbarBranchSelectorProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
|
||||
const [branchQuery, setBranchQuery] = useState("");
|
||||
|
||||
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
|
||||
const branches = useMemo(
|
||||
() => dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []),
|
||||
[branchesQuery.data?.branches],
|
||||
);
|
||||
const currentGitBranch = branches.find((branch) => branch.current)?.name ?? null;
|
||||
const canonicalActiveBranch = resolveBranchToolbarValue({
|
||||
envMode: effectiveEnvMode,
|
||||
activeWorktreePath,
|
||||
activeThreadBranch,
|
||||
currentGitBranch,
|
||||
});
|
||||
const branchNames = useMemo(() => branches.map((branch) => branch.name), [branches]);
|
||||
const branchByName = useMemo(
|
||||
() => new Map(branches.map((branch) => [branch.name, branch] as const)),
|
||||
[branches],
|
||||
);
|
||||
const trimmedBranchQuery = branchQuery.trim();
|
||||
const normalizedBranchQuery = trimmedBranchQuery.toLowerCase();
|
||||
const canCreateBranch = effectiveEnvMode === "local" && trimmedBranchQuery.length > 0;
|
||||
const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
|
||||
const createBranchItemValue = canCreateBranch
|
||||
? `__create_new_branch__:${trimmedBranchQuery}`
|
||||
: null;
|
||||
const branchPickerItems = useMemo(
|
||||
() =>
|
||||
createBranchItemValue && !hasExactBranchMatch
|
||||
? [...branchNames, createBranchItemValue]
|
||||
: branchNames,
|
||||
[branchNames, createBranchItemValue, hasExactBranchMatch],
|
||||
);
|
||||
const filteredBranchPickerItems = useMemo(
|
||||
() =>
|
||||
normalizedBranchQuery.length === 0
|
||||
? branchPickerItems
|
||||
: branchPickerItems.filter((itemValue) => {
|
||||
if (createBranchItemValue && itemValue === createBranchItemValue) return true;
|
||||
return itemValue.toLowerCase().includes(normalizedBranchQuery);
|
||||
}),
|
||||
[branchPickerItems, createBranchItemValue, normalizedBranchQuery],
|
||||
);
|
||||
const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
|
||||
canonicalActiveBranch,
|
||||
(_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
|
||||
);
|
||||
const [isBranchActionPending, startBranchActionTransition] = useTransition();
|
||||
|
||||
const runBranchAction = (action: () => Promise<void>) => {
|
||||
startBranchActionTransition(async () => {
|
||||
await action().catch(() => undefined);
|
||||
await invalidateGitQueries(queryClient).catch(() => undefined);
|
||||
});
|
||||
};
|
||||
|
||||
const selectBranch = (branch: GitBranch) => {
|
||||
const api = readNativeApi();
|
||||
if (!api || !branchCwd || isBranchActionPending) return;
|
||||
|
||||
// In new-worktree mode, selecting a branch sets the base branch.
|
||||
if (effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath) {
|
||||
onSetThreadBranch(branch.name, null);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
return;
|
||||
}
|
||||
|
||||
// If the branch already lives in a worktree, point the thread there.
|
||||
if (branch.worktreePath) {
|
||||
const isMainWorktree = branch.worktreePath === activeProjectCwd;
|
||||
onSetThreadBranch(branch.name, isMainWorktree ? null : branch.worktreePath);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedBranchName = branch.isRemote
|
||||
? deriveLocalBranchNameFromRemoteRef(branch.name)
|
||||
: branch.name;
|
||||
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
|
||||
runBranchAction(async () => {
|
||||
setOptimisticBranch(selectedBranchName);
|
||||
try {
|
||||
await api.git.checkout({ cwd: branchCwd, branch: branch.name });
|
||||
await invalidateGitQueries(queryClient);
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to checkout branch.",
|
||||
description: toBranchActionErrorMessage(error),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let nextBranchName = selectedBranchName;
|
||||
if (branch.isRemote) {
|
||||
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
|
||||
if (status?.branch) {
|
||||
nextBranchName = status.branch;
|
||||
}
|
||||
}
|
||||
|
||||
setOptimisticBranch(nextBranchName);
|
||||
onSetThreadBranch(nextBranchName, activeWorktreePath);
|
||||
});
|
||||
};
|
||||
|
||||
const createBranch = (rawName: string) => {
|
||||
const name = rawName.trim();
|
||||
const api = readNativeApi();
|
||||
if (!api || !branchCwd || !name || isBranchActionPending) return;
|
||||
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
|
||||
runBranchAction(async () => {
|
||||
setOptimisticBranch(name);
|
||||
|
||||
try {
|
||||
await api.git.createBranch({ cwd: branchCwd, branch: name });
|
||||
try {
|
||||
await api.git.checkout({ cwd: branchCwd, branch: name });
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to checkout branch.",
|
||||
description: toBranchActionErrorMessage(error),
|
||||
});
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to create branch.",
|
||||
description: toBranchActionErrorMessage(error),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setOptimisticBranch(name);
|
||||
onSetThreadBranch(name, activeWorktreePath);
|
||||
setBranchQuery("");
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
effectiveEnvMode !== "worktree" ||
|
||||
activeWorktreePath ||
|
||||
activeThreadBranch ||
|
||||
!currentGitBranch
|
||||
) {
|
||||
return;
|
||||
}
|
||||
onSetThreadBranch(currentGitBranch, null);
|
||||
}, [
|
||||
activeThreadBranch,
|
||||
activeWorktreePath,
|
||||
currentGitBranch,
|
||||
effectiveEnvMode,
|
||||
onSetThreadBranch,
|
||||
]);
|
||||
|
||||
const handleOpenChange = useCallback(
|
||||
(open: boolean) => {
|
||||
setIsBranchMenuOpen(open);
|
||||
if (!open) {
|
||||
setBranchQuery("");
|
||||
return;
|
||||
}
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: gitQueryKeys.branches(branchCwd),
|
||||
});
|
||||
},
|
||||
[branchCwd, queryClient],
|
||||
);
|
||||
|
||||
const branchListScrollElementRef = useRef<HTMLDivElement | null>(null);
|
||||
const branchListVirtualizer = useVirtualizer({
|
||||
count: filteredBranchPickerItems.length,
|
||||
estimateSize: () => 28,
|
||||
getScrollElement: () => branchListScrollElementRef.current,
|
||||
overscan: 12,
|
||||
enabled: isBranchMenuOpen,
|
||||
initialRect: {
|
||||
height: 224,
|
||||
width: 0,
|
||||
},
|
||||
});
|
||||
const virtualBranchRows = branchListVirtualizer.getVirtualItems();
|
||||
const setBranchListRef = useCallback(
|
||||
(element: HTMLDivElement | null) => {
|
||||
branchListScrollElementRef.current =
|
||||
(element?.parentElement as HTMLDivElement | null) ?? null;
|
||||
if (element) {
|
||||
branchListVirtualizer.measure();
|
||||
}
|
||||
},
|
||||
[branchListVirtualizer],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isBranchMenuOpen) return;
|
||||
queueMicrotask(() => {
|
||||
branchListVirtualizer.measure();
|
||||
});
|
||||
}, [branchListVirtualizer, filteredBranchPickerItems.length, isBranchMenuOpen]);
|
||||
|
||||
const triggerLabel = getBranchTriggerLabel({
|
||||
activeWorktreePath,
|
||||
effectiveEnvMode,
|
||||
resolvedActiveBranch,
|
||||
});
|
||||
|
||||
return (
|
||||
<Combobox
|
||||
items={branchPickerItems}
|
||||
filteredItems={filteredBranchPickerItems}
|
||||
autoHighlight
|
||||
virtualized
|
||||
onItemHighlighted={(_value, eventDetails) => {
|
||||
if (!isBranchMenuOpen || eventDetails.index < 0) return;
|
||||
branchListVirtualizer.scrollToIndex(eventDetails.index, { align: "auto" });
|
||||
}}
|
||||
onOpenChange={handleOpenChange}
|
||||
open={isBranchMenuOpen}
|
||||
value={resolvedActiveBranch}
|
||||
>
|
||||
<ComboboxTrigger
|
||||
render={<Button variant="ghost" size="xs" />}
|
||||
className="text-muted-foreground/70 hover:text-foreground/80"
|
||||
disabled={branchesQuery.isLoading || isBranchActionPending}
|
||||
>
|
||||
<span className="max-w-[240px] truncate">{triggerLabel}</span>
|
||||
<ChevronDownIcon />
|
||||
</ComboboxTrigger>
|
||||
<ComboboxPopup align="end" side="top" className="w-64">
|
||||
<div className="border-b p-1">
|
||||
<ComboboxInput
|
||||
className="[&_input]:font-sans rounded-md"
|
||||
inputClassName="ring-0"
|
||||
placeholder="Search branches..."
|
||||
showTrigger={false}
|
||||
size="sm"
|
||||
value={branchQuery}
|
||||
onChange={(event) => setBranchQuery(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<ComboboxEmpty>No branches found.</ComboboxEmpty>
|
||||
|
||||
<ComboboxList ref={setBranchListRef} className="max-h-56">
|
||||
<div
|
||||
className="relative"
|
||||
style={{
|
||||
height: `${branchListVirtualizer.getTotalSize()}px`,
|
||||
}}
|
||||
>
|
||||
{virtualBranchRows.map((virtualRow) => {
|
||||
const itemValue = filteredBranchPickerItems[virtualRow.index];
|
||||
if (!itemValue) return null;
|
||||
if (createBranchItemValue && itemValue === createBranchItemValue) {
|
||||
return (
|
||||
<ComboboxItem
|
||||
hideIndicator
|
||||
key={itemValue}
|
||||
index={virtualRow.index}
|
||||
value={itemValue}
|
||||
style={{
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: "100%",
|
||||
transform: `translateY(${virtualRow.start}px)`,
|
||||
}}
|
||||
onClick={() => createBranch(trimmedBranchQuery)}
|
||||
>
|
||||
<span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
|
||||
</ComboboxItem>
|
||||
);
|
||||
}
|
||||
|
||||
const branch = branchByName.get(itemValue);
|
||||
if (!branch) return null;
|
||||
|
||||
const hasSecondaryWorktree =
|
||||
branch.worktreePath && branch.worktreePath !== activeProjectCwd;
|
||||
const badge = branch.current
|
||||
? "current"
|
||||
: hasSecondaryWorktree
|
||||
? "worktree"
|
||||
: branch.isRemote
|
||||
? "remote"
|
||||
: branch.isDefault
|
||||
? "default"
|
||||
: null;
|
||||
return (
|
||||
<ComboboxItem
|
||||
hideIndicator
|
||||
key={itemValue}
|
||||
index={virtualRow.index}
|
||||
value={itemValue}
|
||||
className={
|
||||
itemValue === resolvedActiveBranch ? "bg-accent text-foreground" : undefined
|
||||
}
|
||||
style={{
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: "100%",
|
||||
transform: `translateY(${virtualRow.start}px)`,
|
||||
}}
|
||||
onClick={() => selectBranch(branch)}
|
||||
>
|
||||
<div className="flex w-full items-center justify-between gap-2">
|
||||
<span className="truncate">{itemValue}</span>
|
||||
{badge && (
|
||||
<span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>
|
||||
)}
|
||||
</div>
|
||||
</ComboboxItem>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</ComboboxList>
|
||||
</ComboboxPopup>
|
||||
</Combobox>
|
||||
);
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
type ReasoningEffort,
|
||||
type ResolvedKeybindingsConfig,
|
||||
type ProviderApprovalDecision,
|
||||
type ServerProviderStatus,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
normalizeModelSlug,
|
||||
@@ -118,7 +119,7 @@ import { Toggle } from "./ui/toggle";
|
||||
import { SidebarTrigger } from "./ui/sidebar";
|
||||
import { newCommandId, newMessageId } from "~/lib/utils";
|
||||
import { readNativeApi } from "~/nativeApi";
|
||||
import { getAppModelOptions, useAppSettings } from "../appSettings";
|
||||
import { getAppModelOptions, getSlashModelOptions, useAppSettings } from "../appSettings";
|
||||
import {
|
||||
type ComposerImageAttachment,
|
||||
type DraftThreadEnvMode,
|
||||
@@ -148,6 +149,7 @@ const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
const EMPTY_PROJECT_ENTRIES: ProjectEntry[] = [];
|
||||
const EMPTY_AVAILABLE_EDITORS: EditorId[] = [];
|
||||
const EMPTY_PROVIDER_STATUSES: ServerProviderStatus[] = [];
|
||||
const COMPOSER_PATH_QUERY_DEBOUNCE_MS = 120;
|
||||
const SCRIPT_TERMINAL_COLS = 120;
|
||||
const SCRIPT_TERMINAL_ROWS = 30;
|
||||
@@ -524,7 +526,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const pendingUserScrollUpIntentRef = useRef(false);
|
||||
const pendingAutoScrollFrameRef = useRef<number | null>(null);
|
||||
const composerEditorRef = useRef<ComposerPromptEditorHandle>(null);
|
||||
const composerCommandInputRef = useRef<HTMLInputElement>(null);
|
||||
const composerFormRef = useRef<HTMLFormElement>(null);
|
||||
const composerFormHeightRef = useRef(0);
|
||||
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
|
||||
@@ -632,6 +633,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
() => getAppModelOptions(settings.customCodexModels, selectedModel),
|
||||
[selectedModel, settings.customCodexModels],
|
||||
);
|
||||
const slashModelOptions = useMemo(
|
||||
() =>
|
||||
getSlashModelOptions(settings.customCodexModels, composerTrigger?.query ?? "", selectedModel),
|
||||
[composerTrigger?.query, selectedModel, settings.customCodexModels],
|
||||
);
|
||||
const phase = derivePhase(activeThread?.session ?? null);
|
||||
const isSendBusy = sendPhase !== "idle";
|
||||
const isPreparingWorktree = sendPhase === "preparing-worktree";
|
||||
@@ -907,26 +913,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
];
|
||||
}
|
||||
|
||||
return modelOptions
|
||||
.map(({ slug, name }) => ({
|
||||
slug,
|
||||
name,
|
||||
searchSlug: slug.toLowerCase(),
|
||||
searchName: name.toLowerCase(),
|
||||
}))
|
||||
.filter(({ searchSlug, searchName }) => {
|
||||
const query = composerTrigger.query.trim().toLowerCase();
|
||||
if (!query) return true;
|
||||
return searchSlug.includes(query) || searchName.includes(query);
|
||||
})
|
||||
.map(({ slug, name }) => ({
|
||||
id: `model:${slug}`,
|
||||
type: "model" as const,
|
||||
model: slug,
|
||||
label: name,
|
||||
description: slug,
|
||||
}));
|
||||
}, [composerTrigger, modelOptions, workspaceEntries]);
|
||||
return slashModelOptions.map(({ slug, name }) => ({
|
||||
id: `model:${slug}`,
|
||||
type: "model" as const,
|
||||
model: slug,
|
||||
label: name,
|
||||
description: slug,
|
||||
}));
|
||||
}, [composerTrigger, slashModelOptions, workspaceEntries]);
|
||||
const composerMenuOpen = Boolean(composerTrigger);
|
||||
const activeComposerMenuItem = useMemo(
|
||||
() =>
|
||||
@@ -944,6 +938,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
const keybindings = serverConfigQuery.data?.keybindings ?? EMPTY_KEYBINDINGS;
|
||||
const availableEditors = serverConfigQuery.data?.availableEditors ?? EMPTY_AVAILABLE_EDITORS;
|
||||
const providerStatuses = serverConfigQuery.data?.providers ?? EMPTY_PROVIDER_STATUSES;
|
||||
const activeProvider = activeThread?.session?.provider ?? "codex";
|
||||
const activeProviderStatus = useMemo(
|
||||
() => providerStatuses.find((status) => status.provider === activeProvider) ?? null,
|
||||
[activeProvider, providerStatuses],
|
||||
);
|
||||
const activeProjectCwd = activeProject?.cwd ?? null;
|
||||
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
|
||||
const threadTerminalRuntimeEnv = useMemo(() => {
|
||||
@@ -2320,12 +2320,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
return;
|
||||
}
|
||||
if (item.type === "slash-command") {
|
||||
const applied = applyPromptReplacement(
|
||||
trigger.rangeStart,
|
||||
trigger.rangeEnd,
|
||||
"/model ",
|
||||
{ expectedText: expectedToken },
|
||||
);
|
||||
const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "/model ", {
|
||||
expectedText: expectedToken,
|
||||
});
|
||||
if (applied) {
|
||||
setComposerHighlightedItemId(null);
|
||||
}
|
||||
@@ -2368,18 +2365,27 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
workspaceEntriesQuery.isLoading ||
|
||||
workspaceEntriesQuery.isFetching);
|
||||
|
||||
const onPromptChange = useCallback((nextPrompt: string, nextCursor: number, cursorAdjacentToMention: boolean) => {
|
||||
promptRef.current = nextPrompt;
|
||||
setPrompt(nextPrompt);
|
||||
setComposerCursor(nextCursor);
|
||||
setComposerTrigger(
|
||||
cursorAdjacentToMention
|
||||
? null
|
||||
: detectComposerTrigger(nextPrompt, expandCollapsedComposerCursor(nextPrompt, nextCursor)),
|
||||
);
|
||||
}, [setPrompt]);
|
||||
const onPromptChange = useCallback(
|
||||
(nextPrompt: string, nextCursor: number, cursorAdjacentToMention: boolean) => {
|
||||
promptRef.current = nextPrompt;
|
||||
setPrompt(nextPrompt);
|
||||
setComposerCursor(nextCursor);
|
||||
setComposerTrigger(
|
||||
cursorAdjacentToMention
|
||||
? null
|
||||
: detectComposerTrigger(
|
||||
nextPrompt,
|
||||
expandCollapsedComposerCursor(nextPrompt, nextCursor),
|
||||
),
|
||||
);
|
||||
},
|
||||
[setPrompt],
|
||||
);
|
||||
|
||||
const onComposerCommandKey = (key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab", event: KeyboardEvent) => {
|
||||
const onComposerCommandKey = (
|
||||
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
|
||||
event: KeyboardEvent,
|
||||
) => {
|
||||
const { trigger } = resolveActiveComposerTrigger();
|
||||
const menuIsActive = composerMenuOpenRef.current || trigger !== null;
|
||||
|
||||
@@ -2499,6 +2505,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
</header>
|
||||
|
||||
{/* Error banner */}
|
||||
<ProviderHealthBanner status={activeProviderStatus} />
|
||||
<ThreadErrorBanner error={activeThread.error} />
|
||||
<PendingApprovalsPanel
|
||||
pendingApprovals={pendingApprovals}
|
||||
@@ -2786,7 +2793,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
{isGitRepo && (
|
||||
<BranchToolbar
|
||||
threadId={activeThread.id}
|
||||
envMode={envMode}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
envLocked={envLocked}
|
||||
onComposerFocusRequest={scheduleComposerFocus}
|
||||
@@ -3000,6 +3006,35 @@ const ThreadErrorBanner = memo(function ThreadErrorBanner({ error }: { error: st
|
||||
);
|
||||
});
|
||||
|
||||
const ProviderHealthBanner = memo(function ProviderHealthBanner({
|
||||
status,
|
||||
}: {
|
||||
status: ServerProviderStatus | null;
|
||||
}) {
|
||||
if (!status || status.status === "ready") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const defaultMessage =
|
||||
status.status === "error"
|
||||
? `${status.provider} provider is unavailable.`
|
||||
: `${status.provider} provider has limited availability.`;
|
||||
|
||||
return (
|
||||
<div className="pt-3 mx-auto max-w-3xl">
|
||||
<Alert variant={status.status === "error" ? "error" : "warning"}>
|
||||
<CircleAlertIcon />
|
||||
<AlertTitle>
|
||||
{status.provider === "codex" ? "Codex provider status" : `${status.provider} status`}
|
||||
</AlertTitle>
|
||||
<AlertDescription className="line-clamp-3" title={status.message ?? defaultMessage}>
|
||||
{status.message ?? defaultMessage}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
interface PendingApprovalsPanelProps {
|
||||
pendingApprovals: PendingApproval[];
|
||||
respondingRequestIds: ApprovalRequestId[];
|
||||
|
||||
@@ -737,7 +737,7 @@ describe("when: branch has no upstream configured", () => {
|
||||
});
|
||||
|
||||
describe("requiresDefaultBranchConfirmation", () => {
|
||||
it("requires confirmation only for push actions on default branch", () => {
|
||||
it("requires confirmation for push actions on default branch", () => {
|
||||
assert.isFalse(requiresDefaultBranchConfirmation("commit", true));
|
||||
assert.isTrue(requiresDefaultBranchConfirmation("commit_push", true));
|
||||
assert.isTrue(requiresDefaultBranchConfirmation("commit_push_pr", true));
|
||||
@@ -804,6 +804,17 @@ describe("buildGitActionProgressStages", () => {
|
||||
assert.deepEqual(stages, ["Pushing to origin/feature/test..."]);
|
||||
});
|
||||
|
||||
it("skips commit stages for create-pr flow when push-only is forced", () => {
|
||||
const stages = buildGitActionProgressStages({
|
||||
action: "commit_push_pr",
|
||||
hasCustomCommitMessage: false,
|
||||
hasWorkingTreeChanges: true,
|
||||
forcePushOnly: true,
|
||||
pushTarget: "origin/feature/test",
|
||||
});
|
||||
assert.deepEqual(stages, ["Pushing to origin/feature/test...", "Creating PR..."]);
|
||||
});
|
||||
|
||||
it("includes commit stages for commit+push when working tree is dirty", () => {
|
||||
const stages = buildGitActionProgressStages({
|
||||
action: "commit_push",
|
||||
@@ -823,6 +834,7 @@ describe("summarizeGitResult", () => {
|
||||
it("returns commit-focused toast for commit action", () => {
|
||||
const result = summarizeGitResult({
|
||||
action: "commit",
|
||||
branch: { status: "skipped_not_requested" },
|
||||
commit: {
|
||||
status: "created",
|
||||
commitSha: "0123456789abcdef",
|
||||
@@ -841,6 +853,7 @@ describe("summarizeGitResult", () => {
|
||||
it("returns push-focused toast for push action", () => {
|
||||
const result = summarizeGitResult({
|
||||
action: "commit_push",
|
||||
branch: { status: "skipped_not_requested" },
|
||||
commit: {
|
||||
status: "created",
|
||||
commitSha: "abcdef0123456789",
|
||||
@@ -863,6 +876,7 @@ describe("summarizeGitResult", () => {
|
||||
it("returns PR-focused toast for created PR action", () => {
|
||||
const result = summarizeGitResult({
|
||||
action: "commit_push_pr",
|
||||
branch: { status: "skipped_not_requested" },
|
||||
commit: {
|
||||
status: "created",
|
||||
commitSha: "89abcdef01234567",
|
||||
@@ -888,6 +902,7 @@ describe("summarizeGitResult", () => {
|
||||
it("truncates long description text", () => {
|
||||
const result = summarizeGitResult({
|
||||
action: "commit_push_pr",
|
||||
branch: { status: "skipped_not_requested" },
|
||||
commit: {
|
||||
status: "created",
|
||||
commitSha: "89abcdef01234567",
|
||||
@@ -910,18 +925,31 @@ describe("summarizeGitResult", () => {
|
||||
});
|
||||
|
||||
describe("resolveAutoFeatureBranchName", () => {
|
||||
const day = new Date("2026-03-01T12:00:00.000Z");
|
||||
|
||||
it("returns the base auto feature branch name when available", () => {
|
||||
const branch = resolveAutoFeatureBranchName(["main", "feature/other"], day);
|
||||
assert.equal(branch, "feature/stacked-20260301");
|
||||
it("uses semantic preferred branch names when available", () => {
|
||||
const branch = resolveAutoFeatureBranchName(["main", "feature/other"], "fix toast copy");
|
||||
assert.equal(branch, "feature/fix-toast-copy");
|
||||
});
|
||||
|
||||
it("increments suffix when the base name already exists", () => {
|
||||
it("normalizes preferred names that already include a branch namespace", () => {
|
||||
const branch = resolveAutoFeatureBranchName(["main"], "feature/refine-toolbar-actions");
|
||||
assert.equal(branch, "feature/refine-toolbar-actions");
|
||||
});
|
||||
|
||||
it("increments suffix when the preferred branch name already exists", () => {
|
||||
const branch = resolveAutoFeatureBranchName(
|
||||
["main", "feature/stacked-20260301", "feature/stacked-20260301-2"],
|
||||
day,
|
||||
["main", "feature/fix-toast-copy", "feature/fix-toast-copy-2"],
|
||||
"fix toast copy",
|
||||
);
|
||||
assert.equal(branch, "feature/stacked-20260301-3");
|
||||
assert.equal(branch, "feature/fix-toast-copy-3");
|
||||
});
|
||||
|
||||
it("treats existing branch names as case-insensitive for collision checks", () => {
|
||||
const branch = resolveAutoFeatureBranchName(["Feature/Ticket-1"], "feature/ticket-1");
|
||||
assert.equal(branch, "feature/ticket-1-2");
|
||||
});
|
||||
|
||||
it("falls back to feature/update when no preferred name is provided", () => {
|
||||
const branch = resolveAutoFeatureBranchName(["main"]);
|
||||
assert.equal(branch, "feature/update");
|
||||
});
|
||||
});
|
||||
@@ -35,7 +35,6 @@ export type DefaultBranchConfirmableAction = "commit_push" | "commit_push_pr";
|
||||
|
||||
const SHORT_SHA_LENGTH = 7;
|
||||
const TOAST_DESCRIPTION_MAX = 72;
|
||||
const AUTO_FEATURE_BRANCH_PREFIX = "feature/stacked";
|
||||
|
||||
function shortenSha(sha: string | undefined): string | null {
|
||||
if (!sha) return null;
|
||||
@@ -58,7 +57,9 @@ export function buildGitActionProgressStages(input: {
|
||||
hasWorkingTreeChanges: boolean;
|
||||
forcePushOnly?: boolean;
|
||||
pushTarget?: string;
|
||||
featureBranch?: boolean;
|
||||
}): string[] {
|
||||
const branchStages = input.featureBranch ? ["Preparing feature branch..."] : [];
|
||||
const shouldIncludeCommitStages =
|
||||
!input.forcePushOnly && (input.action === "commit" || input.hasWorkingTreeChanges);
|
||||
const commitStages = !shouldIncludeCommitStages
|
||||
@@ -68,12 +69,12 @@ export function buildGitActionProgressStages(input: {
|
||||
: ["Generating commit message...", "Committing..."];
|
||||
const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing...";
|
||||
if (input.action === "commit") {
|
||||
return commitStages;
|
||||
return [...branchStages, ...commitStages];
|
||||
}
|
||||
if (input.action === "commit_push") {
|
||||
return [...commitStages, pushStage];
|
||||
return [...branchStages, ...commitStages, pushStage];
|
||||
}
|
||||
return [...commitStages, pushStage, "Creating PR..."];
|
||||
return [...branchStages, ...commitStages, pushStage, "Creating PR..."];
|
||||
}
|
||||
|
||||
const withDescription = (title: string, description: string | undefined) =>
|
||||
@@ -321,29 +322,5 @@ export function resolveDefaultBranchActionDialogCopy(input: {
|
||||
};
|
||||
}
|
||||
|
||||
function formatDateForBranch(now: Date): string {
|
||||
const year = now.getUTCFullYear();
|
||||
const month = String(now.getUTCMonth() + 1).padStart(2, "0");
|
||||
const day = String(now.getUTCDate()).padStart(2, "0");
|
||||
return `${year}${month}${day}`;
|
||||
}
|
||||
|
||||
export function resolveAutoFeatureBranchName(
|
||||
existingBranchNames: readonly string[],
|
||||
now = new Date(),
|
||||
): string {
|
||||
const daySlug = formatDateForBranch(now);
|
||||
const base = `${AUTO_FEATURE_BRANCH_PREFIX}-${daySlug}`;
|
||||
const existingNames = new Set(existingBranchNames);
|
||||
|
||||
if (!existingNames.has(base)) {
|
||||
return base;
|
||||
}
|
||||
|
||||
let suffix = 2;
|
||||
while (existingNames.has(`${base}-${suffix}`)) {
|
||||
suffix += 1;
|
||||
}
|
||||
|
||||
return `${base}-${suffix}`;
|
||||
}
|
||||
// Re-export from shared for backwards compatibility in this module's exports
|
||||
export { resolveAutoFeatureBranchName } from "@t3tools/shared/git";
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type GitStatusResult, type GitStackedAction, type ThreadId } from "@t3tools/contracts";
|
||||
import type { GitStackedAction, GitStatusResult, ThreadId } from "@t3tools/contracts";
|
||||
import { useIsMutating, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
type GitQuickAction,
|
||||
type DefaultBranchConfirmableAction,
|
||||
requiresDefaultBranchConfirmation,
|
||||
resolveAutoFeatureBranchName,
|
||||
resolveDefaultBranchActionDialogCopy,
|
||||
resolveQuickAction,
|
||||
summarizeGitResult,
|
||||
@@ -34,7 +33,6 @@ import { Textarea } from "~/components/ui/textarea";
|
||||
import { toastManager } from "~/components/ui/toast";
|
||||
import {
|
||||
gitBranchesQueryOptions,
|
||||
gitCreateBranchAndCheckoutMutationOptions,
|
||||
gitInitMutationOptions,
|
||||
gitMutationKeys,
|
||||
gitPullMutationOptions,
|
||||
@@ -172,18 +170,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
const runImmediateGitActionMutation = useMutation(
|
||||
gitRunStackedActionMutationOptions({ cwd: gitCwd, queryClient }),
|
||||
);
|
||||
const createBranchAndCheckoutMutation = useMutation(
|
||||
gitCreateBranchAndCheckoutMutationOptions({ cwd: gitCwd, queryClient }),
|
||||
);
|
||||
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
|
||||
|
||||
const isRunStackedActionRunning =
|
||||
useIsMutating({ mutationKey: gitMutationKeys.runStackedAction(gitCwd) }) > 0;
|
||||
const isCreateBranchAndCheckoutRunning =
|
||||
useIsMutating({ mutationKey: gitMutationKeys.createBranchAndCheckout(gitCwd) }) > 0;
|
||||
const isPullRunning = useIsMutating({ mutationKey: gitMutationKeys.pull(gitCwd) }) > 0;
|
||||
const isGitActionRunning =
|
||||
isRunStackedActionRunning || isCreateBranchAndCheckoutRunning || isPullRunning;
|
||||
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
|
||||
const isDefaultBranch = useMemo(() => {
|
||||
const branchName = gitStatusForActions?.branch;
|
||||
if (!branchName) return false;
|
||||
@@ -247,6 +239,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
onConfirmed,
|
||||
skipDefaultBranchPrompt = false,
|
||||
statusOverride,
|
||||
featureBranch = false,
|
||||
isDefaultBranchOverride,
|
||||
progressToastId,
|
||||
}: {
|
||||
@@ -256,12 +249,13 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
onConfirmed?: () => void;
|
||||
skipDefaultBranchPrompt?: boolean;
|
||||
statusOverride?: GitStatusResult | null;
|
||||
featureBranch?: boolean;
|
||||
isDefaultBranchOverride?: boolean;
|
||||
progressToastId?: GitActionToastId;
|
||||
}) => {
|
||||
const actionStatus = statusOverride ?? gitStatusForActions;
|
||||
const actionIsDefaultBranch = isDefaultBranchOverride ?? isDefaultBranch;
|
||||
const actionBranch = actionStatus?.branch ?? null;
|
||||
const actionIsDefaultBranch = isDefaultBranchOverride ?? (featureBranch ? false : isDefaultBranch);
|
||||
const includesCommit =
|
||||
!forcePushOnlyProgress && (action === "commit" || !!actionStatus?.hasWorkingTreeChanges);
|
||||
if (
|
||||
@@ -284,12 +278,13 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
}
|
||||
onConfirmed?.();
|
||||
|
||||
const pushTarget = actionBranch ? `origin/${actionBranch}` : undefined;
|
||||
const pushTarget = !featureBranch && actionBranch ? `origin/${actionBranch}` : undefined;
|
||||
const progressStages = buildGitActionProgressStages({
|
||||
action,
|
||||
hasCustomCommitMessage: !!commitMessage?.trim(),
|
||||
hasWorkingTreeChanges: !!actionStatus?.hasWorkingTreeChanges,
|
||||
forcePushOnly: forcePushOnlyProgress,
|
||||
featureBranch,
|
||||
...(pushTarget ? { pushTarget } : {}),
|
||||
});
|
||||
const resolvedProgressToastId =
|
||||
@@ -328,6 +323,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
const promise = runImmediateGitActionMutation.mutateAsync({
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(featureBranch ? { featureBranch } : {}),
|
||||
});
|
||||
|
||||
try {
|
||||
@@ -341,7 +337,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
const shouldOfferOpenPrCta =
|
||||
(action === "commit_push" || action === "commit_push_pr") &&
|
||||
!!prUrl &&
|
||||
!actionIsDefaultBranch;
|
||||
(!actionIsDefaultBranch ||
|
||||
result.pr.status === "created" ||
|
||||
result.pr.status === "opened_existing");
|
||||
const shouldOfferCreatePrCta =
|
||||
action === "commit_push" &&
|
||||
!prUrl &&
|
||||
@@ -395,6 +393,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
closeResultToast();
|
||||
void runGitActionWithToast({
|
||||
action: "commit_push_pr",
|
||||
forcePushOnlyProgress: true,
|
||||
statusOverride: actionStatus,
|
||||
isDefaultBranchOverride: actionIsDefaultBranch,
|
||||
});
|
||||
@@ -443,54 +442,13 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
forcePushOnlyProgress?: boolean;
|
||||
onConfirmed?: () => void;
|
||||
}) => {
|
||||
const branchName = resolveAutoFeatureBranchName(
|
||||
branchList?.branches.map((branch) => branch.name) ?? [],
|
||||
);
|
||||
|
||||
const checkoutPromise = createBranchAndCheckoutMutation.mutateAsync(branchName);
|
||||
const checkoutToastId = toastManager.add({
|
||||
type: "loading",
|
||||
title: `Creating ${branchName}...`,
|
||||
timeout: 0,
|
||||
data: threadToastData,
|
||||
void runGitActionWithToast({
|
||||
...actionParams,
|
||||
featureBranch: true,
|
||||
skipDefaultBranchPrompt: true,
|
||||
});
|
||||
|
||||
void checkoutPromise
|
||||
.then(() => {
|
||||
const statusOverride = gitStatusForActions
|
||||
? {
|
||||
...gitStatusForActions,
|
||||
branch: branchName,
|
||||
pr: null,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
}
|
||||
: null;
|
||||
return runGitActionWithToast({
|
||||
...actionParams,
|
||||
skipDefaultBranchPrompt: true,
|
||||
statusOverride,
|
||||
isDefaultBranchOverride: false,
|
||||
progressToastId: checkoutToastId,
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
toastManager.update(checkoutToastId, {
|
||||
type: "error",
|
||||
title: "Failed to checkout feature branch",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
data: threadToastData,
|
||||
});
|
||||
});
|
||||
},
|
||||
[
|
||||
branchList?.branches,
|
||||
createBranchAndCheckoutMutation,
|
||||
gitStatusForActions,
|
||||
runGitActionWithToast,
|
||||
threadToastData,
|
||||
],
|
||||
[runGitActionWithToast],
|
||||
);
|
||||
|
||||
const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => {
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
import { ChevronRightIcon, FolderIcon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
|
||||
import {
|
||||
ChevronRightIcon,
|
||||
FolderIcon,
|
||||
GitPullRequestIcon,
|
||||
RocketIcon,
|
||||
TerminalIcon,
|
||||
} from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
type DesktopUpdateState,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type GitStatusResult,
|
||||
@@ -23,6 +30,15 @@ import { readNativeApi } from "../nativeApi";
|
||||
import { type DraftThreadEnvMode, useComposerDraftStore } from "../composerDraftStore";
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import {
|
||||
getDesktopUpdateActionError,
|
||||
getDesktopUpdateButtonTooltip,
|
||||
isDesktopUpdateButtonDisabled,
|
||||
resolveDesktopUpdateButtonAction,
|
||||
shouldHighlightDesktopUpdateError,
|
||||
shouldShowDesktopUpdateButton,
|
||||
shouldToastDesktopUpdateActionResult,
|
||||
} from "./desktopUpdate.logic";
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import {
|
||||
@@ -270,6 +286,7 @@ export default function Sidebar() {
|
||||
const [renamingTitle, setRenamingTitle] = useState("");
|
||||
const renamingCommittedRef = useRef(false);
|
||||
const renamingInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const [desktopUpdateState, setDesktopUpdateState] = useState<DesktopUpdateState | null>(null);
|
||||
const pendingApprovalByThreadId = useMemo(() => {
|
||||
const map = new Map<ThreadId, boolean>();
|
||||
for (const thread of threads) {
|
||||
@@ -766,8 +783,7 @@ export default function Sidebar() {
|
||||
}
|
||||
|
||||
if (!isChatNewShortcut(event, keybindings)) return;
|
||||
const projectId =
|
||||
activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
|
||||
const projectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
|
||||
if (!projectId) return;
|
||||
event.preventDefault();
|
||||
void handleNewThread(projectId, {
|
||||
@@ -783,6 +799,39 @@ export default function Sidebar() {
|
||||
};
|
||||
}, [getDraftThread, handleNewThread, keybindings, projects, routeThreadId, threads]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isElectron) return;
|
||||
const bridge = window.desktopBridge;
|
||||
if (
|
||||
!bridge ||
|
||||
typeof bridge.getUpdateState !== "function" ||
|
||||
typeof bridge.onUpdateState !== "function"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
let disposed = false;
|
||||
let receivedSubscriptionUpdate = false;
|
||||
const unsubscribe = bridge.onUpdateState((nextState) => {
|
||||
if (disposed) return;
|
||||
receivedSubscriptionUpdate = true;
|
||||
setDesktopUpdateState(nextState);
|
||||
});
|
||||
|
||||
void bridge
|
||||
.getUpdateState()
|
||||
.then((nextState) => {
|
||||
if (disposed || receivedSubscriptionUpdate) return;
|
||||
setDesktopUpdateState(nextState);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
unsubscribe();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const onCreateThreadClick = () => {
|
||||
if (projects.length === 0) {
|
||||
setAddingProject(true);
|
||||
@@ -792,6 +841,86 @@ export default function Sidebar() {
|
||||
if (firstProject) void handleNewThread(firstProject.id);
|
||||
};
|
||||
|
||||
const showDesktopUpdateButton = isElectron && shouldShowDesktopUpdateButton(desktopUpdateState);
|
||||
|
||||
const desktopUpdateTooltip = desktopUpdateState
|
||||
? getDesktopUpdateButtonTooltip(desktopUpdateState)
|
||||
: "Update available";
|
||||
|
||||
const desktopUpdateButtonDisabled = isDesktopUpdateButtonDisabled(desktopUpdateState);
|
||||
const desktopUpdateButtonAction = desktopUpdateState
|
||||
? resolveDesktopUpdateButtonAction(desktopUpdateState)
|
||||
: "none";
|
||||
const desktopUpdateButtonInteractivityClasses = desktopUpdateButtonDisabled
|
||||
? "cursor-not-allowed opacity-60"
|
||||
: "hover:bg-accent hover:text-foreground";
|
||||
const desktopUpdateButtonClasses =
|
||||
desktopUpdateState?.status === "downloaded"
|
||||
? "text-emerald-500"
|
||||
: desktopUpdateState?.status === "downloading"
|
||||
? "text-sky-400"
|
||||
: shouldHighlightDesktopUpdateError(desktopUpdateState)
|
||||
? "text-rose-500 animate-pulse"
|
||||
: "text-amber-500 animate-pulse";
|
||||
|
||||
const handleDesktopUpdateButtonClick = useCallback(() => {
|
||||
const bridge = window.desktopBridge;
|
||||
if (!bridge || !desktopUpdateState) return;
|
||||
if (desktopUpdateButtonDisabled || desktopUpdateButtonAction === "none") return;
|
||||
|
||||
if (desktopUpdateButtonAction === "download") {
|
||||
void bridge
|
||||
.downloadUpdate()
|
||||
.then((result) => {
|
||||
if (result.completed) {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Update downloaded",
|
||||
description: "Restart the app from the update button to install it.",
|
||||
});
|
||||
}
|
||||
if (!shouldToastDesktopUpdateActionResult(result)) return;
|
||||
const actionError = getDesktopUpdateActionError(result);
|
||||
if (!actionError) return;
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not download update",
|
||||
description: actionError,
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not start update download",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred.",
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (desktopUpdateButtonAction === "install") {
|
||||
void bridge
|
||||
.installUpdate()
|
||||
.then((result) => {
|
||||
if (!shouldToastDesktopUpdateActionResult(result)) return;
|
||||
const actionError = getDesktopUpdateActionError(result);
|
||||
if (!actionError) return;
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not install update",
|
||||
description: actionError,
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not install update",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred.",
|
||||
});
|
||||
});
|
||||
}
|
||||
}, [desktopUpdateButtonAction, desktopUpdateButtonDisabled, desktopUpdateState]);
|
||||
|
||||
const wordmark = (
|
||||
<div className="flex items-center gap-2">
|
||||
<SidebarTrigger className="shrink-0 md:hidden" />
|
||||
@@ -824,6 +953,25 @@ export default function Sidebar() {
|
||||
<>
|
||||
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[82px]">
|
||||
{wordmark}
|
||||
{showDesktopUpdateButton && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
aria-label={desktopUpdateTooltip}
|
||||
aria-disabled={desktopUpdateButtonDisabled || undefined}
|
||||
disabled={desktopUpdateButtonDisabled}
|
||||
className={`inline-flex size-7 ml-auto mt-2 items-center justify-center rounded-md text-muted-foreground transition-colors ${desktopUpdateButtonInteractivityClasses} ${desktopUpdateButtonClasses}`}
|
||||
onClick={handleDesktopUpdateButtonClick}
|
||||
>
|
||||
<RocketIcon className="size-3.5" />
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="bottom">{desktopUpdateTooltip}</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
</SidebarHeader>
|
||||
<div className="px-4 py-2">{newThreadButton}</div>
|
||||
</>
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
getDesktopUpdateActionError,
|
||||
getDesktopUpdateButtonTooltip,
|
||||
isDesktopUpdateButtonDisabled,
|
||||
resolveDesktopUpdateButtonAction,
|
||||
shouldHighlightDesktopUpdateError,
|
||||
shouldShowDesktopUpdateButton,
|
||||
shouldToastDesktopUpdateActionResult,
|
||||
} from "./desktopUpdate.logic";
|
||||
|
||||
const baseState: DesktopUpdateState = {
|
||||
enabled: true,
|
||||
status: "idle",
|
||||
currentVersion: "1.0.0",
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
|
||||
describe("desktop update button state", () => {
|
||||
it("shows a download action when an update is available", () => {
|
||||
const state: DesktopUpdateState = { ...baseState, status: "available", availableVersion: "1.1.0" };
|
||||
expect(shouldShowDesktopUpdateButton(state)).toBe(true);
|
||||
expect(resolveDesktopUpdateButtonAction(state)).toBe("download");
|
||||
});
|
||||
|
||||
it("keeps retry action available after a download error", () => {
|
||||
const state: DesktopUpdateState = {
|
||||
...baseState,
|
||||
status: "error",
|
||||
availableVersion: "1.1.0",
|
||||
message: "network timeout",
|
||||
errorContext: "download",
|
||||
canRetry: true,
|
||||
};
|
||||
expect(shouldShowDesktopUpdateButton(state)).toBe(true);
|
||||
expect(resolveDesktopUpdateButtonAction(state)).toBe("download");
|
||||
expect(getDesktopUpdateButtonTooltip(state)).toContain("Click to retry");
|
||||
});
|
||||
|
||||
it("keeps install action available after an install error", () => {
|
||||
const state: DesktopUpdateState = {
|
||||
...baseState,
|
||||
status: "error",
|
||||
downloadedVersion: "1.1.0",
|
||||
availableVersion: "1.1.0",
|
||||
message: "shutdown timeout",
|
||||
errorContext: "install",
|
||||
canRetry: true,
|
||||
};
|
||||
expect(shouldShowDesktopUpdateButton(state)).toBe(true);
|
||||
expect(resolveDesktopUpdateButtonAction(state)).toBe("install");
|
||||
expect(getDesktopUpdateButtonTooltip(state)).toContain("Click to retry");
|
||||
});
|
||||
|
||||
it("hides the button for non-actionable check errors", () => {
|
||||
const state: DesktopUpdateState = {
|
||||
...baseState,
|
||||
status: "error",
|
||||
message: "network unavailable",
|
||||
errorContext: "check",
|
||||
canRetry: true,
|
||||
};
|
||||
expect(shouldShowDesktopUpdateButton(state)).toBe(false);
|
||||
expect(resolveDesktopUpdateButtonAction(state)).toBe("none");
|
||||
});
|
||||
|
||||
it("disables the button while downloading", () => {
|
||||
const state: DesktopUpdateState = {
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
downloadPercent: 42.5,
|
||||
};
|
||||
expect(shouldShowDesktopUpdateButton(state)).toBe(true);
|
||||
expect(isDesktopUpdateButtonDisabled(state)).toBe(true);
|
||||
expect(getDesktopUpdateButtonTooltip(state)).toContain("42%");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getDesktopUpdateActionError", () => {
|
||||
it("returns user-visible message for accepted failed attempts", () => {
|
||||
const result: DesktopUpdateActionResult = {
|
||||
accepted: true,
|
||||
completed: false,
|
||||
state: {
|
||||
...baseState,
|
||||
status: "available",
|
||||
availableVersion: "1.1.0",
|
||||
message: "checksum mismatch",
|
||||
errorContext: "download",
|
||||
canRetry: true,
|
||||
},
|
||||
};
|
||||
expect(getDesktopUpdateActionError(result)).toBe("checksum mismatch");
|
||||
});
|
||||
|
||||
it("ignores messages for non-accepted attempts", () => {
|
||||
const result: DesktopUpdateActionResult = {
|
||||
accepted: false,
|
||||
completed: false,
|
||||
state: {
|
||||
...baseState,
|
||||
status: "error",
|
||||
message: "background failure",
|
||||
errorContext: "check",
|
||||
canRetry: false,
|
||||
},
|
||||
};
|
||||
expect(getDesktopUpdateActionError(result)).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores messages for successful attempts", () => {
|
||||
const result: DesktopUpdateActionResult = {
|
||||
accepted: true,
|
||||
completed: true,
|
||||
state: {
|
||||
...baseState,
|
||||
status: "downloaded",
|
||||
downloadedVersion: "1.1.0",
|
||||
availableVersion: "1.1.0",
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: true,
|
||||
},
|
||||
};
|
||||
expect(getDesktopUpdateActionError(result)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("desktop update UI helpers", () => {
|
||||
it("toasts only for accepted incomplete actions", () => {
|
||||
expect(
|
||||
shouldToastDesktopUpdateActionResult({
|
||||
accepted: true,
|
||||
completed: false,
|
||||
state: baseState,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldToastDesktopUpdateActionResult({
|
||||
accepted: true,
|
||||
completed: true,
|
||||
state: baseState,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("highlights only actionable updater errors", () => {
|
||||
expect(
|
||||
shouldHighlightDesktopUpdateError({
|
||||
...baseState,
|
||||
status: "error",
|
||||
errorContext: "download",
|
||||
canRetry: true,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldHighlightDesktopUpdateError({
|
||||
...baseState,
|
||||
status: "error",
|
||||
errorContext: "check",
|
||||
canRetry: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
export type DesktopUpdateButtonAction = "download" | "install" | "none";
|
||||
|
||||
export function resolveDesktopUpdateButtonAction(
|
||||
state: DesktopUpdateState,
|
||||
): DesktopUpdateButtonAction {
|
||||
if (state.status === "available") {
|
||||
return "download";
|
||||
}
|
||||
if (state.status === "downloaded") {
|
||||
return "install";
|
||||
}
|
||||
if (state.status === "error") {
|
||||
if (state.errorContext === "install" && state.downloadedVersion) {
|
||||
return "install";
|
||||
}
|
||||
if (state.errorContext === "download" && state.availableVersion) {
|
||||
return "download";
|
||||
}
|
||||
}
|
||||
return "none";
|
||||
}
|
||||
|
||||
export function shouldShowDesktopUpdateButton(state: DesktopUpdateState | null): boolean {
|
||||
if (!state || !state.enabled) {
|
||||
return false;
|
||||
}
|
||||
if (state.status === "downloading") {
|
||||
return true;
|
||||
}
|
||||
return resolveDesktopUpdateButtonAction(state) !== "none";
|
||||
}
|
||||
|
||||
export function isDesktopUpdateButtonDisabled(state: DesktopUpdateState | null): boolean {
|
||||
return state?.status === "downloading";
|
||||
}
|
||||
|
||||
export function getDesktopUpdateButtonTooltip(state: DesktopUpdateState): string {
|
||||
if (state.status === "available") {
|
||||
return `Update ${state.availableVersion ?? "available"} ready to download`;
|
||||
}
|
||||
if (state.status === "downloading") {
|
||||
const progress =
|
||||
typeof state.downloadPercent === "number" ? ` (${Math.floor(state.downloadPercent)}%)` : "";
|
||||
return `Downloading update${progress}`;
|
||||
}
|
||||
if (state.status === "downloaded") {
|
||||
return `Update ${state.downloadedVersion ?? state.availableVersion ?? "ready"} downloaded. Click to restart and install.`;
|
||||
}
|
||||
if (state.status === "error") {
|
||||
if (state.errorContext === "download" && state.availableVersion) {
|
||||
return `Download failed for ${state.availableVersion}. Click to retry.`;
|
||||
}
|
||||
if (state.errorContext === "install" && state.downloadedVersion) {
|
||||
return `Install failed for ${state.downloadedVersion}. Click to retry.`;
|
||||
}
|
||||
return state.message ?? "Update failed";
|
||||
}
|
||||
return "Update available";
|
||||
}
|
||||
|
||||
export function getDesktopUpdateActionError(result: DesktopUpdateActionResult): string | null {
|
||||
if (!result.accepted || result.completed) return null;
|
||||
if (typeof result.state.message !== "string") return null;
|
||||
const message = result.state.message.trim();
|
||||
return message.length > 0 ? message : null;
|
||||
}
|
||||
|
||||
export function shouldToastDesktopUpdateActionResult(result: DesktopUpdateActionResult): boolean {
|
||||
return result.accepted && !result.completed;
|
||||
}
|
||||
|
||||
export function shouldHighlightDesktopUpdateError(state: DesktopUpdateState | null): boolean {
|
||||
if (!state || state.status !== "error") return false;
|
||||
return state.errorContext === "download" || state.errorContext === "install";
|
||||
}
|
||||
@@ -16,8 +16,6 @@ export const gitQueryKeys = {
|
||||
export const gitMutationKeys = {
|
||||
init: (cwd: string | null) => ["git", "mutation", "init", cwd] as const,
|
||||
checkout: (cwd: string | null) => ["git", "mutation", "checkout", cwd] as const,
|
||||
createBranchAndCheckout: (cwd: string | null) =>
|
||||
["git", "mutation", "create-branch-and-checkout", cwd] as const,
|
||||
runStackedAction: (cwd: string | null) => ["git", "mutation", "run-stacked-action", cwd] as const,
|
||||
pull: (cwd: string | null) => ["git", "mutation", "pull", cwd] as const,
|
||||
};
|
||||
@@ -89,24 +87,6 @@ export function gitCheckoutMutationOptions(input: {
|
||||
});
|
||||
}
|
||||
|
||||
export function gitCreateBranchAndCheckoutMutationOptions(input: {
|
||||
cwd: string | null;
|
||||
queryClient: QueryClient;
|
||||
}) {
|
||||
return mutationOptions({
|
||||
mutationKey: gitMutationKeys.createBranchAndCheckout(input.cwd),
|
||||
mutationFn: async (branch: string) => {
|
||||
const api = ensureNativeApi();
|
||||
if (!input.cwd) throw new Error("Git branch creation is unavailable.");
|
||||
await api.git.createBranch({ cwd: input.cwd, branch });
|
||||
return api.git.checkout({ cwd: input.cwd, branch });
|
||||
},
|
||||
onSuccess: async () => {
|
||||
await invalidateGitQueries(input.queryClient);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function gitRunStackedActionMutationOptions(input: {
|
||||
cwd: string | null;
|
||||
queryClient: QueryClient;
|
||||
@@ -116,9 +96,11 @@ export function gitRunStackedActionMutationOptions(input: {
|
||||
mutationFn: async ({
|
||||
action,
|
||||
commitMessage,
|
||||
featureBranch,
|
||||
}: {
|
||||
action: GitStackedAction;
|
||||
commitMessage?: string;
|
||||
featureBranch?: boolean;
|
||||
}) => {
|
||||
const api = ensureNativeApi();
|
||||
if (!input.cwd) throw new Error("Git action is unavailable.");
|
||||
@@ -126,6 +108,7 @@ export function gitRunStackedActionMutationOptions(input: {
|
||||
cwd: input.cwd,
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(featureBranch ? { featureBranch } : {}),
|
||||
});
|
||||
},
|
||||
onSettled: async () => {
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
WS_CHANNELS,
|
||||
type ServerProviderStatus,
|
||||
} from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
@@ -62,6 +63,16 @@ function getWindowForTest(): Window & typeof globalThis & { desktopBridge?: unkn
|
||||
return testGlobal.window;
|
||||
}
|
||||
|
||||
const defaultProviders: ReadonlyArray<ServerProviderStatus> = [
|
||||
{
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
available: true,
|
||||
authStatus: "authenticated",
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
requestMock.mockReset();
|
||||
@@ -162,6 +173,7 @@ describe("wsNativeApi", () => {
|
||||
message: "Entry at index 1 is invalid.",
|
||||
},
|
||||
],
|
||||
providers: defaultProviders,
|
||||
} as const;
|
||||
emitPush(WS_CHANNELS.serverConfigUpdated, payload);
|
||||
|
||||
@@ -185,14 +197,17 @@ describe("wsNativeApi", () => {
|
||||
|
||||
emitPush(WS_CHANNELS.serverConfigUpdated, {
|
||||
issues: [{ kind: "keybindings.invalid-entry", message: "missing index" }],
|
||||
providers: defaultProviders,
|
||||
});
|
||||
emitPush(WS_CHANNELS.serverConfigUpdated, {
|
||||
issues: [{ kind: "keybindings.malformed-config", message: "bad json" }],
|
||||
providers: defaultProviders,
|
||||
});
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
expect(listener).toHaveBeenCalledWith({
|
||||
issues: [{ kind: "keybindings.malformed-config", message: "bad json" }],
|
||||
providers: defaultProviders,
|
||||
});
|
||||
expect(warnSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
@@ -376,5 +391,4 @@ describe("wsNativeApi", () => {
|
||||
{ x: 20, y: 30 },
|
||||
);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -5,35 +5,34 @@
|
||||
"": {
|
||||
"name": "@t3tools/monorepo",
|
||||
"devDependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@types/node": "^24.10.13",
|
||||
"effect": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"oxfmt": "^0.35.0",
|
||||
"oxlint": "^1.50.0",
|
||||
"turbo": "^2.3.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0",
|
||||
"vitest": "catalog:",
|
||||
},
|
||||
},
|
||||
"apps/desktop": {
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
"electron": "40.6.0",
|
||||
"electron-updater": "^6.6.2",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@types/node": "^24.10.13",
|
||||
"electronmon": "^2.0.2",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@types/node": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
"wait-on": "^8.0.2",
|
||||
},
|
||||
},
|
||||
"apps/server": {
|
||||
"name": "t3",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"bin": {
|
||||
"t3": "./dist/index.mjs",
|
||||
},
|
||||
@@ -47,26 +46,28 @@
|
||||
"ws": "^8.18.0",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "0.75.1",
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/bun": "^1.3.9",
|
||||
"@types/node": "^24.10.13",
|
||||
"@types/bun": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"@types/ws": "^8.5.13",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
},
|
||||
},
|
||||
"apps/web": {
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
"@lexical/react": "^0.41.0",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
"@tanstack/react-router": "^1.160.2",
|
||||
@@ -93,21 +94,53 @@
|
||||
"@vitejs/plugin-react": "^5.1.4",
|
||||
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "^5.7.3",
|
||||
"typescript": "catalog:",
|
||||
"vite": "^8.0.0-beta.12",
|
||||
"vitest": "catalog:",
|
||||
},
|
||||
},
|
||||
"packages/contracts": {
|
||||
"name": "@t3tools/contracts",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "0.75.1",
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
},
|
||||
},
|
||||
"packages/shared": {
|
||||
"name": "@t3tools/shared",
|
||||
"version": "0.0.0-alpha.1",
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
},
|
||||
},
|
||||
"scripts": {
|
||||
"name": "@t3tools/scripts",
|
||||
"dependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"effect": "catalog:",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"@types/bun": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -116,7 +149,12 @@
|
||||
"@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b",
|
||||
"@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@8881a9b",
|
||||
"@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@8881a9b",
|
||||
"@types/bun": "^1.3.9",
|
||||
"@types/node": "^24.10.13",
|
||||
"effect": "https://pkg.pr.new/Effect-TS/effect-smol/effect@8881a9b",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0",
|
||||
},
|
||||
"packages": {
|
||||
"@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.28.5", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw=="],
|
||||
@@ -537,6 +575,10 @@
|
||||
|
||||
"@t3tools/desktop": ["@t3tools/desktop@workspace:apps/desktop"],
|
||||
|
||||
"@t3tools/scripts": ["@t3tools/scripts@workspace:scripts"],
|
||||
|
||||
"@t3tools/shared": ["@t3tools/shared@workspace:packages/shared"],
|
||||
|
||||
"@t3tools/web": ["@t3tools/web@workspace:apps/web"],
|
||||
|
||||
"@tailwindcss/node": ["@tailwindcss/[email protected]", "", { "dependencies": { "@jridgewell/remapping": "^2.3.4", "enhanced-resolve": "^5.18.3", "jiti": "^2.6.1", "lightningcss": "1.30.2", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.1.18" } }, "sha512-DoR7U1P7iYhw16qJ49fgXUlry1t4CpXeErJHnQ44JgTSKMaZUdf17cfn5mHchfJ4KRBZRFA/Coo+MUF5+gOaCQ=="],
|
||||
@@ -685,6 +727,8 @@
|
||||
|
||||
"anymatch": ["[email protected]", "", { "dependencies": { "normalize-path": "^3.0.0", "picomatch": "^2.0.4" } }, "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw=="],
|
||||
|
||||
"argparse": ["[email protected]", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],
|
||||
|
||||
"assertion-error": ["[email protected]", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="],
|
||||
|
||||
"ast-kit": ["[email protected]", "", { "dependencies": { "@babel/parser": "^8.0.0-beta.4", "estree-walker": "^3.0.3", "pathe": "^2.0.3" } }, "sha512-trmleAnZ2PxN/loHWVhhx1qeOHSRXq4TDsBBxq3GqeJitfk3+jTQ+v/C1km/KYq9M7wKqCewMh+/NAvVH7m+bw=="],
|
||||
@@ -715,6 +759,8 @@
|
||||
|
||||
"buffer-crc32": ["[email protected]", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
|
||||
|
||||
"builder-util-runtime": ["[email protected]", "", { "dependencies": { "debug": "^4.3.4", "sax": "^1.2.4" } }, "sha512-qt41tMfgHTllhResqM5DcnHyDIWNgzHvuY2jDcYP9iaGpkWxTUzV6GQjDeLnlR1/DtdlcsWQbA7sByMpmJFTLQ=="],
|
||||
|
||||
"bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-+UBWWOakIP4Tswh0Bt0QD0alpTY8cb5hvgiYeWCMet9YukHbzuruIEeXC2D7nMJPB12kbh8C7XJykSexEqGKJg=="],
|
||||
|
||||
"bundle-name": ["[email protected]", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="],
|
||||
@@ -733,8 +779,6 @@
|
||||
|
||||
"chai": ["[email protected]", "", {}, "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg=="],
|
||||
|
||||
"chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg=="],
|
||||
|
||||
"character-entities": ["[email protected]", "", {}, "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ=="],
|
||||
|
||||
"character-entities-html4": ["[email protected]", "", {}, "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA=="],
|
||||
@@ -817,7 +861,7 @@
|
||||
|
||||
"electron-to-chromium": ["[email protected]", "", {}, "sha512-9tfDXhJ4RKFNerfjdCcZfufu49vg620741MNs26a9+bhLThdB+plgMeou98CAaHu/WATj2iHOOHTp1hWtABj2A=="],
|
||||
|
||||
"electronmon": ["electron[email protected]", "", { "dependencies": { "chalk": "^3.0.0", "import-from": "^3.0.0", "runtime-required": "^1.1.0", "watchboy": "^0.4.3" }, "bin": { "electronmon": "bin/cli.js" } }, "sha512-u6eDrvUbqa+wsnMrhG2vHmo5neL1owLg2e5i1avGWcOb4rHsUf9lSfbs0FvfPsBNpLxxlPO98nrMhAGV+zw/fQ=="],
|
||||
"electron-updater": ["electron[email protected]", "", { "dependencies": { "builder-util-runtime": "9.5.1", "fs-extra": "^10.1.0", "js-yaml": "^4.1.0", "lazy-val": "^1.0.5", "lodash.escaperegexp": "^4.1.2", "lodash.isequal": "^4.5.0", "semver": "~7.7.3", "tiny-typed-emitter": "^2.1.0" } }, "sha512-Z6sgw3jgbikWKXei1ENdqFOxBP0WlXg3TtKfz0rgw2vIZFJUyI4pD7ZN7jrkm7EoMK+tcm/qTnPUdqfZukBlBQ=="],
|
||||
|
||||
"emoji-regex": ["[email protected]", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
|
||||
|
||||
@@ -873,7 +917,7 @@
|
||||
|
||||
"form-data": ["[email protected]", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.2", "mime-types": "^2.1.12" } }, "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w=="],
|
||||
|
||||
"fs-extra": ["fs-extra@8.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="],
|
||||
"fs-extra": ["fs-extra@10.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ=="],
|
||||
|
||||
"fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
@@ -905,8 +949,6 @@
|
||||
|
||||
"graphql": ["[email protected]", "", {}, "sha512-DKKrynuQRne0PNpEbzuEdHlYOMksHSUI8Zc9Unei5gTsMNA2/vMpoMz/yKba50pejK56qj98qM0SjYxAKi13gQ=="],
|
||||
|
||||
"has-flag": ["[email protected]", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],
|
||||
|
||||
"has-property-descriptors": ["[email protected]", "", { "dependencies": { "es-define-property": "^1.0.0" } }, "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg=="],
|
||||
|
||||
"has-symbols": ["[email protected]", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="],
|
||||
@@ -933,8 +975,6 @@
|
||||
|
||||
"http2-wrapper": ["[email protected]", "", { "dependencies": { "quick-lru": "^5.1.1", "resolve-alpn": "^1.0.0" } }, "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg=="],
|
||||
|
||||
"import-from": ["[email protected]", "", { "dependencies": { "resolve-from": "^5.0.0" } }, "sha512-CiuXOFFSzkU5x/CR0+z7T91Iht4CXgfCxVOFRhh2Zyhg5wOpWvvDLQUsWl+gcN+QscYBjez8hDCt85O7RLDttQ=="],
|
||||
|
||||
"import-without-cache": ["[email protected]", "", {}, "sha512-B6Lc2s6yApwnD2/pMzFh/d5AVjdsDXjgkeJ766FmFuJELIGHNycKRj+l3A39yZPM4CchqNCB4RITEAYB1KUM6A=="],
|
||||
|
||||
"ini": ["[email protected]", "", {}, "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ=="],
|
||||
@@ -981,6 +1021,8 @@
|
||||
|
||||
"js-tokens": ["[email protected]", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
|
||||
|
||||
"js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="],
|
||||
|
||||
"jsesc": ["[email protected]", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="],
|
||||
|
||||
"json-buffer": ["[email protected]", "", {}, "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ=="],
|
||||
@@ -989,12 +1031,14 @@
|
||||
|
||||
"json5": ["[email protected]", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="],
|
||||
|
||||
"jsonfile": ["jsonfile@4.0.0", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="],
|
||||
"jsonfile": ["jsonfile@6.2.0", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg=="],
|
||||
|
||||
"keyv": ["[email protected]", "", { "dependencies": { "json-buffer": "3.0.1" } }, "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw=="],
|
||||
|
||||
"kubernetes-types": ["[email protected]", "", {}, "sha512-Dew1okvhM/SQcIa2rcgujNndZwU8VnSapDgdxlYoB84ZlpAD43U6KLAFqYo17ykSFGHNPrg0qry0bP+GJd9v7Q=="],
|
||||
|
||||
"lazy-val": ["[email protected]", "", {}, "sha512-0/BnGCCfyUMkBpeDgWihanIAF9JmZhHBgUhEqzvf+adhNGLoP6TaiI5oF8oyb3I45P+PcnrqihSf01M0l0G5+Q=="],
|
||||
|
||||
"lexical": ["[email protected]", "", {}, "sha512-pNIm5+n+hVnJHB9gYPDYsIO5Y59dNaDU9rJmPPsfqQhP2ojKFnUoPbcRnrI9FJLXB14sSumcY8LUw7Sq70TZqA=="],
|
||||
|
||||
"lib0": ["[email protected]", "", { "dependencies": { "isomorphic.js": "^0.2.4" }, "bin": { "0serve": "bin/0serve.js", "0gentesthtml": "bin/gentesthtml.js", "0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js" } }, "sha512-DeXj9X5xDCjgKLU/7RR+/HQEVzuuEUiwldwOGsHK/sfAfELGWEyTcf0x+uOvCvK3O2zPmZePXWL85vtia6GyZw=="],
|
||||
@@ -1027,10 +1071,12 @@
|
||||
|
||||
"lodash.defaults": ["[email protected]", "", {}, "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ=="],
|
||||
|
||||
"lodash.difference": ["[email protected]", "", {}, "sha512-dS2j+W26TQ7taQBGN8Lbbq04ssV3emRw4NY58WErlTO29pIqS0HmoT5aJ9+TUQ1N3G+JOZSji4eugsWwGp9yPA=="],
|
||||
"lodash.escaperegexp": ["[email protected]", "", {}, "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw=="],
|
||||
|
||||
"lodash.isarguments": ["[email protected]", "", {}, "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg=="],
|
||||
|
||||
"lodash.isequal": ["[email protected]", "", {}, "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ=="],
|
||||
|
||||
"longest-streak": ["[email protected]", "", {}, "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g=="],
|
||||
|
||||
"lowercase-keys": ["[email protected]", "", {}, "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA=="],
|
||||
@@ -1135,8 +1181,6 @@
|
||||
|
||||
"micromark-util-types": ["[email protected]", "", {}, "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA=="],
|
||||
|
||||
"micromatch": ["[email protected]", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="],
|
||||
|
||||
"mime": ["[email protected]", "", { "bin": { "mime": "bin/cli.js" } }, "sha512-X5ju04+cAzsojXKes0B/S4tcYtFAJ6tTMuSPBEn9CPGlrWr8Fiw7qYeLT0XyH80HSoAoqWCaz+MWKh22P7G1cw=="],
|
||||
|
||||
"mime-db": ["[email protected]", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="],
|
||||
@@ -1205,8 +1249,6 @@
|
||||
|
||||
"picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],
|
||||
|
||||
"pify": ["[email protected]", "", {}, "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g=="],
|
||||
|
||||
"postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg=="],
|
||||
|
||||
"prettier": ["[email protected]", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg=="],
|
||||
@@ -1259,16 +1301,12 @@
|
||||
|
||||
"remark-stringify": ["[email protected]", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-to-markdown": "^2.0.0", "unified": "^11.0.0" } }, "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw=="],
|
||||
|
||||
"remove-trailing-separator": ["[email protected]", "", {}, "sha512-/hS+Y0u3aOfIETiaiirUFwDBDzmXPvO+jAfKTitUngIPzdKc6Z0LoFjM/CK5PL4C+eKwHohlHAb6H0VFfmmUsw=="],
|
||||
|
||||
"require-directory": ["[email protected]", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="],
|
||||
|
||||
"reselect": ["[email protected]", "", {}, "sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w=="],
|
||||
|
||||
"resolve-alpn": ["[email protected]", "", {}, "sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g=="],
|
||||
|
||||
"resolve-from": ["[email protected]", "", {}, "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw=="],
|
||||
|
||||
"resolve-pkg-maps": ["[email protected]", "", {}, "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw=="],
|
||||
|
||||
"responselike": ["[email protected]", "", { "dependencies": { "lowercase-keys": "^2.0.0" } }, "sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw=="],
|
||||
@@ -1285,10 +1323,10 @@
|
||||
|
||||
"run-applescript": ["[email protected]", "", {}, "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q=="],
|
||||
|
||||
"runtime-required": ["[email protected]", "", {}, "sha512-yX97f5E0WfNpcQnfVjap6vzQcvErkYYCx6eTK4siqGEdC8lglwypUFgZVTX7ShvIlgfkC4XGFl9O1KTYcff0pw=="],
|
||||
|
||||
"rxjs": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="],
|
||||
|
||||
"sax": ["[email protected]", "", {}, "sha512-21IYA3Q5cQf089Z6tgaUTr7lDAyzoTPx5HRtbhsME8Udispad8dC/+sziTNugOEx54ilvatQ9YCzl4KQLPcRHA=="],
|
||||
|
||||
"scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
|
||||
|
||||
"semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],
|
||||
@@ -1337,8 +1375,6 @@
|
||||
|
||||
"sumchecker": ["[email protected]", "", { "dependencies": { "debug": "^4.1.0" } }, "sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg=="],
|
||||
|
||||
"supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="],
|
||||
|
||||
"t3": ["t3@workspace:apps/server"],
|
||||
|
||||
"tabbable": ["[email protected]", "", {}, "sha512-05PUHKSNE8ou2dwIxTngl4EzcnsCDZGJ/iCLtDflR/SHB/ny14rXc+qU5P4mG9JkusiV7EivzY9Mhm55AzAvCg=="],
|
||||
@@ -1353,6 +1389,8 @@
|
||||
|
||||
"tiny-invariant": ["[email protected]", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="],
|
||||
|
||||
"tiny-typed-emitter": ["[email protected]", "", {}, "sha512-qVtvMxeXbVej0cQWKqVSSAHmKZEHAvxdF8HEUBFWts8h+xEo5m/lEiPakuyZ3BnCBjOD8i24kzNOiOLLgsSxhA=="],
|
||||
|
||||
"tiny-warning": ["[email protected]", "", {}, "sha512-lBN9zLN/oAf68o3zNXYrdCt1kP8WsiGW8Oo2ka41b2IM5JL/S1CTyX1rW0mb/zSuJun0ZUrDxx4sqvYS2FWzPA=="],
|
||||
|
||||
"tinybench": ["[email protected]", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="],
|
||||
@@ -1423,9 +1461,7 @@
|
||||
|
||||
"unist-util-visit-parents": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0" } }, "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ=="],
|
||||
|
||||
"universalify": ["[email protected].2", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="],
|
||||
|
||||
"unixify": ["[email protected]", "", { "dependencies": { "normalize-path": "^2.1.1" } }, "sha512-6bc58dPYhCMHHuwxldQxO3RRNZ4eCogZ/st++0+fcC1nr0jiGUtAdBJ2qzmLQWSxbtz42pWt4QQMiZ9HvZf5cg=="],
|
||||
"universalify": ["universalify@2.0.1", "", {}, "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw=="],
|
||||
|
||||
"unplugin": ["[email protected]", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "acorn": "^8.15.0", "picomatch": "^4.0.3", "webpack-virtual-modules": "^0.6.2" } }, "sha512-5uKD0nqiYVzlmCRs01Fhs2BdkEgBS3SAVP6ndrBsuK42iC2+JHyxM05Rm9G8+5mkmRtzMZGY8Ct5+mliZxU/Ww=="],
|
||||
|
||||
@@ -1449,8 +1485,6 @@
|
||||
|
||||
"wait-on": ["[email protected]", "", { "dependencies": { "axios": "^1.12.1", "joi": "^18.0.1", "lodash": "^4.17.21", "minimist": "^1.2.8", "rxjs": "^7.8.2" }, "bin": { "wait-on": "bin/wait-on" } }, "sha512-J3WlS0txVHkhLRb2FsmRg3dkMTCV1+M6Xra3Ho7HzZDHpE7DCOnoSoCJsZotrmW3uRMhvIJGSKUKrh/MeF4iag=="],
|
||||
|
||||
"watchboy": ["[email protected]", "", { "dependencies": { "lodash.difference": "^4.5.0", "micromatch": "^4.0.2", "pify": "^4.0.1", "unixify": "^1.0.0" } }, "sha512-GHs1HxwvxSMBsqd/WfTOZhj5gBdMqf5HQpfgtKxDfZRxrlYPDdVLRB61LCeRzJaWANmvSIMlfmRVDwVmJFgAKA=="],
|
||||
|
||||
"webpack-virtual-modules": ["[email protected]", "", {}, "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ=="],
|
||||
|
||||
"why-is-node-running": ["[email protected]", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="],
|
||||
@@ -1509,6 +1543,8 @@
|
||||
|
||||
"@babel/types/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="],
|
||||
|
||||
"@electron/get/fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="],
|
||||
|
||||
"@electron/get/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
|
||||
|
||||
"@tailwindcss/node/lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.30.2", "lightningcss-darwin-arm64": "1.30.2", "lightningcss-darwin-x64": "1.30.2", "lightningcss-freebsd-x64": "1.30.2", "lightningcss-linux-arm-gnueabihf": "1.30.2", "lightningcss-linux-arm64-gnu": "1.30.2", "lightningcss-linux-arm64-musl": "1.30.2", "lightningcss-linux-x64-gnu": "1.30.2", "lightningcss-linux-x64-musl": "1.30.2", "lightningcss-win32-arm64-msvc": "1.30.2", "lightningcss-win32-x64-msvc": "1.30.2" } }, "sha512-utfs7Pr5uJyyvDETitgsaqSyjCb2qNRAtuqUeWIAKztsOYdcACf2KtARYXg2pSvhkt+9NfoaNY7fxjl6nuMjIQ=="],
|
||||
@@ -1557,8 +1593,6 @@
|
||||
|
||||
"mdast-util-find-and-replace/escape-string-regexp": ["[email protected]", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="],
|
||||
|
||||
"micromatch/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
|
||||
|
||||
"parse-entities/@types/unist": ["@types/[email protected]", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="],
|
||||
|
||||
"readdirp/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
|
||||
@@ -1569,14 +1603,16 @@
|
||||
|
||||
"serialize-error/type-fest": ["[email protected]", "", {}, "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg=="],
|
||||
|
||||
"unixify/normalize-path": ["[email protected]", "", { "dependencies": { "remove-trailing-separator": "^1.0.1" } }, "sha512-3pKJwH184Xo/lnH6oyP1q2pMd7HcypqqmRs91/6/i2CGtWwIKGCkOOMTm/zXbgTEWHw1uNpNi/igc3ePOYHb6w=="],
|
||||
|
||||
"vitest/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA=="],
|
||||
|
||||
"@babel/generator/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
|
||||
|
||||
"@babel/parser/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
|
||||
|
||||
"@electron/get/fs-extra/jsonfile": ["[email protected]", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="],
|
||||
|
||||
"@electron/get/fs-extra/universalify": ["[email protected]", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="],
|
||||
|
||||
"@tailwindcss/node/lightningcss/lightningcss-android-arm64": ["[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-BH9sEdOCahSgmkVhBLeU7Hc9DWeZ1Eb6wNS6Da8igvUwAe0sqROHddIlvU06q3WyXVEOYDZ6ykBZQnjTbmo4+A=="],
|
||||
|
||||
"@tailwindcss/node/lightningcss/lightningcss-darwin-arm64": ["[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-ylTcDJBN3Hp21TdhRT5zBOIi73P6/W0qwvlFEk22fkdXchtNTOU4Qc37SkzV+EKYxLouZ6M4LG9NfZ1qkhhBWA=="],
|
||||
|
||||
@@ -12,9 +12,29 @@ This document covers how to run desktop releases from one tag, first without sig
|
||||
- Linux `x64` AppImage
|
||||
- Windows `x64` NSIS installer
|
||||
- Publishes one GitHub Release with all produced files.
|
||||
- Includes Electron auto-update metadata (for example `latest*.yml` and `*.blockmap`) in release assets.
|
||||
- Publishes the CLI package (`apps/server`, npm package `t3`) with OIDC trusted publishing.
|
||||
- Signing is optional and auto-detected per platform from secrets.
|
||||
|
||||
## Desktop auto-update notes
|
||||
|
||||
- Runtime updater: `electron-updater` in `apps/desktop/src/main.ts`.
|
||||
- Update UX:
|
||||
- Background checks run on startup delay + interval.
|
||||
- No automatic download or install.
|
||||
- The desktop UI shows a rocket update button when an update is available; click once to download, click again after download to restart/install.
|
||||
- Provider: GitHub Releases (`provider: github`) configured at build time.
|
||||
- Repository slug source:
|
||||
- `T3CODE_DESKTOP_UPDATE_REPOSITORY` (format `owner/repo`), if set.
|
||||
- otherwise `GITHUB_REPOSITORY` from GitHub Actions.
|
||||
- Temporary private-repo auth workaround:
|
||||
- set `T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN` (or `GH_TOKEN`) in the desktop app runtime environment.
|
||||
- the app forwards it as an `Authorization: Bearer <token>` request header for updater HTTP calls.
|
||||
- Required release assets for updater:
|
||||
- platform installers (`.exe`, `.dmg`, `.AppImage`, plus macOS `.zip` for Squirrel.Mac update payloads)
|
||||
- `latest*.yml` metadata
|
||||
- `*.blockmap` files (used for differential downloads)
|
||||
|
||||
## 0) npm OIDC trusted publishing setup (CLI)
|
||||
|
||||
The workflow publishes the CLI with `bun publish` from `apps/server` after bumping
|
||||
|
||||
+14
-11
@@ -4,22 +4,28 @@
|
||||
"workspaces": {
|
||||
"packages": [
|
||||
"apps/*",
|
||||
"packages/*"
|
||||
"packages/*",
|
||||
"scripts"
|
||||
],
|
||||
"catalog": {
|
||||
"effect": "https://pkg.pr.new/Effect-TS/effect-smol/effect@8881a9b",
|
||||
"@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b",
|
||||
"@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@8881a9b",
|
||||
"@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@8881a9b",
|
||||
"@effect/language-service": "0.75.1"
|
||||
"@effect/language-service": "0.75.1",
|
||||
"@types/bun": "^1.3.9",
|
||||
"@types/node": "^24.10.13",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0"
|
||||
}
|
||||
},
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "bun run scripts/dev-runner.mjs dev",
|
||||
"dev:server": "bun run scripts/dev-runner.mjs dev:server",
|
||||
"dev:web": "bun run scripts/dev-runner.mjs dev:web",
|
||||
"dev:desktop": "bun run scripts/dev-runner.mjs dev:desktop",
|
||||
"dev": "node scripts/dev-runner.ts dev",
|
||||
"dev:server": "node scripts/dev-runner.ts dev:server",
|
||||
"dev:web": "node scripts/dev-runner.ts dev:web",
|
||||
"dev:desktop": "node scripts/dev-runner.ts dev:desktop",
|
||||
"start": "turbo run start --filter=t3",
|
||||
"start:desktop": "turbo run start --filter=@t3tools/desktop",
|
||||
"build": "turbo run build",
|
||||
@@ -40,14 +46,11 @@
|
||||
"sync:vscode-icons": "node scripts/sync-vscode-icons.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@types/node": "^24.10.13",
|
||||
"effect": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"oxfmt": "^0.35.0",
|
||||
"oxlint": "^1.50.0",
|
||||
"turbo": "^2.3.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0"
|
||||
"vitest": "catalog:"
|
||||
},
|
||||
"engines": {
|
||||
"bun": "^1.3.9",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/contracts",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"private": true,
|
||||
"files": [
|
||||
"dist"
|
||||
@@ -27,9 +27,10 @@
|
||||
"effect": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "0.75.1",
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3"
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ export const GitPushStepStatus = Schema.Literals([
|
||||
"skipped_not_requested",
|
||||
"skipped_up_to_date",
|
||||
]);
|
||||
export const GitBranchStepStatus = Schema.Literals(["created", "skipped_not_requested"]);
|
||||
export const GitPrStepStatus = Schema.Literals([
|
||||
"created",
|
||||
"opened_existing",
|
||||
@@ -53,6 +54,7 @@ export const GitRunStackedActionInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyStringSchema,
|
||||
action: GitStackedAction,
|
||||
commitMessage: Schema.optional(TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(10_000))),
|
||||
featureBranch: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
export type GitRunStackedActionInput = typeof GitRunStackedActionInput.Type;
|
||||
|
||||
@@ -139,6 +141,10 @@ export type GitCreateWorktreeResult = typeof GitCreateWorktreeResult.Type;
|
||||
|
||||
export const GitRunStackedActionResult = Schema.Struct({
|
||||
action: GitStackedAction,
|
||||
branch: Schema.Struct({
|
||||
status: GitBranchStepStatus,
|
||||
name: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
}),
|
||||
commit: Schema.Struct({
|
||||
status: GitCommitStepStatus,
|
||||
commitSha: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
|
||||
@@ -43,6 +43,35 @@ export interface ContextMenuItem<T extends string = string> {
|
||||
destructive?: boolean;
|
||||
}
|
||||
|
||||
export type DesktopUpdateStatus =
|
||||
| "disabled"
|
||||
| "idle"
|
||||
| "checking"
|
||||
| "up-to-date"
|
||||
| "available"
|
||||
| "downloading"
|
||||
| "downloaded"
|
||||
| "error";
|
||||
|
||||
export interface DesktopUpdateState {
|
||||
enabled: boolean;
|
||||
status: DesktopUpdateStatus;
|
||||
currentVersion: string;
|
||||
availableVersion: string | null;
|
||||
downloadedVersion: string | null;
|
||||
downloadPercent: number | null;
|
||||
checkedAt: string | null;
|
||||
message: string | null;
|
||||
errorContext: "check" | "download" | "install" | null;
|
||||
canRetry: boolean;
|
||||
}
|
||||
|
||||
export interface DesktopUpdateActionResult {
|
||||
accepted: boolean;
|
||||
completed: boolean;
|
||||
state: DesktopUpdateState;
|
||||
}
|
||||
|
||||
export interface DesktopBridge {
|
||||
getWsUrl: () => string | null;
|
||||
pickFolder: () => Promise<string | null>;
|
||||
@@ -53,6 +82,10 @@ export interface DesktopBridge {
|
||||
) => Promise<T | null>;
|
||||
openExternal: (url: string) => Promise<boolean>;
|
||||
onMenuAction: (listener: (action: string) => void) => () => void;
|
||||
getUpdateState: () => Promise<DesktopUpdateState>;
|
||||
downloadUpdate: () => Promise<DesktopUpdateActionResult>;
|
||||
installUpdate: () => Promise<DesktopUpdateActionResult>;
|
||||
onUpdateState: (listener: (state: DesktopUpdateState) => void) => () => void;
|
||||
}
|
||||
|
||||
export interface NativeApi {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Schema } from "effect";
|
||||
import { TrimmedNonEmptyString } from "./baseSchemas";
|
||||
import { IsoDateTime, TrimmedNonEmptyString } from "./baseSchemas";
|
||||
import { KeybindingRule, ResolvedKeybindingsConfig } from "./keybindings";
|
||||
import { EditorId } from "./editor";
|
||||
import { ProviderKind } from "./orchestration";
|
||||
|
||||
export const KeybindingsMalformedConfigIssue = Schema.Struct({
|
||||
kind: Schema.Literal("keybindings.malformed-config"),
|
||||
@@ -25,12 +26,55 @@ export type ServerConfigIssue = typeof ServerConfigIssue.Type;
|
||||
export const ServerConfigIssues = Schema.Array(ServerConfigIssue);
|
||||
export type ServerConfigIssues = typeof ServerConfigIssues.Type;
|
||||
|
||||
export const ServerProviderStatusState = Schema.Literals(["ready", "warning", "error"]);
|
||||
export type ServerProviderStatusState = typeof ServerProviderStatusState.Type;
|
||||
|
||||
export const ServerProviderAuthStatus = Schema.Literals([
|
||||
"authenticated",
|
||||
"unauthenticated",
|
||||
"unknown",
|
||||
]);
|
||||
export type ServerProviderAuthStatus = typeof ServerProviderAuthStatus.Type;
|
||||
|
||||
export const ServerProviderStatus = Schema.Struct({
|
||||
provider: ProviderKind,
|
||||
status: ServerProviderStatusState,
|
||||
available: Schema.Boolean,
|
||||
authStatus: ServerProviderAuthStatus,
|
||||
checkedAt: IsoDateTime,
|
||||
message: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
export type ServerProviderStatus = typeof ServerProviderStatus.Type;
|
||||
|
||||
export const ServerProviderStatuses = Schema.Array(ServerProviderStatus);
|
||||
export type ServerProviderStatuses = typeof ServerProviderStatuses.Type;
|
||||
|
||||
export const ServerRuntimePlatform = Schema.Literals(["windows", "linux", "macos"]);
|
||||
export type ServerRuntimePlatform = typeof ServerRuntimePlatform.Type;
|
||||
|
||||
export const ServerPathStyle = Schema.Literals(["windows", "posix"]);
|
||||
export type ServerPathStyle = typeof ServerPathStyle.Type;
|
||||
|
||||
export const ServerWindowsInteropMode = Schema.Literals(["windows-native", "wsl-hosted"]);
|
||||
export type ServerWindowsInteropMode = typeof ServerWindowsInteropMode.Type;
|
||||
|
||||
export const ServerRuntimeEnvironment = Schema.Struct({
|
||||
platform: ServerRuntimePlatform,
|
||||
pathStyle: ServerPathStyle,
|
||||
isWsl: Schema.Boolean,
|
||||
windowsInteropMode: Schema.NullOr(ServerWindowsInteropMode),
|
||||
wslDistroName: Schema.NullOr(TrimmedNonEmptyString),
|
||||
});
|
||||
export type ServerRuntimeEnvironment = typeof ServerRuntimeEnvironment.Type;
|
||||
|
||||
export const ServerConfig = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyString,
|
||||
keybindingsConfigPath: TrimmedNonEmptyString,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
issues: ServerConfigIssues,
|
||||
providers: ServerProviderStatuses,
|
||||
availableEditors: Schema.Array(EditorId),
|
||||
runtimeEnvironment: ServerRuntimeEnvironment,
|
||||
});
|
||||
export type ServerConfig = typeof ServerConfig.Type;
|
||||
|
||||
@@ -45,5 +89,6 @@ export type ServerUpsertKeybindingResult = typeof ServerUpsertKeybindingResult.T
|
||||
|
||||
export const ServerConfigUpdatedPayload = Schema.Struct({
|
||||
issues: ServerConfigIssues,
|
||||
providers: ServerProviderStatuses,
|
||||
});
|
||||
export type ServerConfigUpdatedPayload = typeof ServerConfigUpdatedPayload.Type;
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"name": "@t3tools/shared",
|
||||
"version": "0.0.0-alpha.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
"./git": {
|
||||
"types": "./src/git.ts",
|
||||
"import": "./src/git.ts"
|
||||
},
|
||||
"./logging": {
|
||||
"types": "./src/logging.ts",
|
||||
"import": "./src/logging.ts"
|
||||
},
|
||||
"./Net": {
|
||||
"types": "./src/Net.ts",
|
||||
"import": "./src/Net.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"effect": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import * as Net from "node:net";
|
||||
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect } from "effect";
|
||||
|
||||
import { NetError, NetService } from "./Net";
|
||||
|
||||
const closeServer = (server: Net.Server) =>
|
||||
Effect.sync(() => {
|
||||
try {
|
||||
server.close();
|
||||
} catch {
|
||||
// Ignore cleanup failures in tests.
|
||||
}
|
||||
});
|
||||
|
||||
const getPort = (server: Net.Server): number => {
|
||||
const address = server.address();
|
||||
return typeof address === "object" && address !== null ? address.port : 0;
|
||||
};
|
||||
|
||||
const openServer = (host?: string): Effect.Effect<Net.Server, NetError> =>
|
||||
Effect.callback<Net.Server, NetError>((resume) => {
|
||||
const server = Net.createServer();
|
||||
let settled = false;
|
||||
|
||||
const settle = (effect: Effect.Effect<Net.Server, NetError>) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
resume(effect);
|
||||
};
|
||||
|
||||
server.once("error", (cause) => {
|
||||
settle(Effect.fail(new NetError({ message: "Failed to open test server", cause })));
|
||||
});
|
||||
|
||||
if (host) {
|
||||
server.listen(0, host, () => settle(Effect.succeed(server)));
|
||||
} else {
|
||||
server.listen(0, () => settle(Effect.succeed(server)));
|
||||
}
|
||||
|
||||
return closeServer(server);
|
||||
});
|
||||
|
||||
it.layer(NetService.layer)("NetService", (it) => {
|
||||
describe("Net helpers", () => {
|
||||
it.effect("reserveLoopbackPort returns a positive loopback port", () =>
|
||||
Effect.gen(function* () {
|
||||
const net = yield* NetService;
|
||||
const port = yield* net.reserveLoopbackPort();
|
||||
|
||||
assert.ok(port > 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("isPortAvailableOnLoopback reports false for an occupied port", () =>
|
||||
Effect.acquireUseRelease(
|
||||
openServer("127.0.0.1"),
|
||||
(server) =>
|
||||
Effect.gen(function* () {
|
||||
const net = yield* NetService;
|
||||
const port = getPort(server);
|
||||
|
||||
const available = yield* net.isPortAvailableOnLoopback(port);
|
||||
assert.equal(available, false);
|
||||
}),
|
||||
closeServer,
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("findAvailablePort returns preferred when it is free", () =>
|
||||
Effect.gen(function* () {
|
||||
const net = yield* NetService;
|
||||
const preferred = yield* net.reserveLoopbackPort();
|
||||
|
||||
const resolved = yield* net.findAvailablePort(preferred);
|
||||
assert.equal(resolved, preferred);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("findAvailablePort falls back when preferred is occupied", () =>
|
||||
Effect.acquireUseRelease(
|
||||
openServer(),
|
||||
(server) =>
|
||||
Effect.gen(function* () {
|
||||
const net = yield* NetService;
|
||||
const preferred = getPort(server);
|
||||
|
||||
const resolved = yield* net.findAvailablePort(preferred);
|
||||
assert.ok(resolved > 0);
|
||||
assert.notEqual(resolved, preferred);
|
||||
}),
|
||||
closeServer,
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,180 @@
|
||||
import * as Net from "node:net";
|
||||
|
||||
import { Data, Effect, Layer, ServiceMap } from "effect";
|
||||
|
||||
export class NetError extends Data.TaggedError("NetError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
function isErrnoExceptionWithCode(cause: unknown): cause is {
|
||||
readonly code: string;
|
||||
} {
|
||||
return (
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"code" in cause &&
|
||||
typeof (cause as { readonly code: unknown }).code === "string"
|
||||
);
|
||||
}
|
||||
|
||||
const closeServer = (server: Net.Server) => {
|
||||
try {
|
||||
server.close();
|
||||
} catch {
|
||||
// Ignore close failures during cleanup.
|
||||
}
|
||||
};
|
||||
|
||||
const tryReservePort = (port: number): Effect.Effect<number, NetError> =>
|
||||
Effect.callback<number, NetError>((resume) => {
|
||||
const server = Net.createServer();
|
||||
let settled = false;
|
||||
|
||||
const settle = (effect: Effect.Effect<number, NetError>) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
resume(effect);
|
||||
};
|
||||
|
||||
server.unref();
|
||||
|
||||
server.once("error", (cause) => {
|
||||
settle(Effect.fail(new NetError({ message: "Could not find an available port.", cause })));
|
||||
});
|
||||
|
||||
server.listen(port, () => {
|
||||
const address = server.address();
|
||||
const resolved = typeof address === "object" && address !== null ? address.port : 0;
|
||||
server.close(() => {
|
||||
if (resolved > 0) {
|
||||
settle(Effect.succeed(resolved));
|
||||
return;
|
||||
}
|
||||
settle(Effect.fail(new NetError({ message: "Could not find an available port." })));
|
||||
});
|
||||
});
|
||||
|
||||
return Effect.sync(() => {
|
||||
closeServer(server);
|
||||
});
|
||||
});
|
||||
|
||||
export interface NetServiceShape {
|
||||
/**
|
||||
* Returns true when a TCP server can bind to {host, port}.
|
||||
*/
|
||||
readonly canListenOnHost: (port: number, host: string) => Effect.Effect<boolean>;
|
||||
|
||||
/**
|
||||
* Checks loopback availability on both IPv4 and IPv6 localhost addresses.
|
||||
*/
|
||||
readonly isPortAvailableOnLoopback: (port: number) => Effect.Effect<boolean>;
|
||||
|
||||
/**
|
||||
* Reserve an ephemeral loopback port and release it immediately.
|
||||
*/
|
||||
readonly reserveLoopbackPort: (host?: string) => Effect.Effect<number, NetError>;
|
||||
|
||||
/**
|
||||
* Resolve an available listening port, preferring the provided port first.
|
||||
*/
|
||||
readonly findAvailablePort: (preferred: number) => Effect.Effect<number, NetError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* NetService - Service tag for startup networking helpers.
|
||||
*/
|
||||
export class NetService extends ServiceMap.Service<NetService, NetServiceShape>()(
|
||||
"@t3tools/shared/Net/NetService",
|
||||
) {
|
||||
static readonly layer = Layer.sync(NetService, () => {
|
||||
/**
|
||||
* Returns true when a TCP server can bind to {host, port}.
|
||||
* `EADDRNOTAVAIL` is treated as available so IPv6-absent hosts don't fail
|
||||
* loopback availability checks.
|
||||
*/
|
||||
const canListenOnHost = (port: number, host: string): Effect.Effect<boolean> =>
|
||||
Effect.callback<boolean>((resume) => {
|
||||
const server = Net.createServer();
|
||||
let settled = false;
|
||||
|
||||
const settle = (value: boolean) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
resume(Effect.succeed(value));
|
||||
};
|
||||
|
||||
server.unref();
|
||||
|
||||
server.once("error", (cause) => {
|
||||
if (isErrnoExceptionWithCode(cause) && cause.code === "EADDRNOTAVAIL") {
|
||||
settle(true);
|
||||
return;
|
||||
}
|
||||
settle(false);
|
||||
});
|
||||
|
||||
server.once("listening", () => {
|
||||
server.close(() => {
|
||||
settle(true);
|
||||
});
|
||||
});
|
||||
|
||||
server.listen({ host, port });
|
||||
|
||||
return Effect.sync(() => {
|
||||
closeServer(server);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Reserve an ephemeral loopback port and release it immediately.
|
||||
* Returns the reserved port number.
|
||||
*/
|
||||
const reserveLoopbackPort = (host = "127.0.0.1"): Effect.Effect<number, NetError> =>
|
||||
Effect.callback<number, NetError>((resume) => {
|
||||
const probe = Net.createServer();
|
||||
let settled = false;
|
||||
|
||||
const settle = (effect: Effect.Effect<number, NetError>) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
resume(effect);
|
||||
};
|
||||
|
||||
probe.once("error", (cause) => {
|
||||
settle(Effect.fail(new NetError({ message: "Failed to reserve loopback port", cause })));
|
||||
});
|
||||
|
||||
probe.listen(0, host, () => {
|
||||
const address = probe.address();
|
||||
const port = typeof address === "object" && address !== null ? address.port : 0;
|
||||
probe.close(() => {
|
||||
if (port > 0) {
|
||||
settle(Effect.succeed(port));
|
||||
return;
|
||||
}
|
||||
settle(Effect.fail(new NetError({ message: "Failed to reserve loopback port" })));
|
||||
});
|
||||
});
|
||||
|
||||
return Effect.sync(() => {
|
||||
closeServer(probe);
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
canListenOnHost,
|
||||
isPortAvailableOnLoopback: (port) =>
|
||||
Effect.zipWith(
|
||||
canListenOnHost(port, "127.0.0.1"),
|
||||
canListenOnHost(port, "::1"),
|
||||
(ipv4, ipv6) => ipv4 && ipv6,
|
||||
),
|
||||
reserveLoopbackPort,
|
||||
findAvailablePort: (preferred) =>
|
||||
Effect.catch(tryReservePort(preferred), () => tryReservePort(0)),
|
||||
} satisfies NetServiceShape;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Sanitize an arbitrary string into a valid, lowercase git branch fragment.
|
||||
* Strips quotes, collapses separators, limits to 64 chars.
|
||||
*/
|
||||
export function sanitizeBranchFragment(raw: string): string {
|
||||
const normalized = raw
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/['"`]/g, "")
|
||||
.replace(/^[./\s_-]+|[./\s_-]+$/g, "");
|
||||
|
||||
const branchFragment = normalized
|
||||
.replace(/[^a-z0-9/_-]+/g, "-")
|
||||
.replace(/\/+/g, "/")
|
||||
.replace(/-+/g, "-")
|
||||
.replace(/^[./_-]+|[./_-]+$/g, "")
|
||||
.slice(0, 64)
|
||||
.replace(/[./_-]+$/g, "");
|
||||
|
||||
return branchFragment.length > 0 ? branchFragment : "update";
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize a string into a `feature/…` branch name.
|
||||
* Preserves an existing `feature/` prefix or slash-separated namespace.
|
||||
*/
|
||||
export function sanitizeFeatureBranchName(raw: string): string {
|
||||
const sanitized = sanitizeBranchFragment(raw);
|
||||
if (sanitized.includes("/")) {
|
||||
return sanitized.startsWith("feature/") ? sanitized : `feature/${sanitized}`;
|
||||
}
|
||||
return `feature/${sanitized}`;
|
||||
}
|
||||
|
||||
const AUTO_FEATURE_BRANCH_FALLBACK = "feature/update";
|
||||
|
||||
/**
|
||||
* Resolve a unique `feature/…` branch name that doesn't collide with
|
||||
* any existing branch. Appends a numeric suffix when needed.
|
||||
*/
|
||||
export function resolveAutoFeatureBranchName(
|
||||
existingBranchNames: readonly string[],
|
||||
preferredBranch?: string,
|
||||
): string {
|
||||
const preferred = preferredBranch?.trim();
|
||||
const resolvedBase = sanitizeFeatureBranchName(
|
||||
preferred && preferred.length > 0 ? preferred : AUTO_FEATURE_BRANCH_FALLBACK,
|
||||
);
|
||||
const existingNames = new Set(existingBranchNames.map((branch) => branch.toLowerCase()));
|
||||
|
||||
if (!existingNames.has(resolvedBase)) {
|
||||
return resolvedBase;
|
||||
}
|
||||
|
||||
let suffix = 2;
|
||||
while (existingNames.has(`${resolvedBase}-${suffix}`)) {
|
||||
suffix += 1;
|
||||
}
|
||||
|
||||
return `${resolvedBase}-${suffix}`;
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
export interface RotatingFileSinkOptions {
|
||||
readonly filePath: string;
|
||||
readonly maxBytes: number;
|
||||
readonly maxFiles: number;
|
||||
readonly throwOnError?: boolean;
|
||||
}
|
||||
|
||||
export class RotatingFileSink {
|
||||
private readonly filePath: string;
|
||||
private readonly maxBytes: number;
|
||||
private readonly maxFiles: number;
|
||||
private readonly throwOnError: boolean;
|
||||
private currentSize = 0;
|
||||
|
||||
constructor(options: RotatingFileSinkOptions) {
|
||||
if (options.maxBytes < 1) {
|
||||
throw new Error(`maxBytes must be >= 1 (received ${options.maxBytes})`);
|
||||
}
|
||||
if (options.maxFiles < 1) {
|
||||
throw new Error(`maxFiles must be >= 1 (received ${options.maxFiles})`);
|
||||
}
|
||||
|
||||
this.filePath = options.filePath;
|
||||
this.maxBytes = options.maxBytes;
|
||||
this.maxFiles = options.maxFiles;
|
||||
this.throwOnError = options.throwOnError ?? false;
|
||||
|
||||
fs.mkdirSync(path.dirname(this.filePath), { recursive: true });
|
||||
this.pruneOverflowBackups();
|
||||
this.currentSize = this.readCurrentSize();
|
||||
}
|
||||
|
||||
write(chunk: string | Buffer): void {
|
||||
const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
|
||||
if (buffer.length === 0) return;
|
||||
|
||||
try {
|
||||
if (this.currentSize > 0 && this.currentSize + buffer.length > this.maxBytes) {
|
||||
this.rotate();
|
||||
}
|
||||
|
||||
fs.appendFileSync(this.filePath, buffer);
|
||||
this.currentSize += buffer.length;
|
||||
|
||||
if (this.currentSize > this.maxBytes) {
|
||||
this.rotate();
|
||||
}
|
||||
} catch {
|
||||
this.currentSize = this.readCurrentSize();
|
||||
if (this.throwOnError) {
|
||||
throw new Error(`Failed to write log chunk to ${this.filePath}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private rotate(): void {
|
||||
try {
|
||||
const oldest = this.withSuffix(this.maxFiles);
|
||||
if (fs.existsSync(oldest)) {
|
||||
fs.rmSync(oldest, { force: true });
|
||||
}
|
||||
|
||||
for (let index = this.maxFiles - 1; index >= 1; index -= 1) {
|
||||
const source = this.withSuffix(index);
|
||||
const target = this.withSuffix(index + 1);
|
||||
if (fs.existsSync(source)) {
|
||||
fs.renameSync(source, target);
|
||||
}
|
||||
}
|
||||
|
||||
if (fs.existsSync(this.filePath)) {
|
||||
fs.renameSync(this.filePath, this.withSuffix(1));
|
||||
}
|
||||
|
||||
this.currentSize = 0;
|
||||
} catch {
|
||||
this.currentSize = this.readCurrentSize();
|
||||
if (this.throwOnError) {
|
||||
throw new Error(`Failed to rotate log file ${this.filePath}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private pruneOverflowBackups(): void {
|
||||
try {
|
||||
const dir = path.dirname(this.filePath);
|
||||
const baseName = path.basename(this.filePath);
|
||||
for (const entry of fs.readdirSync(dir)) {
|
||||
if (!entry.startsWith(`${baseName}.`)) continue;
|
||||
const suffix = Number(entry.slice(baseName.length + 1));
|
||||
if (!Number.isInteger(suffix) || suffix <= this.maxFiles) continue;
|
||||
fs.rmSync(path.join(dir, entry), { force: true });
|
||||
}
|
||||
} catch {
|
||||
if (this.throwOnError) {
|
||||
throw new Error(`Failed to prune log backups for ${this.filePath}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private readCurrentSize(): number {
|
||||
try {
|
||||
return fs.statSync(this.filePath).size;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private withSuffix(index: number): string {
|
||||
return `${this.filePath}.${index}`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -6,11 +6,13 @@ import rootPackageJson from "../package.json" with { type: "json" };
|
||||
import desktopPackageJson from "../apps/desktop/package.json" with { type: "json" };
|
||||
import serverPackageJson from "../apps/server/package.json" with { type: "json" };
|
||||
|
||||
import { resolveCatalogDependencies } from "./lib/resolve-catalog.ts";
|
||||
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Config, Data, Effect, FileSystem, Logger, Option, Path, Schema } from "effect";
|
||||
import { Config, Data, Effect, FileSystem, Layer, Logger, Option, Path, Schema } from "effect";
|
||||
import { Command, Flag } from "effect/unstable/cli";
|
||||
import { ChildProcess } from "effect/unstable/process";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
const BuildPlatform = Schema.Literals(["mac", "linux", "win"]);
|
||||
const BuildArch = Schema.Literals(["arm64", "x64", "universal"]);
|
||||
@@ -21,6 +23,7 @@ const RepoRoot = Effect.service(Path.Path).pipe(
|
||||
const IconSource = Effect.zipWith(RepoRoot, Effect.service(Path.Path), (repoRoot, path) =>
|
||||
path.join(repoRoot, "assets/macos-icon-1024.png"),
|
||||
);
|
||||
const encodeJsonString = Schema.encodeEffect(Schema.UnknownFromJsonString);
|
||||
|
||||
interface PlatformConfig {
|
||||
readonly cliFlag: "--mac" | "--linux" | "--win";
|
||||
@@ -134,14 +137,12 @@ const AzureTrustedSigningOptionsConfig = Config.all({
|
||||
endpoint: Config.string("AZURE_TRUSTED_SIGNING_ENDPOINT"),
|
||||
certificateProfileName: Config.string("AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME"),
|
||||
codeSigningAccountName: Config.string("AZURE_TRUSTED_SIGNING_ACCOUNT_NAME"),
|
||||
fileDigest: Config.string("AZURE_TRUSTED_SIGNING_FILE_DIGEST").pipe(
|
||||
Config.withDefault(() => "SHA256"),
|
||||
),
|
||||
fileDigest: Config.string("AZURE_TRUSTED_SIGNING_FILE_DIGEST").pipe(Config.withDefault("SHA256")),
|
||||
timestampDigest: Config.string("AZURE_TRUSTED_SIGNING_TIMESTAMP_DIGEST").pipe(
|
||||
Config.withDefault(() => "SHA256"),
|
||||
Config.withDefault("SHA256"),
|
||||
),
|
||||
timestampRfc3161: Config.string("AZURE_TRUSTED_SIGNING_TIMESTAMP_RFC3161").pipe(
|
||||
Config.withDefault(() => "http://timestamp.acs.microsoft.com"),
|
||||
Config.withDefault("http://timestamp.acs.microsoft.com"),
|
||||
),
|
||||
});
|
||||
|
||||
@@ -151,10 +152,10 @@ const BuildEnvConfig = Config.all({
|
||||
arch: Config.schema(BuildArch, "T3CODE_DESKTOP_ARCH").pipe(Config.option),
|
||||
version: Config.string("T3CODE_DESKTOP_VERSION").pipe(Config.option),
|
||||
outputDir: Config.string("T3CODE_DESKTOP_OUTPUT_DIR").pipe(Config.option),
|
||||
skipBuild: Config.boolean("T3CODE_DESKTOP_SKIP_BUILD").pipe(Config.withDefault(() => false)),
|
||||
keepStage: Config.boolean("T3CODE_DESKTOP_KEEP_STAGE").pipe(Config.withDefault(() => false)),
|
||||
signed: Config.boolean("T3CODE_DESKTOP_SIGNED").pipe(Config.withDefault(() => false)),
|
||||
verbose: Config.boolean("T3CODE_DESKTOP_VERBOSE").pipe(Config.withDefault(() => false)),
|
||||
skipBuild: Config.boolean("T3CODE_DESKTOP_SKIP_BUILD").pipe(Config.withDefault(false)),
|
||||
keepStage: Config.boolean("T3CODE_DESKTOP_KEEP_STAGE").pipe(Config.withDefault(false)),
|
||||
signed: Config.boolean("T3CODE_DESKTOP_SIGNED").pipe(Config.withDefault(false)),
|
||||
verbose: Config.boolean("T3CODE_DESKTOP_VERBOSE").pipe(Config.withDefault(false)),
|
||||
});
|
||||
|
||||
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
|
||||
@@ -162,7 +163,7 @@ const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
|
||||
const mergeOptions = <A>(a: Option.Option<A>, b: Option.Option<A>, defaultValue: A) =>
|
||||
Option.getOrElse(a, () => Option.getOrElse(b, () => defaultValue));
|
||||
|
||||
const resolveBuildOptions = Effect.fn(function* (input: BuildCliInput) {
|
||||
const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (input: BuildCliInput) {
|
||||
const path = yield* Path.Path;
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const env = yield* BuildEnvConfig.asEffect();
|
||||
@@ -208,12 +209,14 @@ const commandOutputOptions = (verbose: boolean) =>
|
||||
stderr: "inherit",
|
||||
}) as const;
|
||||
|
||||
const runCommand = Effect.fn(function* (command: ChildProcess.Command) {
|
||||
const exitCode = yield* ChildProcess.exitCode(command);
|
||||
const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const child = yield* commandSpawner.spawn(command);
|
||||
const exitCode = yield* child.exitCode;
|
||||
|
||||
if (exitCode !== 0) {
|
||||
return yield* new BuildScriptError({
|
||||
message: "Command exited with non-zero exit code",
|
||||
message: `Command exited with non-zero exit code (${exitCode})`,
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -288,9 +291,9 @@ function validateBundledClientAssets(clientDir: string) {
|
||||
const path = yield* Path.Path;
|
||||
const indexPath = path.join(clientDir, "index.html");
|
||||
const indexHtml = yield* fs.readFileString(indexPath);
|
||||
const refs = [...indexHtml.matchAll(/\b(?:src|href)=["']([^"']+)["']/g)].map(
|
||||
(match) => match[1],
|
||||
);
|
||||
const refs = [...indexHtml.matchAll(/\b(?:src|href)=["']([^"']+)["']/g)]
|
||||
.map((match) => match[1])
|
||||
.filter((value): value is string => value !== undefined);
|
||||
const missing: string[] = [];
|
||||
|
||||
for (const ref of refs) {
|
||||
@@ -319,32 +322,47 @@ function validateBundledClientAssets(clientDir: string) {
|
||||
});
|
||||
}
|
||||
|
||||
function resolveCatalogDependencies(
|
||||
dependencies: Record<string, unknown>,
|
||||
function resolveDesktopRuntimeDependencies(
|
||||
dependencies: Record<string, unknown> | undefined,
|
||||
catalog: Record<string, unknown>,
|
||||
dependencySourceLabel: string,
|
||||
): Record<string, unknown> {
|
||||
return Object.fromEntries(
|
||||
Object.entries(dependencies).map(([dependencyName, spec]) => {
|
||||
if (typeof spec !== "string" || !spec.startsWith("catalog:")) {
|
||||
return [dependencyName, spec];
|
||||
}
|
||||
if (!dependencies || Object.keys(dependencies).length === 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const catalogKey = spec.slice("catalog:".length).trim();
|
||||
const lookupKey = catalogKey.length > 0 ? catalogKey : dependencyName;
|
||||
const resolvedSpec = catalog[lookupKey];
|
||||
if (typeof resolvedSpec !== "string" || resolvedSpec.length === 0) {
|
||||
throw new BuildScriptError({
|
||||
message: `Unable to resolve '${spec}' for ${dependencySourceLabel} dependency '${dependencyName}'. Expected key '${lookupKey}' in root workspace catalog.`,
|
||||
});
|
||||
}
|
||||
|
||||
return [dependencyName, resolvedSpec];
|
||||
}),
|
||||
const runtimeDependencies = Object.fromEntries(
|
||||
Object.entries(dependencies).filter(([dependencyName]) => dependencyName !== "electron"),
|
||||
);
|
||||
|
||||
return resolveCatalogDependencies(runtimeDependencies, catalog, "apps/desktop");
|
||||
}
|
||||
|
||||
const createBuildConfig = Effect.fn(function* (
|
||||
function resolveGitHubPublishConfig():
|
||||
| {
|
||||
readonly provider: "github";
|
||||
readonly owner: string;
|
||||
readonly repo: string;
|
||||
readonly releaseType: "release";
|
||||
}
|
||||
| undefined {
|
||||
const rawRepo =
|
||||
process.env.T3CODE_DESKTOP_UPDATE_REPOSITORY?.trim() ||
|
||||
process.env.GITHUB_REPOSITORY?.trim() ||
|
||||
"";
|
||||
if (!rawRepo) return undefined;
|
||||
|
||||
const [owner, repo, ...rest] = rawRepo.split("/");
|
||||
if (!owner || !repo || rest.length > 0) return undefined;
|
||||
|
||||
return {
|
||||
provider: "github",
|
||||
owner,
|
||||
repo,
|
||||
releaseType: "release",
|
||||
};
|
||||
}
|
||||
|
||||
const createBuildConfig = Effect.fn("createBuildConfig")(function* (
|
||||
platform: typeof BuildPlatform.Type,
|
||||
target: string,
|
||||
productName: string,
|
||||
@@ -358,10 +376,14 @@ const createBuildConfig = Effect.fn(function* (
|
||||
buildResources: "apps/desktop/resources",
|
||||
},
|
||||
};
|
||||
const publishConfig = resolveGitHubPublishConfig();
|
||||
if (publishConfig) {
|
||||
buildConfig.publish = [publishConfig];
|
||||
}
|
||||
|
||||
if (platform === "mac") {
|
||||
buildConfig.mac = {
|
||||
target: [target],
|
||||
target: target === "dmg" ? [target, "zip"] : [target],
|
||||
icon: "icon.icns",
|
||||
category: "public.app-category.developer-tools",
|
||||
};
|
||||
@@ -389,7 +411,7 @@ const createBuildConfig = Effect.fn(function* (
|
||||
return buildConfig;
|
||||
});
|
||||
|
||||
const assertPlatformBuildResources = Effect.fn(function* (
|
||||
const assertPlatformBuildResources = Effect.fn("assertPlatformBuildResources")(function* (
|
||||
platform: typeof BuildPlatform.Type,
|
||||
stageResourcesDir: string,
|
||||
verbose: boolean,
|
||||
@@ -422,7 +444,9 @@ const assertPlatformBuildResources = Effect.fn(function* (
|
||||
}
|
||||
});
|
||||
|
||||
const buildDesktopArtifact = Effect.fn(function* (options: ResolvedBuildOptions) {
|
||||
const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
|
||||
options: ResolvedBuildOptions,
|
||||
) {
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
@@ -436,22 +460,38 @@ const buildDesktopArtifact = Effect.fn(function* (options: ResolvedBuildOptions)
|
||||
|
||||
const electronVersion = desktopPackageJson.dependencies.electron;
|
||||
|
||||
const dependencies = serverPackageJson.dependencies;
|
||||
if (!dependencies || Object.keys(dependencies).length === 0) {
|
||||
const serverDependencies = serverPackageJson.dependencies;
|
||||
if (!serverDependencies || Object.keys(serverDependencies).length === 0) {
|
||||
return yield* new BuildScriptError({
|
||||
message: "Could not resolve production dependencies from apps/server/package.json.",
|
||||
});
|
||||
}
|
||||
|
||||
const resolvedDependencies = yield* Effect.try({
|
||||
const resolvedServerDependencies = yield* Effect.try({
|
||||
try: () =>
|
||||
resolveCatalogDependencies(dependencies, rootPackageJson.workspaces.catalog, "apps/server"),
|
||||
resolveCatalogDependencies(
|
||||
serverDependencies,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"apps/server",
|
||||
),
|
||||
catch: (cause) =>
|
||||
new BuildScriptError({
|
||||
message: "Could not resolve production dependencies from apps/server/package.json.",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const resolvedDesktopRuntimeDependencies = yield* Effect.try({
|
||||
try: () =>
|
||||
resolveDesktopRuntimeDependencies(
|
||||
desktopPackageJson.dependencies,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
),
|
||||
catch: (cause) =>
|
||||
new BuildScriptError({
|
||||
message: "Could not resolve desktop runtime dependencies from apps/desktop/package.json.",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
const appVersion = options.version ?? serverPackageJson.version;
|
||||
const commitHash = resolveGitCommitHash(repoRoot);
|
||||
@@ -520,16 +560,17 @@ const buildDesktopArtifact = Effect.fn(function* (options: ResolvedBuildOptions)
|
||||
desktopPackageJson.productName ?? "T3 Code",
|
||||
options.signed,
|
||||
),
|
||||
dependencies: resolvedDependencies,
|
||||
dependencies: {
|
||||
...resolvedServerDependencies,
|
||||
...resolvedDesktopRuntimeDependencies,
|
||||
},
|
||||
devDependencies: {
|
||||
electron: electronVersion,
|
||||
},
|
||||
};
|
||||
|
||||
yield* fs.writeFileString(
|
||||
path.join(stageAppDir, "package.json"),
|
||||
`${JSON.stringify(stagePackageJson, null, 2)}\n`,
|
||||
);
|
||||
const stagePackageJsonString = yield* encodeJsonString(stagePackageJson);
|
||||
yield* fs.writeFileString(path.join(stageAppDir, "package.json"), `${stagePackageJsonString}\n`);
|
||||
|
||||
yield* Effect.log("[desktop-artifact] Installing staged production dependencies...");
|
||||
yield* runCommand(
|
||||
@@ -564,7 +605,7 @@ const buildDesktopArtifact = Effect.fn(function* (options: ResolvedBuildOptions)
|
||||
cwd: stageAppDir,
|
||||
env: buildEnv,
|
||||
...commandOutputOptions(options.verbose),
|
||||
})`bunx electron-builder ${platformConfig.cliFlag} ${options.target} --${options.arch} --publish never`,
|
||||
})`bunx electron-builder ${platformConfig.cliFlag} --${options.arch} --publish never`,
|
||||
);
|
||||
|
||||
const stageDistDir = path.join(stageAppDir, "dist");
|
||||
@@ -647,9 +688,10 @@ const buildDesktopArtifactCli = Command.make("build-desktop-artifact", {
|
||||
Command.withHandler((input) => Effect.flatMap(resolveBuildOptions(input), buildDesktopArtifact)),
|
||||
);
|
||||
|
||||
const cliRuntimeLayer = Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer);
|
||||
|
||||
Command.run(buildDesktopArtifactCli, { version: "0.0.0" }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Logger.layer([Logger.consolePretty()])),
|
||||
Effect.provide(NodeServices.layer),
|
||||
Effect.provide(cliRuntimeLayer),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
@@ -1,425 +0,0 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import net from "node:net";
|
||||
import { homedir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
const BASE_SERVER_PORT = 3773;
|
||||
const BASE_WEB_PORT = 5733;
|
||||
const MAX_HASH_OFFSET = 3000;
|
||||
const MAX_PORT = 65535;
|
||||
export const DEFAULT_DEV_STATE_DIR = path.join(homedir(), ".t3", "dev");
|
||||
const MODE_ARGS = {
|
||||
dev: [
|
||||
"run",
|
||||
"dev",
|
||||
"--ui=tui",
|
||||
"--filter=@t3tools/contracts",
|
||||
"--filter=@t3tools/web",
|
||||
"--filter=t3",
|
||||
"--parallel",
|
||||
],
|
||||
"dev:server": ["run", "dev", "--filter=t3"],
|
||||
"dev:web": ["run", "dev", "--filter=@t3tools/web"],
|
||||
"dev:desktop": ["run", "dev", "--filter=@t3tools/desktop", "--filter=@t3tools/web", "--parallel"],
|
||||
};
|
||||
const FORWARDED_ENV_FLAGS = {
|
||||
"state-dir": { envName: "T3CODE_STATE_DIR", expectsValue: true },
|
||||
"auth-token": { envName: "T3CODE_AUTH_TOKEN", expectsValue: true },
|
||||
token: { envName: "T3CODE_AUTH_TOKEN", expectsValue: true },
|
||||
"no-browser": { envName: "T3CODE_NO_BROWSER", expectsValue: false },
|
||||
"auto-bootstrap-project-from-cwd": {
|
||||
envName: "T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD",
|
||||
expectsValue: false,
|
||||
},
|
||||
"log-websocket-events": { envName: "T3CODE_LOG_WS_EVENTS", expectsValue: false },
|
||||
"log-ws-events": { envName: "T3CODE_LOG_WS_EVENTS", expectsValue: false },
|
||||
host: { envName: "T3CODE_HOST", expectsValue: true },
|
||||
port: { envName: "T3CODE_PORT", expectsValue: true },
|
||||
"dev-url": { envName: "VITE_DEV_SERVER_URL", expectsValue: true },
|
||||
};
|
||||
|
||||
function parseInteger(value, envName) {
|
||||
const parsed = Number(value);
|
||||
if (!Number.isInteger(parsed)) {
|
||||
throw new Error(`Invalid ${envName}: ${value}`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function hashSeed(seed) {
|
||||
let hash = 0x811c9dc5;
|
||||
for (let i = 0; i < seed.length; i += 1) {
|
||||
hash ^= seed.charCodeAt(i);
|
||||
hash = Math.imul(hash, 0x01000193);
|
||||
}
|
||||
return hash >>> 0;
|
||||
}
|
||||
|
||||
export function resolveOffset(env = process.env) {
|
||||
const explicitOffset = env.T3CODE_PORT_OFFSET?.trim();
|
||||
if (explicitOffset) {
|
||||
const parsed = parseInteger(explicitOffset, "T3CODE_PORT_OFFSET");
|
||||
if (parsed < 0) {
|
||||
throw new Error(`Invalid T3CODE_PORT_OFFSET: ${explicitOffset}`);
|
||||
}
|
||||
return { offset: parsed, source: `T3CODE_PORT_OFFSET=${explicitOffset}` };
|
||||
}
|
||||
|
||||
const seed = env.T3CODE_DEV_INSTANCE?.trim();
|
||||
if (!seed) {
|
||||
return { offset: 0, source: "default ports" };
|
||||
}
|
||||
|
||||
if (/^\d+$/.test(seed)) {
|
||||
return { offset: Number(seed), source: `numeric T3CODE_DEV_INSTANCE=${seed}` };
|
||||
}
|
||||
|
||||
const offset = (hashSeed(seed) % MAX_HASH_OFFSET) + 1;
|
||||
return { offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` };
|
||||
}
|
||||
|
||||
function parseLongFlag(raw) {
|
||||
if (!raw.startsWith("--")) return null;
|
||||
const normalized = raw.slice(2);
|
||||
const equalsIndex = normalized.indexOf("=");
|
||||
if (equalsIndex === -1) {
|
||||
return { name: normalized, value: undefined };
|
||||
}
|
||||
return {
|
||||
name: normalized.slice(0, equalsIndex),
|
||||
value: normalized.slice(equalsIndex + 1),
|
||||
};
|
||||
}
|
||||
|
||||
function toBooleanEnvValue(value) {
|
||||
if (value === undefined) return "1";
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (normalized === "false" || normalized === "0" || normalized === "no") return "0";
|
||||
return "1";
|
||||
}
|
||||
|
||||
export function parseDevRunnerArgs(rawArgs) {
|
||||
const args = rawArgs[0] === "--" ? rawArgs.slice(1) : rawArgs.slice();
|
||||
const envOverrides = {};
|
||||
const turboArgs = [];
|
||||
let isDryRun = false;
|
||||
|
||||
for (let index = 0; index < args.length; index += 1) {
|
||||
const arg = args[index];
|
||||
if (arg === "--dry-run") {
|
||||
isDryRun = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg === "--") {
|
||||
turboArgs.push(...args.slice(index + 1));
|
||||
break;
|
||||
}
|
||||
|
||||
const parsedFlag = parseLongFlag(arg);
|
||||
if (!parsedFlag) {
|
||||
turboArgs.push(arg);
|
||||
continue;
|
||||
}
|
||||
|
||||
const definition = FORWARDED_ENV_FLAGS[parsedFlag.name];
|
||||
if (!definition) {
|
||||
turboArgs.push(arg);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (definition.expectsValue) {
|
||||
let value = parsedFlag.value;
|
||||
if (value === undefined) {
|
||||
const next = args[index + 1];
|
||||
if (next === undefined || next === "--" || next.startsWith("-")) {
|
||||
throw new Error(`Missing value for --${parsedFlag.name}`);
|
||||
}
|
||||
value = next;
|
||||
index += 1;
|
||||
}
|
||||
envOverrides[definition.envName] = value;
|
||||
continue;
|
||||
}
|
||||
|
||||
envOverrides[definition.envName] = toBooleanEnvValue(parsedFlag.value);
|
||||
}
|
||||
|
||||
return {
|
||||
isDryRun,
|
||||
envOverrides,
|
||||
turboArgs,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveStateDir(env, envOverrides) {
|
||||
const overrideValue = envOverrides?.T3CODE_STATE_DIR?.trim();
|
||||
if (overrideValue) {
|
||||
// Resolve relative paths against cwd (monorepo root) before turbo changes directories
|
||||
return path.resolve(overrideValue);
|
||||
}
|
||||
|
||||
const envValue = env?.T3CODE_STATE_DIR?.trim();
|
||||
if (envValue) {
|
||||
return path.resolve(envValue);
|
||||
}
|
||||
|
||||
return DEFAULT_DEV_STATE_DIR;
|
||||
}
|
||||
|
||||
export function createDevRunnerEnv({ mode, env, offset, envOverrides }) {
|
||||
const serverPort = BASE_SERVER_PORT + offset;
|
||||
const webPort = BASE_WEB_PORT + offset;
|
||||
|
||||
const output = {
|
||||
...env,
|
||||
T3CODE_PORT: String(serverPort),
|
||||
PORT: String(webPort),
|
||||
ELECTRON_RENDERER_PORT: String(webPort),
|
||||
VITE_WS_URL: `ws://localhost:${serverPort}`,
|
||||
VITE_DEV_SERVER_URL: `http://localhost:${webPort}`,
|
||||
...envOverrides,
|
||||
};
|
||||
|
||||
output.T3CODE_STATE_DIR = resolveStateDir(env, envOverrides);
|
||||
|
||||
const parsedServerPort = Number(output.T3CODE_PORT);
|
||||
if (!Number.isInteger(parsedServerPort) || parsedServerPort < 1 || parsedServerPort > 65535) {
|
||||
throw new Error(
|
||||
`Invalid T3CODE_PORT override: '${String(output.T3CODE_PORT)}'. Expected an integer between 1 and 65535.`,
|
||||
);
|
||||
}
|
||||
output.VITE_WS_URL = `ws://localhost:${parsedServerPort}`;
|
||||
|
||||
if (mode === "dev" || mode === "dev:server" || mode === "dev:web") {
|
||||
// Running server/web in browser mode should not inherit desktop launcher state.
|
||||
output.T3CODE_MODE = "web";
|
||||
if (!("T3CODE_NO_BROWSER" in envOverrides)) {
|
||||
delete output.T3CODE_NO_BROWSER;
|
||||
}
|
||||
if (!("T3CODE_AUTH_TOKEN" in envOverrides)) {
|
||||
delete output.T3CODE_AUTH_TOKEN;
|
||||
}
|
||||
delete output.T3CODE_DESKTOP_WS_URL;
|
||||
}
|
||||
|
||||
if (mode === "dev" && !output.T3CODE_LOG_WS_EVENTS) {
|
||||
output.T3CODE_LOG_WS_EVENTS = "1";
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
function portPairForOffset(offset) {
|
||||
return {
|
||||
serverPort: BASE_SERVER_PORT + offset,
|
||||
webPort: BASE_WEB_PORT + offset,
|
||||
};
|
||||
}
|
||||
|
||||
async function canListenOnHost(port, host) {
|
||||
return await new Promise((resolve) => {
|
||||
const server = net.createServer();
|
||||
server.unref();
|
||||
server.once("error", (error) => {
|
||||
const code = error?.code;
|
||||
if (code === "EADDRNOTAVAIL") {
|
||||
// Host family unavailable on this machine (for example, no IPv6 loopback).
|
||||
resolve(true);
|
||||
return;
|
||||
}
|
||||
resolve(false);
|
||||
});
|
||||
server.once("listening", () => {
|
||||
server.close(() => {
|
||||
resolve(true);
|
||||
});
|
||||
});
|
||||
server.listen({ host, port });
|
||||
});
|
||||
}
|
||||
|
||||
async function isPortAvailable(port) {
|
||||
// Vite/dev traffic uses localhost loopback. Verify both IPv4 and IPv6 loopback
|
||||
// so we don't pick a port that fails later on one address family.
|
||||
const [ipv4, ipv6] = await Promise.all([
|
||||
canListenOnHost(port, "127.0.0.1"),
|
||||
canListenOnHost(port, "::1"),
|
||||
]);
|
||||
return ipv4 && ipv6;
|
||||
}
|
||||
|
||||
const defaultCheckPortAvailability = isPortAvailable;
|
||||
|
||||
export async function findFirstAvailableOffset({
|
||||
startOffset,
|
||||
requireServerPort,
|
||||
requireWebPort,
|
||||
checkPortAvailability = defaultCheckPortAvailability,
|
||||
}) {
|
||||
for (let candidate = startOffset; ; candidate += 1) {
|
||||
const { serverPort, webPort } = portPairForOffset(candidate);
|
||||
const serverPortOutOfRange = serverPort > MAX_PORT;
|
||||
const webPortOutOfRange = webPort > MAX_PORT;
|
||||
if (
|
||||
(requireServerPort && serverPortOutOfRange) ||
|
||||
(requireWebPort && webPortOutOfRange) ||
|
||||
(!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
|
||||
) {
|
||||
break;
|
||||
}
|
||||
|
||||
const checks = [];
|
||||
if (requireServerPort) {
|
||||
checks.push(checkPortAvailability(serverPort));
|
||||
}
|
||||
if (requireWebPort) {
|
||||
checks.push(checkPortAvailability(webPort));
|
||||
}
|
||||
|
||||
if (checks.length === 0) {
|
||||
return candidate;
|
||||
}
|
||||
|
||||
const availability = await Promise.all(checks);
|
||||
if (availability.every(Boolean)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`No available dev ports found from offset ${startOffset}. Tried server=${BASE_SERVER_PORT}+n web=${BASE_WEB_PORT}+n up to port ${MAX_PORT}.`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function resolveModePortOffsets({
|
||||
mode,
|
||||
startOffset,
|
||||
envOverrides,
|
||||
checkPortAvailability,
|
||||
}) {
|
||||
const hasExplicitServerPort = typeof envOverrides.T3CODE_PORT === "string";
|
||||
const hasExplicitDevUrl = typeof envOverrides.VITE_DEV_SERVER_URL === "string";
|
||||
|
||||
if (mode === "dev:web") {
|
||||
if (hasExplicitDevUrl) {
|
||||
return { serverOffset: startOffset, webOffset: startOffset };
|
||||
}
|
||||
const webOffset = await findFirstAvailableOffset({
|
||||
startOffset,
|
||||
requireServerPort: false,
|
||||
requireWebPort: true,
|
||||
checkPortAvailability,
|
||||
});
|
||||
return { serverOffset: startOffset, webOffset };
|
||||
}
|
||||
|
||||
if (mode === "dev:server") {
|
||||
if (hasExplicitServerPort) {
|
||||
return { serverOffset: startOffset, webOffset: startOffset };
|
||||
}
|
||||
const serverOffset = await findFirstAvailableOffset({
|
||||
startOffset,
|
||||
requireServerPort: true,
|
||||
requireWebPort: false,
|
||||
checkPortAvailability,
|
||||
});
|
||||
return { serverOffset, webOffset: serverOffset };
|
||||
}
|
||||
|
||||
const sharedOffset = await findFirstAvailableOffset({
|
||||
startOffset,
|
||||
requireServerPort: !hasExplicitServerPort,
|
||||
requireWebPort: !hasExplicitDevUrl,
|
||||
checkPortAvailability,
|
||||
});
|
||||
return { serverOffset: sharedOffset, webOffset: sharedOffset };
|
||||
}
|
||||
|
||||
export async function runDevRunner(argv = process.argv) {
|
||||
const mode = argv[2];
|
||||
const parsedArgs = parseDevRunnerArgs(argv.slice(3));
|
||||
if (!mode || !(mode in MODE_ARGS)) {
|
||||
const supportedModes = Object.keys(MODE_ARGS).join(", ");
|
||||
throw new Error(`Usage: bun scripts/dev-runner.mjs <mode>. Supported modes: ${supportedModes}`);
|
||||
}
|
||||
|
||||
const { offset, source } = resolveOffset();
|
||||
const { serverOffset, webOffset } = await resolveModePortOffsets({
|
||||
mode,
|
||||
startOffset: offset,
|
||||
envOverrides: parsedArgs.envOverrides,
|
||||
});
|
||||
|
||||
const mergedEnvOverrides = { ...parsedArgs.envOverrides };
|
||||
if (!("VITE_DEV_SERVER_URL" in mergedEnvOverrides)) {
|
||||
const { webPort } = portPairForOffset(webOffset);
|
||||
mergedEnvOverrides.PORT = String(webPort);
|
||||
mergedEnvOverrides.ELECTRON_RENDERER_PORT = String(webPort);
|
||||
mergedEnvOverrides.VITE_DEV_SERVER_URL = `http://localhost:${webPort}`;
|
||||
}
|
||||
|
||||
const env = createDevRunnerEnv({
|
||||
mode,
|
||||
env: process.env,
|
||||
offset: serverOffset,
|
||||
envOverrides: mergedEnvOverrides,
|
||||
});
|
||||
|
||||
const parsedServerPort = Number(env.T3CODE_PORT);
|
||||
const parsedWebPort = Number(env.PORT);
|
||||
if (
|
||||
!Number.isInteger(parsedServerPort) ||
|
||||
parsedServerPort < 1 ||
|
||||
parsedServerPort > MAX_PORT ||
|
||||
!Number.isInteger(parsedWebPort) ||
|
||||
parsedWebPort < 1 ||
|
||||
parsedWebPort > MAX_PORT
|
||||
) {
|
||||
throw new Error(
|
||||
`Invalid computed dev ports: server='${String(env.T3CODE_PORT)}' web='${String(env.PORT)}'.`,
|
||||
);
|
||||
}
|
||||
|
||||
const selectionSuffix =
|
||||
serverOffset !== offset || webOffset !== offset
|
||||
? ` selectedOffset(server=${serverOffset},web=${webOffset})`
|
||||
: "";
|
||||
|
||||
console.info(
|
||||
`[dev-runner] mode=${mode} source=${source}${selectionSuffix} serverPort=${parsedServerPort} webPort=${parsedWebPort} stateDir=${env.T3CODE_STATE_DIR}`,
|
||||
);
|
||||
|
||||
if (parsedArgs.isDryRun) {
|
||||
return;
|
||||
}
|
||||
|
||||
const command = process.platform === "win32" ? "turbo.cmd" : "turbo";
|
||||
const child = spawn(command, [...MODE_ARGS[mode], ...parsedArgs.turboArgs], {
|
||||
stdio: "inherit",
|
||||
env,
|
||||
});
|
||||
|
||||
child.on("exit", (code, signal) => {
|
||||
if (signal) {
|
||||
process.kill(process.pid, signal);
|
||||
return;
|
||||
}
|
||||
process.exit(code ?? 0);
|
||||
});
|
||||
|
||||
child.on("error", (error) => {
|
||||
console.error("[dev-runner] failed to start turbo", error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
const entrypointPath = process.argv[1] ? pathToFileURL(process.argv[1]).href : "";
|
||||
|
||||
if (import.meta.url === entrypointPath) {
|
||||
runDevRunner().catch((error) => {
|
||||
console.error("[dev-runner]", error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
+203
-208
@@ -1,223 +1,218 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { resolve } from "node:path";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect } from "effect";
|
||||
|
||||
import {
|
||||
DEFAULT_DEV_STATE_DIR,
|
||||
createDevRunnerEnv,
|
||||
findFirstAvailableOffset,
|
||||
parseDevRunnerArgs,
|
||||
resolveModePortOffsets,
|
||||
} from "./dev-runner.mjs";
|
||||
resolveOffset,
|
||||
} from "./dev-runner.ts";
|
||||
|
||||
describe("parseDevRunnerArgs", () => {
|
||||
it("maps supported server flags to env overrides and keeps other flags for turbo", () => {
|
||||
const parsed = parseDevRunnerArgs([
|
||||
"--",
|
||||
"--state-dir",
|
||||
"~/alt-state",
|
||||
"--token=abc123",
|
||||
"--no-browser=false",
|
||||
"--dry-run",
|
||||
"--continue",
|
||||
]);
|
||||
it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
describe("resolveOffset", () => {
|
||||
it.effect("uses explicit T3CODE_PORT_OFFSET when provided", () =>
|
||||
Effect.sync(() => {
|
||||
const result = resolveOffset({ portOffset: 12, devInstance: undefined });
|
||||
assert.deepStrictEqual(result, {
|
||||
offset: 12,
|
||||
source: "T3CODE_PORT_OFFSET=12",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
expect(parsed.isDryRun).toBe(true);
|
||||
expect(parsed.envOverrides).toEqual({
|
||||
T3CODE_STATE_DIR: "~/alt-state",
|
||||
T3CODE_AUTH_TOKEN: "abc123",
|
||||
T3CODE_NO_BROWSER: "0",
|
||||
});
|
||||
expect(parsed.turboArgs).toEqual(["--continue"]);
|
||||
it.effect("hashes non-numeric instance values", () =>
|
||||
Effect.sync(() => {
|
||||
const result = resolveOffset({ portOffset: undefined, devInstance: "feature-branch" });
|
||||
assert.ok(result.offset >= 1);
|
||||
assert.ok(result.offset <= 3000);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("throws for negative port offset", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
Effect.try({
|
||||
try: () => resolveOffset({ portOffset: -1, devInstance: undefined }),
|
||||
catch: (cause) => String(cause),
|
||||
}),
|
||||
);
|
||||
|
||||
assert.ok(error.includes("Invalid T3CODE_PORT_OFFSET"));
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("throws when a value flag is missing its value", () => {
|
||||
expect(() => parseDevRunnerArgs(["--state-dir"])).toThrow("Missing value for --state-dir");
|
||||
describe("createDevRunnerEnv", () => {
|
||||
it.effect("defaults state dir to ~/.t3/dev when not provided", () =>
|
||||
Effect.gen(function* () {
|
||||
const [env, defaultStateDir] = yield* Effect.all([
|
||||
createDevRunnerEnv({
|
||||
mode: "dev",
|
||||
baseEnv: {},
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
stateDir: undefined,
|
||||
authToken: undefined,
|
||||
noBrowser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: undefined,
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
}),
|
||||
DEFAULT_DEV_STATE_DIR,
|
||||
]);
|
||||
|
||||
assert.equal(env.T3CODE_STATE_DIR, defaultStateDir);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("supports explicit typed overrides", () =>
|
||||
Effect.gen(function* () {
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode: "dev:server",
|
||||
baseEnv: {},
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
stateDir: "/tmp/override-state",
|
||||
authToken: "secret",
|
||||
noBrowser: true,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: true,
|
||||
host: "0.0.0.0",
|
||||
port: 4222,
|
||||
devUrl: new URL("http://localhost:7331"),
|
||||
});
|
||||
|
||||
assert.equal(env.T3CODE_STATE_DIR, resolve("/tmp/override-state"));
|
||||
assert.equal(env.T3CODE_PORT, "4222");
|
||||
assert.equal(env.VITE_WS_URL, "ws://localhost:4222");
|
||||
assert.equal(env.T3CODE_NO_BROWSER, "1");
|
||||
assert.equal(env.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD, "0");
|
||||
assert.equal(env.T3CODE_LOG_WS_EVENTS, "1");
|
||||
assert.equal(env.T3CODE_HOST, "0.0.0.0");
|
||||
assert.equal(env.VITE_DEV_SERVER_URL, "http://localhost:7331/");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("throws when a value flag is followed by another flag token", () => {
|
||||
expect(() => parseDevRunnerArgs(["--state-dir", "--continue"])).toThrow(
|
||||
"Missing value for --state-dir",
|
||||
describe("findFirstAvailableOffset", () => {
|
||||
it.effect("returns the starting offset when required ports are available", () =>
|
||||
Effect.gen(function* () {
|
||||
const offset = yield* findFirstAvailableOffset({
|
||||
startOffset: 0,
|
||||
requireServerPort: true,
|
||||
requireWebPort: true,
|
||||
checkPortAvailability: () => Effect.succeed(true),
|
||||
});
|
||||
|
||||
assert.equal(offset, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("advances until all required ports are available", () =>
|
||||
Effect.gen(function* () {
|
||||
const taken = new Set([3773, 5733, 3774, 5734]);
|
||||
const offset = yield* findFirstAvailableOffset({
|
||||
startOffset: 0,
|
||||
requireServerPort: true,
|
||||
requireWebPort: true,
|
||||
checkPortAvailability: (port) => Effect.succeed(!taken.has(port)),
|
||||
});
|
||||
|
||||
assert.equal(offset, 2);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("allows offsets where only non-required ports exceed max", () =>
|
||||
Effect.gen(function* () {
|
||||
const offset = yield* findFirstAvailableOffset({
|
||||
startOffset: 59_803,
|
||||
requireServerPort: true,
|
||||
requireWebPort: false,
|
||||
checkPortAvailability: () => Effect.succeed(true),
|
||||
});
|
||||
|
||||
assert.equal(offset, 59_803);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("resolveModePortOffsets", () => {
|
||||
it.effect("uses a shared fallback offset for dev mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const taken = new Set([3773, 5733]);
|
||||
const offsets = yield* resolveModePortOffsets({
|
||||
mode: "dev",
|
||||
startOffset: 0,
|
||||
hasExplicitServerPort: false,
|
||||
hasExplicitDevUrl: false,
|
||||
checkPortAvailability: (port) => Effect.succeed(!taken.has(port)),
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(offsets, { serverOffset: 1, webOffset: 1 });
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps server offset stable for dev:web and only shifts web offset", () =>
|
||||
Effect.gen(function* () {
|
||||
const taken = new Set([5733]);
|
||||
const offsets = yield* resolveModePortOffsets({
|
||||
mode: "dev:web",
|
||||
startOffset: 0,
|
||||
hasExplicitServerPort: false,
|
||||
hasExplicitDevUrl: false,
|
||||
checkPortAvailability: (port) => Effect.succeed(!taken.has(port)),
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(offsets, { serverOffset: 0, webOffset: 1 });
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("shifts only server offset for dev:server", () =>
|
||||
Effect.gen(function* () {
|
||||
const taken = new Set([3773]);
|
||||
const offsets = yield* resolveModePortOffsets({
|
||||
mode: "dev:server",
|
||||
startOffset: 0,
|
||||
hasExplicitServerPort: false,
|
||||
hasExplicitDevUrl: false,
|
||||
checkPortAvailability: (port) => Effect.succeed(!taken.has(port)),
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(offsets, { serverOffset: 1, webOffset: 1 });
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("respects explicit dev-url override for dev:web", () =>
|
||||
Effect.gen(function* () {
|
||||
const offsets = yield* resolveModePortOffsets({
|
||||
mode: "dev:web",
|
||||
startOffset: 0,
|
||||
hasExplicitServerPort: false,
|
||||
hasExplicitDevUrl: true,
|
||||
checkPortAvailability: () => Effect.succeed(false),
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(offsets, { serverOffset: 0, webOffset: 0 });
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("respects explicit server port override for dev:server", () =>
|
||||
Effect.gen(function* () {
|
||||
const offsets = yield* resolveModePortOffsets({
|
||||
mode: "dev:server",
|
||||
startOffset: 0,
|
||||
hasExplicitServerPort: true,
|
||||
hasExplicitDevUrl: false,
|
||||
checkPortAvailability: () => Effect.succeed(false),
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(offsets, { serverOffset: 0, webOffset: 0 });
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createDevRunnerEnv", () => {
|
||||
it("defaults state dir to ~/.t3/dev when not provided", () => {
|
||||
const env = createDevRunnerEnv({
|
||||
mode: "dev",
|
||||
env: {},
|
||||
offset: 0,
|
||||
envOverrides: {},
|
||||
});
|
||||
|
||||
expect(env.T3CODE_STATE_DIR).toBe(DEFAULT_DEV_STATE_DIR);
|
||||
});
|
||||
|
||||
it("uses existing env state dir when --state-dir is not provided", () => {
|
||||
const env = createDevRunnerEnv({
|
||||
mode: "dev:server",
|
||||
env: { T3CODE_STATE_DIR: "/tmp/existing-state" },
|
||||
offset: 0,
|
||||
envOverrides: {},
|
||||
});
|
||||
|
||||
expect(env.T3CODE_STATE_DIR).toBe("/tmp/existing-state");
|
||||
});
|
||||
|
||||
it("lets --state-dir override existing env state dir", () => {
|
||||
const env = createDevRunnerEnv({
|
||||
mode: "dev:server",
|
||||
env: { T3CODE_STATE_DIR: "/tmp/existing-state" },
|
||||
offset: 0,
|
||||
envOverrides: { T3CODE_STATE_DIR: "/tmp/override-state" },
|
||||
});
|
||||
|
||||
expect(env.T3CODE_STATE_DIR).toBe("/tmp/override-state");
|
||||
});
|
||||
|
||||
it("treats whitespace-only --state-dir as missing and falls back to env/default", () => {
|
||||
const env = createDevRunnerEnv({
|
||||
mode: "dev:server",
|
||||
env: { T3CODE_STATE_DIR: "/tmp/existing-state" },
|
||||
offset: 0,
|
||||
envOverrides: { T3CODE_STATE_DIR: " " },
|
||||
});
|
||||
|
||||
expect(env.T3CODE_STATE_DIR).toBe("/tmp/existing-state");
|
||||
});
|
||||
|
||||
it("recomputes websocket url when port is overridden", () => {
|
||||
const env = createDevRunnerEnv({
|
||||
mode: "dev",
|
||||
env: {},
|
||||
offset: 0,
|
||||
envOverrides: { T3CODE_PORT: "4222" },
|
||||
});
|
||||
|
||||
expect(env.T3CODE_PORT).toBe("4222");
|
||||
expect(env.VITE_WS_URL).toBe("ws://localhost:4222");
|
||||
});
|
||||
|
||||
it("keeps explicitly forwarded web-mode flags", () => {
|
||||
const env = createDevRunnerEnv({
|
||||
mode: "dev",
|
||||
env: {
|
||||
T3CODE_AUTH_TOKEN: "desktop-token",
|
||||
},
|
||||
offset: 0,
|
||||
envOverrides: {
|
||||
T3CODE_NO_BROWSER: "1",
|
||||
T3CODE_AUTH_TOKEN: "cli-token",
|
||||
},
|
||||
});
|
||||
|
||||
expect(env.T3CODE_NO_BROWSER).toBe("1");
|
||||
expect(env.T3CODE_AUTH_TOKEN).toBe("cli-token");
|
||||
});
|
||||
|
||||
it("fails fast for invalid port overrides", () => {
|
||||
expect(() =>
|
||||
createDevRunnerEnv({
|
||||
mode: "dev",
|
||||
env: {},
|
||||
offset: 0,
|
||||
envOverrides: { T3CODE_PORT: "not-a-port" },
|
||||
}),
|
||||
).toThrow("Invalid T3CODE_PORT override");
|
||||
});
|
||||
});
|
||||
|
||||
describe("findFirstAvailableOffset", () => {
|
||||
it("returns the starting offset when required ports are available", async () => {
|
||||
const offset = await findFirstAvailableOffset({
|
||||
startOffset: 0,
|
||||
requireServerPort: true,
|
||||
requireWebPort: true,
|
||||
checkPortAvailability: async () => true,
|
||||
});
|
||||
|
||||
expect(offset).toBe(0);
|
||||
});
|
||||
|
||||
it("advances until all required ports are available", async () => {
|
||||
const taken = new Set([3773, 5733, 3774, 5734]);
|
||||
const offset = await findFirstAvailableOffset({
|
||||
startOffset: 0,
|
||||
requireServerPort: true,
|
||||
requireWebPort: true,
|
||||
checkPortAvailability: async (port) => !taken.has(port),
|
||||
});
|
||||
|
||||
expect(offset).toBe(2);
|
||||
});
|
||||
|
||||
it("allows offsets where only non-required ports exceed max", async () => {
|
||||
const offset = await findFirstAvailableOffset({
|
||||
startOffset: 59_803,
|
||||
requireServerPort: true,
|
||||
requireWebPort: false,
|
||||
checkPortAvailability: async () => true,
|
||||
});
|
||||
|
||||
expect(offset).toBe(59_803);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveModePortOffsets", () => {
|
||||
it("uses a shared fallback offset for dev mode", async () => {
|
||||
const taken = new Set([3773, 5733]);
|
||||
const offsets = await resolveModePortOffsets({
|
||||
mode: "dev",
|
||||
startOffset: 0,
|
||||
envOverrides: {},
|
||||
checkPortAvailability: async (port) => !taken.has(port),
|
||||
});
|
||||
|
||||
expect(offsets).toEqual({ serverOffset: 1, webOffset: 1 });
|
||||
});
|
||||
|
||||
it("keeps server offset stable for dev:web and only shifts web offset", async () => {
|
||||
const taken = new Set([5733]);
|
||||
const offsets = await resolveModePortOffsets({
|
||||
mode: "dev:web",
|
||||
startOffset: 0,
|
||||
envOverrides: {},
|
||||
checkPortAvailability: async (port) => !taken.has(port),
|
||||
});
|
||||
|
||||
expect(offsets).toEqual({ serverOffset: 0, webOffset: 1 });
|
||||
});
|
||||
|
||||
it("shifts only server offset for dev:server", async () => {
|
||||
const taken = new Set([3773]);
|
||||
const offsets = await resolveModePortOffsets({
|
||||
mode: "dev:server",
|
||||
startOffset: 0,
|
||||
envOverrides: {},
|
||||
checkPortAvailability: async (port) => !taken.has(port),
|
||||
});
|
||||
|
||||
expect(offsets).toEqual({ serverOffset: 1, webOffset: 1 });
|
||||
});
|
||||
|
||||
it("respects explicit dev-url override for dev:web", async () => {
|
||||
const offsets = await resolveModePortOffsets({
|
||||
mode: "dev:web",
|
||||
startOffset: 0,
|
||||
envOverrides: { VITE_DEV_SERVER_URL: "http://localhost:9999" },
|
||||
checkPortAvailability: async () => false,
|
||||
});
|
||||
|
||||
expect(offsets).toEqual({ serverOffset: 0, webOffset: 0 });
|
||||
});
|
||||
|
||||
it("respects explicit server port override for dev:server", async () => {
|
||||
const offsets = await resolveModePortOffsets({
|
||||
mode: "dev:server",
|
||||
startOffset: 0,
|
||||
envOverrides: { T3CODE_PORT: "4888" },
|
||||
checkPortAvailability: async () => false,
|
||||
});
|
||||
|
||||
expect(offsets).toEqual({ serverOffset: 0, webOffset: 0 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,507 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { homedir } from "node:os";
|
||||
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { Config, Data, Effect, Hash, Layer, Logger, Option, Path, Schema } from "effect";
|
||||
import { Argument, Command, Flag } from "effect/unstable/cli";
|
||||
import { ChildProcess } from "effect/unstable/process";
|
||||
|
||||
const BASE_SERVER_PORT = 3773;
|
||||
const BASE_WEB_PORT = 5733;
|
||||
const MAX_HASH_OFFSET = 3000;
|
||||
const MAX_PORT = 65535;
|
||||
|
||||
export const DEFAULT_DEV_STATE_DIR = Effect.map(Effect.service(Path.Path), (path) =>
|
||||
path.join(homedir(), ".t3", "dev"),
|
||||
);
|
||||
|
||||
const MODE_ARGS = {
|
||||
dev: [
|
||||
"run",
|
||||
"dev",
|
||||
"--ui=tui",
|
||||
"--filter=@t3tools/contracts",
|
||||
"--filter=@t3tools/web",
|
||||
"--filter=t3",
|
||||
"--parallel",
|
||||
],
|
||||
"dev:server": ["run", "dev", "--filter=t3"],
|
||||
"dev:web": ["run", "dev", "--filter=@t3tools/web"],
|
||||
"dev:desktop": ["run", "dev", "--filter=@t3tools/desktop", "--filter=@t3tools/web", "--parallel"],
|
||||
} as const satisfies Record<string, ReadonlyArray<string>>;
|
||||
|
||||
type DevMode = keyof typeof MODE_ARGS;
|
||||
type PortAvailabilityCheck<R = never> = (port: number) => Effect.Effect<boolean, never, R>;
|
||||
|
||||
const DEV_RUNNER_MODES = Object.keys(MODE_ARGS) as Array<DevMode>;
|
||||
|
||||
class DevRunnerError extends Data.TaggedError("DevRunnerError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
const optionalStringConfig = (name: string): Config.Config<string | undefined> =>
|
||||
Config.string(name).pipe(
|
||||
Config.option,
|
||||
Config.map((value) => Option.getOrUndefined(value)),
|
||||
);
|
||||
const optionalBooleanConfig = (name: string): Config.Config<boolean | undefined> =>
|
||||
Config.boolean(name).pipe(
|
||||
Config.option,
|
||||
Config.map((value) => Option.getOrUndefined(value)),
|
||||
);
|
||||
const optionalPortConfig = (name: string): Config.Config<number | undefined> =>
|
||||
Config.port(name).pipe(
|
||||
Config.option,
|
||||
Config.map((value) => Option.getOrUndefined(value)),
|
||||
);
|
||||
const optionalIntegerConfig = (name: string): Config.Config<number | undefined> =>
|
||||
Config.int(name).pipe(
|
||||
Config.option,
|
||||
Config.map((value) => Option.getOrUndefined(value)),
|
||||
);
|
||||
const optionalUrlConfig = (name: string): Config.Config<URL | undefined> =>
|
||||
Config.url(name).pipe(
|
||||
Config.option,
|
||||
Config.map((value) => Option.getOrUndefined(value)),
|
||||
);
|
||||
|
||||
const OffsetConfig = Config.all({
|
||||
portOffset: optionalIntegerConfig("T3CODE_PORT_OFFSET"),
|
||||
devInstance: optionalStringConfig("T3CODE_DEV_INSTANCE"),
|
||||
});
|
||||
|
||||
export function resolveOffset(config: {
|
||||
readonly portOffset: number | undefined;
|
||||
readonly devInstance: string | undefined;
|
||||
}): { readonly offset: number; readonly source: string } {
|
||||
if (config.portOffset !== undefined) {
|
||||
if (config.portOffset < 0) {
|
||||
throw new Error(`Invalid T3CODE_PORT_OFFSET: ${config.portOffset}`);
|
||||
}
|
||||
return {
|
||||
offset: config.portOffset,
|
||||
source: `T3CODE_PORT_OFFSET=${config.portOffset}`,
|
||||
};
|
||||
}
|
||||
|
||||
const seed = config.devInstance?.trim();
|
||||
if (!seed) {
|
||||
return { offset: 0, source: "default ports" };
|
||||
}
|
||||
|
||||
if (/^\d+$/.test(seed)) {
|
||||
return { offset: Number(seed), source: `numeric T3CODE_DEV_INSTANCE=${seed}` };
|
||||
}
|
||||
|
||||
const offset = ((Hash.string(seed) >>> 0) % MAX_HASH_OFFSET) + 1;
|
||||
return { offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` };
|
||||
}
|
||||
|
||||
function resolveStateDir(stateDir: string | undefined): Effect.Effect<string, never, Path.Path> {
|
||||
return Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const configured = stateDir?.trim();
|
||||
|
||||
if (configured) {
|
||||
// Resolve relative paths against cwd (monorepo root) before turbo changes directories.
|
||||
return path.resolve(configured);
|
||||
}
|
||||
|
||||
return yield* DEFAULT_DEV_STATE_DIR;
|
||||
});
|
||||
}
|
||||
|
||||
interface CreateDevRunnerEnvInput {
|
||||
readonly mode: DevMode;
|
||||
readonly baseEnv: NodeJS.ProcessEnv;
|
||||
readonly serverOffset: number;
|
||||
readonly webOffset: number;
|
||||
readonly stateDir: string | undefined;
|
||||
readonly authToken: string | undefined;
|
||||
readonly noBrowser: boolean | undefined;
|
||||
readonly autoBootstrapProjectFromCwd: boolean | undefined;
|
||||
readonly logWebSocketEvents: boolean | undefined;
|
||||
readonly host: string | undefined;
|
||||
readonly port: number | undefined;
|
||||
readonly devUrl: URL | undefined;
|
||||
}
|
||||
|
||||
export function createDevRunnerEnv({
|
||||
mode,
|
||||
baseEnv,
|
||||
serverOffset,
|
||||
webOffset,
|
||||
stateDir,
|
||||
authToken,
|
||||
noBrowser,
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
host,
|
||||
port,
|
||||
devUrl,
|
||||
}: CreateDevRunnerEnvInput): Effect.Effect<NodeJS.ProcessEnv, never, Path.Path> {
|
||||
return Effect.gen(function* () {
|
||||
const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
|
||||
const webPort = BASE_WEB_PORT + webOffset;
|
||||
const resolvedStateDir = yield* resolveStateDir(stateDir);
|
||||
|
||||
const output: NodeJS.ProcessEnv = {
|
||||
...baseEnv,
|
||||
T3CODE_PORT: String(serverPort),
|
||||
PORT: String(webPort),
|
||||
ELECTRON_RENDERER_PORT: String(webPort),
|
||||
VITE_WS_URL: `ws://localhost:${serverPort}`,
|
||||
VITE_DEV_SERVER_URL: devUrl?.toString() ?? `http://localhost:${webPort}`,
|
||||
T3CODE_STATE_DIR: resolvedStateDir,
|
||||
};
|
||||
|
||||
if (host !== undefined) {
|
||||
output.T3CODE_HOST = host;
|
||||
}
|
||||
|
||||
if (authToken !== undefined) {
|
||||
output.T3CODE_AUTH_TOKEN = authToken;
|
||||
} else {
|
||||
delete output.T3CODE_AUTH_TOKEN;
|
||||
}
|
||||
|
||||
if (noBrowser !== undefined) {
|
||||
output.T3CODE_NO_BROWSER = noBrowser ? "1" : "0";
|
||||
} else {
|
||||
delete output.T3CODE_NO_BROWSER;
|
||||
}
|
||||
|
||||
if (autoBootstrapProjectFromCwd !== undefined) {
|
||||
output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD = autoBootstrapProjectFromCwd ? "1" : "0";
|
||||
} else {
|
||||
delete output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD;
|
||||
}
|
||||
|
||||
if (logWebSocketEvents !== undefined) {
|
||||
output.T3CODE_LOG_WS_EVENTS = logWebSocketEvents ? "1" : "0";
|
||||
} else {
|
||||
delete output.T3CODE_LOG_WS_EVENTS;
|
||||
}
|
||||
|
||||
if (mode === "dev") {
|
||||
output.T3CODE_MODE = "web";
|
||||
if (logWebSocketEvents === undefined) {
|
||||
output.T3CODE_LOG_WS_EVENTS = "1";
|
||||
}
|
||||
delete output.T3CODE_DESKTOP_WS_URL;
|
||||
}
|
||||
|
||||
if (mode === "dev:server" || mode === "dev:web") {
|
||||
output.T3CODE_MODE = "web";
|
||||
delete output.T3CODE_DESKTOP_WS_URL;
|
||||
}
|
||||
|
||||
return output;
|
||||
});
|
||||
}
|
||||
|
||||
function portPairForOffset(offset: number): {
|
||||
readonly serverPort: number;
|
||||
readonly webPort: number;
|
||||
} {
|
||||
return {
|
||||
serverPort: BASE_SERVER_PORT + offset,
|
||||
webPort: BASE_WEB_PORT + offset,
|
||||
};
|
||||
}
|
||||
|
||||
const defaultCheckPortAvailability: PortAvailabilityCheck<NetService> = (port) =>
|
||||
Effect.gen(function* () {
|
||||
const net = yield* NetService;
|
||||
return yield* net.isPortAvailableOnLoopback(port);
|
||||
});
|
||||
|
||||
interface FindFirstAvailableOffsetInput<R = NetService> {
|
||||
readonly startOffset: number;
|
||||
readonly requireServerPort: boolean;
|
||||
readonly requireWebPort: boolean;
|
||||
readonly checkPortAvailability?: PortAvailabilityCheck<R>;
|
||||
}
|
||||
|
||||
export function findFirstAvailableOffset<R = NetService>({
|
||||
startOffset,
|
||||
requireServerPort,
|
||||
requireWebPort,
|
||||
checkPortAvailability,
|
||||
}: FindFirstAvailableOffsetInput<R>): Effect.Effect<number, DevRunnerError, R> {
|
||||
return Effect.gen(function* () {
|
||||
const checkPort = (checkPortAvailability ??
|
||||
defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
|
||||
|
||||
for (let candidate = startOffset; ; candidate += 1) {
|
||||
const { serverPort, webPort } = portPairForOffset(candidate);
|
||||
const serverPortOutOfRange = serverPort > MAX_PORT;
|
||||
const webPortOutOfRange = webPort > MAX_PORT;
|
||||
|
||||
if (
|
||||
(requireServerPort && serverPortOutOfRange) ||
|
||||
(requireWebPort && webPortOutOfRange) ||
|
||||
(!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
|
||||
) {
|
||||
break;
|
||||
}
|
||||
|
||||
const checks: Array<Effect.Effect<boolean, never, R>> = [];
|
||||
if (requireServerPort) {
|
||||
checks.push(checkPort(serverPort));
|
||||
}
|
||||
if (requireWebPort) {
|
||||
checks.push(checkPort(webPort));
|
||||
}
|
||||
|
||||
if (checks.length === 0) {
|
||||
return candidate;
|
||||
}
|
||||
|
||||
const availability = yield* Effect.all(checks);
|
||||
if (availability.every(Boolean)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return yield* new DevRunnerError({
|
||||
message: `No available dev ports found from offset ${startOffset}. Tried server=${BASE_SERVER_PORT}+n web=${BASE_WEB_PORT}+n up to port ${MAX_PORT}.`,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
interface ResolveModePortOffsetsInput<R = NetService> {
|
||||
readonly mode: DevMode;
|
||||
readonly startOffset: number;
|
||||
readonly hasExplicitServerPort: boolean;
|
||||
readonly hasExplicitDevUrl: boolean;
|
||||
readonly checkPortAvailability?: PortAvailabilityCheck<R>;
|
||||
}
|
||||
|
||||
export function resolveModePortOffsets<R = NetService>({
|
||||
mode,
|
||||
startOffset,
|
||||
hasExplicitServerPort,
|
||||
hasExplicitDevUrl,
|
||||
checkPortAvailability,
|
||||
}: ResolveModePortOffsetsInput<R>): Effect.Effect<
|
||||
{ readonly serverOffset: number; readonly webOffset: number },
|
||||
DevRunnerError,
|
||||
R
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const checkPort = (checkPortAvailability ??
|
||||
defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
|
||||
|
||||
if (mode === "dev:web") {
|
||||
if (hasExplicitDevUrl) {
|
||||
return { serverOffset: startOffset, webOffset: startOffset };
|
||||
}
|
||||
|
||||
const webOffset = yield* findFirstAvailableOffset({
|
||||
startOffset,
|
||||
requireServerPort: false,
|
||||
requireWebPort: true,
|
||||
checkPortAvailability: checkPort,
|
||||
});
|
||||
return { serverOffset: startOffset, webOffset };
|
||||
}
|
||||
|
||||
if (mode === "dev:server") {
|
||||
if (hasExplicitServerPort) {
|
||||
return { serverOffset: startOffset, webOffset: startOffset };
|
||||
}
|
||||
|
||||
const serverOffset = yield* findFirstAvailableOffset({
|
||||
startOffset,
|
||||
requireServerPort: true,
|
||||
requireWebPort: false,
|
||||
checkPortAvailability: checkPort,
|
||||
});
|
||||
return { serverOffset, webOffset: serverOffset };
|
||||
}
|
||||
|
||||
const sharedOffset = yield* findFirstAvailableOffset({
|
||||
startOffset,
|
||||
requireServerPort: !hasExplicitServerPort,
|
||||
requireWebPort: !hasExplicitDevUrl,
|
||||
checkPortAvailability: checkPort,
|
||||
});
|
||||
|
||||
return { serverOffset: sharedOffset, webOffset: sharedOffset };
|
||||
});
|
||||
}
|
||||
|
||||
interface DevRunnerCliInput {
|
||||
readonly mode: DevMode;
|
||||
readonly stateDir: string | undefined;
|
||||
readonly authToken: string | undefined;
|
||||
readonly noBrowser: boolean | undefined;
|
||||
readonly autoBootstrapProjectFromCwd: boolean | undefined;
|
||||
readonly logWebSocketEvents: boolean | undefined;
|
||||
readonly host: string | undefined;
|
||||
readonly port: number | undefined;
|
||||
readonly devUrl: URL | undefined;
|
||||
readonly dryRun: boolean;
|
||||
readonly turboArgs: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
export function runDevRunnerWithInput(input: DevRunnerCliInput) {
|
||||
return Effect.gen(function* () {
|
||||
const { portOffset, devInstance } = yield* OffsetConfig.asEffect().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DevRunnerError({
|
||||
message: "Failed to read T3CODE_PORT_OFFSET/T3CODE_DEV_INSTANCE configuration.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const { offset, source } = yield* Effect.try({
|
||||
try: () => resolveOffset({ portOffset, devInstance }),
|
||||
catch: (cause) =>
|
||||
new DevRunnerError({
|
||||
message: cause instanceof Error ? cause.message : String(cause),
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
const { serverOffset, webOffset } = yield* resolveModePortOffsets({
|
||||
mode: input.mode,
|
||||
startOffset: offset,
|
||||
hasExplicitServerPort: input.port !== undefined,
|
||||
hasExplicitDevUrl: input.devUrl !== undefined,
|
||||
});
|
||||
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode: input.mode,
|
||||
baseEnv: process.env,
|
||||
serverOffset,
|
||||
webOffset,
|
||||
stateDir: input.stateDir,
|
||||
authToken: input.authToken,
|
||||
noBrowser: input.noBrowser,
|
||||
autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents: input.logWebSocketEvents,
|
||||
host: input.host,
|
||||
port: input.port,
|
||||
devUrl: input.devUrl,
|
||||
});
|
||||
|
||||
const selectionSuffix =
|
||||
serverOffset !== offset || webOffset !== offset
|
||||
? ` selectedOffset(server=${serverOffset},web=${webOffset})`
|
||||
: "";
|
||||
|
||||
yield* Effect.logInfo(
|
||||
`[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} stateDir=${String(env.T3CODE_STATE_DIR)}`,
|
||||
);
|
||||
|
||||
if (input.dryRun) {
|
||||
return;
|
||||
}
|
||||
|
||||
const child = yield* ChildProcess.make(
|
||||
"turbo",
|
||||
[...MODE_ARGS[input.mode], ...input.turboArgs],
|
||||
{
|
||||
stdin: "inherit",
|
||||
stdout: "inherit",
|
||||
stderr: "inherit",
|
||||
env,
|
||||
extendEnv: false,
|
||||
},
|
||||
);
|
||||
|
||||
const exitCode = yield* child.exitCode;
|
||||
if (exitCode !== 0) {
|
||||
return yield* new DevRunnerError({
|
||||
message: `turbo exited with code ${exitCode}`,
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause instanceof DevRunnerError
|
||||
? cause
|
||||
: new DevRunnerError({
|
||||
message: cause instanceof Error ? cause.message : "dev-runner failed",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const devRunnerCli = Command.make("dev-runner", {
|
||||
mode: Argument.choice("mode", DEV_RUNNER_MODES).pipe(
|
||||
Argument.withDescription("Development mode to run."),
|
||||
),
|
||||
stateDir: Flag.string("state-dir").pipe(
|
||||
Flag.withDescription("State directory path (forwards to T3CODE_STATE_DIR)."),
|
||||
Flag.withFallbackConfig(optionalStringConfig("T3CODE_STATE_DIR")),
|
||||
),
|
||||
authToken: Flag.string("auth-token").pipe(
|
||||
Flag.withDescription("Auth token (forwards to T3CODE_AUTH_TOKEN)."),
|
||||
Flag.withAlias("token"),
|
||||
Flag.withFallbackConfig(optionalStringConfig("T3CODE_AUTH_TOKEN")),
|
||||
),
|
||||
noBrowser: Flag.boolean("no-browser").pipe(
|
||||
Flag.withDescription("Browser auto-open toggle (equivalent to T3CODE_NO_BROWSER)."),
|
||||
Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_NO_BROWSER")),
|
||||
),
|
||||
autoBootstrapProjectFromCwd: Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
|
||||
Flag.withDescription(
|
||||
"Auto-bootstrap toggle (equivalent to T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).",
|
||||
),
|
||||
Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD")),
|
||||
),
|
||||
logWebSocketEvents: Flag.boolean("log-websocket-events").pipe(
|
||||
Flag.withDescription("WebSocket event logging toggle (equivalent to T3CODE_LOG_WS_EVENTS)."),
|
||||
Flag.withAlias("log-ws-events"),
|
||||
Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_LOG_WS_EVENTS")),
|
||||
),
|
||||
host: Flag.string("host").pipe(
|
||||
Flag.withDescription("Server host/interface override (forwards to T3CODE_HOST)."),
|
||||
Flag.withFallbackConfig(optionalStringConfig("T3CODE_HOST")),
|
||||
),
|
||||
port: Flag.integer("port").pipe(
|
||||
Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
|
||||
Flag.withDescription("Server port override (forwards to T3CODE_PORT)."),
|
||||
Flag.withFallbackConfig(optionalPortConfig("T3CODE_PORT")),
|
||||
),
|
||||
devUrl: Flag.string("dev-url").pipe(
|
||||
Flag.withSchema(Schema.URLFromString),
|
||||
Flag.withDescription("Web dev URL override (forwards to VITE_DEV_SERVER_URL)."),
|
||||
Flag.withFallbackConfig(optionalUrlConfig("VITE_DEV_SERVER_URL")),
|
||||
),
|
||||
dryRun: Flag.boolean("dry-run").pipe(
|
||||
Flag.withDescription("Resolve mode/ports/env and print, but do not spawn turbo."),
|
||||
Flag.withDefault(false),
|
||||
),
|
||||
turboArgs: Argument.string("turbo-arg").pipe(
|
||||
Argument.withDescription("Additional turbo args (pass after `--`)."),
|
||||
Argument.variadic(),
|
||||
),
|
||||
}).pipe(
|
||||
Command.withDescription("Run monorepo development modes with deterministic port/env wiring."),
|
||||
Command.withHandler((input) => runDevRunnerWithInput(input)),
|
||||
);
|
||||
|
||||
const cliRuntimeLayer = Layer.mergeAll(
|
||||
Logger.layer([Logger.consolePretty()]),
|
||||
NodeServices.layer,
|
||||
NetService.layer,
|
||||
);
|
||||
|
||||
const runtimeProgram = Command.run(devRunnerCli, { version: "0.0.0" }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(cliRuntimeLayer),
|
||||
);
|
||||
|
||||
if (import.meta.main) {
|
||||
NodeRuntime.runMain(runtimeProgram);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Resolve `catalog:` dependency specs using the workspace catalog.
|
||||
*
|
||||
* Pure function: returns a new record with every `catalog:…` value replaced by
|
||||
* the concrete version string found in `catalog`. Throws on missing entries.
|
||||
*/
|
||||
export function resolveCatalogDependencies(
|
||||
dependencies: Record<string, unknown>,
|
||||
catalog: Record<string, unknown>,
|
||||
label: string,
|
||||
): Record<string, unknown> {
|
||||
return Object.fromEntries(
|
||||
Object.entries(dependencies).map(([name, spec]) => {
|
||||
if (typeof spec !== "string" || !spec.startsWith("catalog:")) {
|
||||
return [name, spec];
|
||||
}
|
||||
|
||||
const catalogKey = spec.slice("catalog:".length).trim();
|
||||
const lookupKey = catalogKey.length > 0 ? catalogKey : name;
|
||||
const resolved = catalog[lookupKey];
|
||||
|
||||
if (typeof resolved !== "string" || resolved.length === 0) {
|
||||
throw new Error(
|
||||
`Unable to resolve '${spec}' for ${label} dependency '${name}'. Expected key '${lookupKey}' in root workspace catalog.`,
|
||||
);
|
||||
}
|
||||
|
||||
return [name, resolved];
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "@t3tools/scripts",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"effect": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"@types/bun": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"types": ["node", "bun"],
|
||||
"lib": ["ES2023", "esnext.disposable"],
|
||||
"noEmit": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "@effect/language-service"
|
||||
}
|
||||
]
|
||||
},
|
||||
"include": ["**/*.ts"]
|
||||
}
|
||||
Reference in new issue
Block a user