Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
31b515cd6c |
No files matched your search
@@ -8,7 +8,7 @@ on:
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
name: Lint, Typecheck, Browser Test, Build
|
||||
name: Lint, Typecheck, Test, Build
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -34,14 +34,6 @@ jobs:
|
||||
restore-keys: |
|
||||
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
|
||||
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-playwright-
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
@@ -51,13 +43,9 @@ jobs:
|
||||
- name: Typecheck
|
||||
run: bun run typecheck
|
||||
|
||||
- name: Install browser test runtime
|
||||
run: |
|
||||
cd apps/web
|
||||
bunx playwright install --with-deps chromium
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
- name: Browser test
|
||||
run: bun run --cwd apps/web test:browser
|
||||
- name: Build desktop pipeline
|
||||
run: bun run build:desktop
|
||||
|
||||
@@ -65,44 +53,3 @@ jobs:
|
||||
run: |
|
||||
test -f apps/desktop/dist-electron/preload.js
|
||||
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
|
||||
|
||||
test:
|
||||
name: Test (${{ matrix.label }})
|
||||
runs-on: ${{ matrix.runner }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- label: Linux
|
||||
runner: blacksmith-4vcpu-ubuntu-2404
|
||||
- label: Windows
|
||||
runner: blacksmith-4vcpu-windows-2025
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- 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
|
||||
|
||||
- name: Cache Bun and Turbo
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.bun/install/cache
|
||||
.turbo
|
||||
key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-${{ hashFiles('turbo.json') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Test
|
||||
run: bun run test
|
||||
@@ -198,7 +198,6 @@ jobs:
|
||||
--target "${{ matrix.target }}"
|
||||
--arch "${{ matrix.arch }}"
|
||||
--build-version "${{ needs.preflight.outputs.version }}"
|
||||
--verbose
|
||||
)
|
||||
|
||||
has_all() {
|
||||
@@ -240,71 +239,57 @@ 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-publish/*
|
||||
path: release/*
|
||||
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
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
# publish_cli:
|
||||
# name: Publish CLI to npm
|
||||
# needs: [preflight, build]
|
||||
# runs-on: ubuntu-24.04
|
||||
# steps:
|
||||
# - name: Checkout
|
||||
# uses: actions/checkout@v4
|
||||
|
||||
- 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: Build CLI package
|
||||
run: bun run build --filter=@t3tools/web --filter=t3
|
||||
# - 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: Publish CLI package
|
||||
run: node apps/server/scripts/cli.ts publish --tag alpha --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
# - 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
|
||||
|
||||
release:
|
||||
name: Publish GitHub Release
|
||||
needs: [preflight, build, publish_cli]
|
||||
needs: [preflight, build]
|
||||
# needs: [preflight, build, publish_cli]
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Download all desktop artifacts
|
||||
@@ -320,11 +305,5 @@ jobs:
|
||||
tag_name: ${{ needs.preflight.outputs.tag }}
|
||||
name: T3 Code v${{ needs.preflight.outputs.version }}
|
||||
generate_release_notes: true
|
||||
files: |
|
||||
release-assets/*.dmg
|
||||
release-assets/*.zip
|
||||
release-assets/*.AppImage
|
||||
release-assets/*.exe
|
||||
release-assets/*.blockmap
|
||||
release-assets/latest*.yml
|
||||
files: release-assets/*
|
||||
fail_on_unmatched_files: true
|
||||
+1
-4
@@ -11,7 +11,4 @@ packages/*/dist
|
||||
build/
|
||||
.logs/
|
||||
release/
|
||||
.t3
|
||||
apps/web/.playwright
|
||||
apps/web/playwright-report
|
||||
apps/web/src/components/__screenshots__
|
||||
.t3
|
||||
@@ -18,16 +18,11 @@ 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. 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.
|
||||
- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
|
||||
|
||||
## Codex App Server (Important)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
@@ -14,17 +14,15 @@
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
"electron": "40.6.0",
|
||||
"electron-updater": "^6.6.2"
|
||||
"electron": "40.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@types/node": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
"@types/node": "^22.10.2",
|
||||
"electronmon": "^2.0.2",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0",
|
||||
"wait-on": "^8.0.2"
|
||||
},
|
||||
"productName": "T3 Code (Alpha)"
|
||||
|
||||
@@ -1,171 +1,43 @@
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { watch } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
import electronmon from "electronmon";
|
||||
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}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
|
||||
resources: [
|
||||
`tcp:${port}`,
|
||||
"file:dist-electron/main.js",
|
||||
"file:dist-electron/preload.js",
|
||||
"file:../server/dist/index.mjs",
|
||||
],
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// Kill direct children as a final fallback in case normal shutdown leaves stragglers.
|
||||
// electronmon may leave Electron orphaned when parent shutdown races; kill direct children as fallback.
|
||||
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
@@ -173,29 +45,20 @@ async function shutdown(exitCode) {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
restartTimer = null;
|
||||
try {
|
||||
await Promise.race([monitor.destroy(), new Promise((resolve) => setTimeout(resolve, 1_500))]);
|
||||
} catch {
|
||||
// Best effort only; fallback process kill below handles stubborn children.
|
||||
}
|
||||
|
||||
for (const watcher of watchers) {
|
||||
watcher.close();
|
||||
}
|
||||
|
||||
await stopApp();
|
||||
killChildTree("TERM");
|
||||
await new Promise((resolve) => {
|
||||
setTimeout(resolve, childTreeGracePeriodMs);
|
||||
});
|
||||
killChildTree("KILL");
|
||||
setTimeout(() => {
|
||||
killChildTree("KILL");
|
||||
}, 1_200).unref();
|
||||
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
startWatchers();
|
||||
cleanupStaleDevApps();
|
||||
startApp();
|
||||
|
||||
process.once("SIGINT", () => {
|
||||
void shutdown(130);
|
||||
});
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import * as ChildProcess from "node:child_process";
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
export function fixPath(): void {
|
||||
if (process.platform !== "darwin") return;
|
||||
|
||||
try {
|
||||
const shell = process.env.SHELL ?? "/bin/zsh";
|
||||
const result = ChildProcess.execFileSync(shell, ["-ilc", "echo -n $PATH"], {
|
||||
const result = execFileSync(shell, ["-ilc", "echo -n $PATH"], {
|
||||
encoding: "utf8",
|
||||
timeout: 5000,
|
||||
});
|
||||
|
||||
+68
-666
@@ -1,36 +1,16 @@
|
||||
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 { 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 { 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();
|
||||
|
||||
@@ -39,30 +19,16 @@ 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.ChildProcess | null = null;
|
||||
let backendProcess: ChildProcess | null = null;
|
||||
let backendPort = 0;
|
||||
let backendAuthToken = "";
|
||||
let backendWsUrl = "";
|
||||
@@ -70,134 +36,8 @@ let restartAttempt = 0;
|
||||
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;
|
||||
@@ -221,18 +61,6 @@ 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([
|
||||
{
|
||||
@@ -253,96 +81,26 @@ 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;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
if (!COMMIT_HASH_PATTERN.test(trimmed)) {
|
||||
return null;
|
||||
}
|
||||
return trimmed.slice(0, COMMIT_HASH_DISPLAY_LENGTH).toLowerCase();
|
||||
}
|
||||
|
||||
function resolveEmbeddedCommitHash(): string | null {
|
||||
const packageJsonPath = Path.join(resolveAppRoot(), "package.json");
|
||||
if (!FS.existsSync(packageJsonPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = FS.readFileSync(packageJsonPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as { t3codeCommitHash?: unknown };
|
||||
return normalizeCommitHash(parsed.t3codeCommitHash);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveAboutCommitHash(): string | null {
|
||||
if (aboutCommitHashCache !== undefined) {
|
||||
return aboutCommitHashCache;
|
||||
}
|
||||
|
||||
const envCommitHash = normalizeCommitHash(process.env.T3CODE_COMMIT_HASH);
|
||||
if (envCommitHash) {
|
||||
aboutCommitHashCache = envCommitHash;
|
||||
return aboutCommitHashCache;
|
||||
}
|
||||
|
||||
// Only packaged builds are required to expose commit metadata.
|
||||
if (!app.isPackaged) {
|
||||
aboutCommitHashCache = null;
|
||||
return aboutCommitHashCache;
|
||||
}
|
||||
|
||||
aboutCommitHashCache = resolveEmbeddedCommitHash();
|
||||
|
||||
return aboutCommitHashCache;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -353,50 +111,35 @@ 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;
|
||||
|
||||
@@ -407,19 +150,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;
|
||||
@@ -462,32 +205,6 @@ 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[] = [];
|
||||
|
||||
@@ -496,11 +213,6 @@ function configureApplicationMenu(): void {
|
||||
label: app.name,
|
||||
submenu: [
|
||||
{ role: "about" },
|
||||
{
|
||||
label: "Check for Updates...",
|
||||
click: () => handleCheckForUpdatesMenuClick(),
|
||||
},
|
||||
{ type: "separator" },
|
||||
{
|
||||
label: "Settings...",
|
||||
accelerator: "CmdOrCtrl+,",
|
||||
@@ -538,15 +250,6 @@ function configureApplicationMenu(): void {
|
||||
{ role: "editMenu" },
|
||||
{ role: "viewMenu" },
|
||||
{ role: "windowMenu" },
|
||||
{
|
||||
role: "help",
|
||||
submenu: [
|
||||
{
|
||||
label: "Check for Updates...",
|
||||
click: () => handleCheckForUpdatesMenuClick(),
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
|
||||
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
|
||||
@@ -554,13 +257,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;
|
||||
}
|
||||
}
|
||||
@@ -574,11 +277,8 @@ function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
|
||||
|
||||
function configureAppIdentity(): void {
|
||||
app.setName(APP_DISPLAY_NAME);
|
||||
const commitHash = resolveAboutCommitHash();
|
||||
app.setAboutPanelOptions({
|
||||
applicationName: APP_DISPLAY_NAME,
|
||||
applicationVersion: app.getVersion(),
|
||||
version: commitHash ?? "unknown",
|
||||
});
|
||||
|
||||
if (process.platform === "win32") {
|
||||
@@ -593,200 +293,24 @@ function configureAppIdentity(): void {
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
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"));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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...");
|
||||
});
|
||||
probe.on("error", reject);
|
||||
});
|
||||
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,
|
||||
@@ -815,13 +339,12 @@ 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 captureBackendLogs = app.isPackaged && backendLogSink !== null;
|
||||
const child = ChildProcess.spawn(process.execPath, [backendEntry], {
|
||||
const child = 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.
|
||||
@@ -829,20 +352,9 @@ function startBackend(): void {
|
||||
...backendEnv(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
stdio: captureBackendLogs ? ["ignore", "pipe", "pipe"] : "inherit",
|
||||
stdio: "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;
|
||||
@@ -852,7 +364,6 @@ function startBackend(): void {
|
||||
if (backendProcess === child) {
|
||||
backendProcess = null;
|
||||
}
|
||||
closeBackendSession(`pid=${child.pid ?? "unknown"} error=${error.message}`);
|
||||
scheduleBackendRestart(error.message);
|
||||
});
|
||||
|
||||
@@ -860,9 +371,6 @@ 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);
|
||||
@@ -889,57 +397,6 @@ 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 () => {
|
||||
@@ -968,7 +425,11 @@ function registerIpcHandlers(): void {
|
||||
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
|
||||
ipcMain.handle(
|
||||
CONTEXT_MENU_CHANNEL,
|
||||
async (_event, items: ContextMenuItem[], position?: { x: number; y: number }) => {
|
||||
async (
|
||||
_event,
|
||||
items: ContextMenuItem[],
|
||||
position?: { x: number; y: number },
|
||||
) => {
|
||||
const normalizedItems = items
|
||||
.filter((item) => typeof item.id === "string" && typeof item.label === "string")
|
||||
.map((item) => ({
|
||||
@@ -1019,7 +480,7 @@ function registerIpcHandlers(): void {
|
||||
const menu = Menu.buildFromTemplate(template);
|
||||
menu.popup({
|
||||
window,
|
||||
...popupPosition,
|
||||
...(popupPosition ?? {}),
|
||||
callback: () => resolve(null),
|
||||
});
|
||||
});
|
||||
@@ -1050,36 +511,6 @@ 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> {
|
||||
@@ -1102,7 +533,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,
|
||||
@@ -1116,7 +547,6 @@ function createWindow(): BrowserWindow {
|
||||
});
|
||||
window.webContents.on("did-finish-load", () => {
|
||||
window.setTitle(APP_DISPLAY_NAME);
|
||||
emitUpdateState();
|
||||
});
|
||||
window.once("ready-to-show", () => {
|
||||
window.show();
|
||||
@@ -1141,55 +571,33 @@ function createWindow(): BrowserWindow {
|
||||
configureAppIdentity();
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
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");
|
||||
backendPort = await reserveLoopbackPort();
|
||||
backendAuthToken = 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(() => {
|
||||
writeDesktopLogHeader("app ready");
|
||||
configureAppIdentity();
|
||||
configureApplicationMenu();
|
||||
registerDesktopProtocol();
|
||||
configureAutoUpdater();
|
||||
void bootstrap().catch((error) => {
|
||||
handleFatalStartupError("bootstrap", error);
|
||||
});
|
||||
app.whenReady().then(() => {
|
||||
configureAppIdentity();
|
||||
configureApplicationMenu();
|
||||
registerDesktopProtocol();
|
||||
void bootstrap();
|
||||
|
||||
app.on("activate", () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
mainWindow = createWindow();
|
||||
}
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
handleFatalStartupError("whenReady", error);
|
||||
app.on("activate", () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
mainWindow = createWindow();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
app.on("window-all-closed", () => {
|
||||
if (process.platform !== "darwin") {
|
||||
@@ -1201,20 +609,14 @@ 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,10 +6,6 @@ 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", {
|
||||
@@ -29,18 +25,4 @@ 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);
|
||||
@@ -1,74 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,130 +0,0 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -1,155 +0,0 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,142 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,48 +0,0 @@
|
||||
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: (id) => id.startsWith("@t3tools/"),
|
||||
noExternal: ["@t3tools/contracts"],
|
||||
},
|
||||
{
|
||||
...shared,
|
||||
|
||||
+10
-13
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"bin": {
|
||||
"t3": "./dist/index.mjs"
|
||||
},
|
||||
@@ -8,9 +8,10 @@
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "./dist/index.mjs",
|
||||
"scripts": {
|
||||
"dev": "bun run src/index.ts",
|
||||
"build": "node scripts/cli.ts build",
|
||||
"dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5733} bun run src/index.ts",
|
||||
"build": "tsdown && node scripts/bundle-client.ts",
|
||||
"start": "node dist/index.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
@@ -26,19 +27,15 @@
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/language-service": "0.75.1",
|
||||
"@effect/vitest": "catalog:",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/bun": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"@types/bun": "^1.3.9",
|
||||
"@types/node": "^22.10.2",
|
||||
"@types/ws": "^8.5.13",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.13 || ^23.4 || >=24.10"
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* 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");
|
||||
@@ -1,170 +0,0 @@
|
||||
#!/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,44 +1,17 @@
|
||||
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 { 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 = createManager();
|
||||
const manager = new CodexAppServerManager();
|
||||
const context = {
|
||||
session: {
|
||||
sessionId: "sess_1",
|
||||
@@ -74,7 +47,7 @@ function createSendTurnHarness() {
|
||||
}
|
||||
|
||||
function createThreadControlHarness() {
|
||||
const manager = createManager();
|
||||
const manager = new CodexAppServerManager();
|
||||
const context = {
|
||||
session: {
|
||||
sessionId: "sess_1",
|
||||
@@ -173,22 +146,9 @@ describe("isRecoverableThreadResumeError", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("messageFromCodexProcessCause", () => {
|
||||
it("extracts the underlying error message from an effect cause", () => {
|
||||
expect(messageFromCodexProcessCause(Cause.fail(new Error("boom")))).toBe("boom");
|
||||
});
|
||||
});
|
||||
|
||||
describe("constructor", () => {
|
||||
it("supports the optional no-services path without unsafe casting", () => {
|
||||
const manager = new CodexAppServerManager();
|
||||
expect(() => manager.stopAll()).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("startSession", () => {
|
||||
it("emits session/startFailed when resolving cwd throws before process launch", async () => {
|
||||
const manager = createManager();
|
||||
const manager = new CodexAppServerManager();
|
||||
const events: Array<{ method: string; kind: string; message?: string }> = [];
|
||||
manager.on("event", (event) => {
|
||||
events.push({
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
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,
|
||||
@@ -16,10 +18,6 @@ import {
|
||||
type ProviderSessionStartInput,
|
||||
type ProviderTurnStartResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Cause, Effect, Exit, ManagedRuntime, ServiceMap, Scope, Stream } from "effect";
|
||||
import type { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { makeRuntimeCommand, spawnManagedCommand } from "./processRunner";
|
||||
|
||||
type PendingRequestKey = string;
|
||||
|
||||
@@ -42,8 +40,8 @@ interface PendingApprovalRequest {
|
||||
|
||||
interface CodexSessionContext {
|
||||
session: ProviderSession;
|
||||
child: ChildProcessSpawner.ChildProcessHandle;
|
||||
scope: Scope.Closeable;
|
||||
child: ChildProcessWithoutNullStreams;
|
||||
output: readline.Interface;
|
||||
pending: Map<PendingRequestKey, PendingRequest>;
|
||||
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
|
||||
nextRequestId: number;
|
||||
@@ -153,37 +151,12 @@ 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 ownedRuntime:
|
||||
| ManagedRuntime.ManagedRuntime<NodeServices.NodeServices, unknown>
|
||||
| null;
|
||||
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();
|
||||
if (services) {
|
||||
this.ownedRuntime = null;
|
||||
this.runPromise = Effect.runPromiseWith(services);
|
||||
return;
|
||||
}
|
||||
|
||||
const runtime = ManagedRuntime.make(NodeServices.layer);
|
||||
this.ownedRuntime = runtime;
|
||||
this.runPromise = runtime.runPromise.bind(runtime);
|
||||
}
|
||||
|
||||
async startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
|
||||
const sessionId = ProviderSessionId.makeUnsafe(randomUUID());
|
||||
@@ -205,23 +178,20 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
|
||||
const codexBinaryPath = input.codexBinaryPath ?? "codex";
|
||||
const codexHomePath = input.codexHomePath;
|
||||
const managedProcess = await this.runPromise(
|
||||
spawnManagedCommand(
|
||||
makeRuntimeCommand(codexBinaryPath, ["app-server"], {
|
||||
cwd: resolvedCwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
|
||||
},
|
||||
extendEnv: false,
|
||||
}),
|
||||
),
|
||||
);
|
||||
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 });
|
||||
|
||||
context = {
|
||||
session,
|
||||
child: managedProcess.handle,
|
||||
scope: managedProcess.scope,
|
||||
child,
|
||||
output,
|
||||
pending: new Map(),
|
||||
pendingApprovals: new Map(),
|
||||
nextRequestId: 1,
|
||||
@@ -229,7 +199,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
};
|
||||
|
||||
this.sessions.set(sessionId, context);
|
||||
await this.attachProcessListeners(context);
|
||||
this.attachProcessListeners(context);
|
||||
|
||||
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
|
||||
|
||||
@@ -244,7 +214,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
},
|
||||
});
|
||||
|
||||
await this.writeMessage(context, { method: "initialized" });
|
||||
this.writeMessage(context, { method: "initialized" });
|
||||
|
||||
const normalizedModel = normalizeCodexModelSlug(input.model);
|
||||
const sessionOverrides = {
|
||||
@@ -460,7 +430,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
context.pendingApprovals.delete(requestId);
|
||||
await this.writeMessage(context, {
|
||||
this.writeMessage(context, {
|
||||
id: pendingRequest.jsonRpcId,
|
||||
result: {
|
||||
decision,
|
||||
@@ -501,7 +471,12 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
context.pending.clear();
|
||||
context.pendingApprovals.clear();
|
||||
void this.runPromise(Scope.close(context.scope, Exit.void)).catch(() => undefined);
|
||||
|
||||
context.output.close();
|
||||
|
||||
if (!context.child.killed) {
|
||||
context.child.kill();
|
||||
}
|
||||
|
||||
this.updateSession(context, {
|
||||
status: "closed",
|
||||
@@ -525,10 +500,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
for (const sessionId of this.sessions.keys()) {
|
||||
this.stopSession(sessionId);
|
||||
}
|
||||
|
||||
if (this.ownedRuntime) {
|
||||
void this.ownedRuntime.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private requireSession(sessionId: ProviderSessionId): CodexSessionContext {
|
||||
@@ -544,71 +515,47 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return context;
|
||||
}
|
||||
|
||||
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);
|
||||
}),
|
||||
),
|
||||
);
|
||||
private attachProcessListeners(context: CodexSessionContext): void {
|
||||
context.output.on("line", (line) => {
|
||||
this.handleStdoutLine(context, line);
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
this.emitErrorEvent(context, "process/stderr", classified.message);
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
this.emitErrorEvent(context, "process/stderr", classified.message);
|
||||
}
|
||||
});
|
||||
|
||||
yield* Effect.forkScoped(
|
||||
Effect.matchCauseEffect(context.child.exitCode, {
|
||||
onFailure: (cause) =>
|
||||
Effect.sync(() => {
|
||||
if (context.stopping) {
|
||||
return;
|
||||
}
|
||||
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);
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
context.child.on("exit", (code, signal) => {
|
||||
if (context.stopping) {
|
||||
return;
|
||||
}
|
||||
|
||||
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)),
|
||||
);
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
private handleStdoutLine(context: CodexSessionContext, line: string): void {
|
||||
@@ -764,31 +711,19 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
if (request.method === "item/tool/requestUserInput") {
|
||||
void this.writeMessage(context, {
|
||||
this.writeMessage(context, {
|
||||
id: request.id,
|
||||
result: { answers: {} },
|
||||
}).catch((error) => {
|
||||
this.emitErrorEvent(
|
||||
context,
|
||||
"protocol/writeError",
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
void this.writeMessage(context, {
|
||||
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),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -831,30 +766,23 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
resolve,
|
||||
reject,
|
||||
});
|
||||
void this.writeMessage(context, {
|
||||
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 async writeMessage(context: CodexSessionContext, message: unknown): Promise<void> {
|
||||
private writeMessage(context: CodexSessionContext, message: unknown): void {
|
||||
const encoded = JSON.stringify(message);
|
||||
if (context.stopping || !this.sessions.has(context.session.sessionId)) {
|
||||
if (!context.child.stdin.writable) {
|
||||
throw new Error("Cannot write to codex app-server stdin.");
|
||||
}
|
||||
await this.runPromise(
|
||||
Stream.run(context.child.stdin)(Stream.make(new TextEncoder().encode(`${encoded}\n`))).pipe(
|
||||
Scope.provide(context.scope),
|
||||
),
|
||||
);
|
||||
|
||||
context.child.stdin.write(`${encoded}\n`);
|
||||
}
|
||||
|
||||
private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
import { accessSync, constants, statSync } from "node:fs";
|
||||
import { extname, isAbsolute, resolve } from "node:path";
|
||||
|
||||
export function stripWrappingQuotes(value: string): string {
|
||||
return value.replace(/^"+|"+$/g, "");
|
||||
}
|
||||
|
||||
export function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
|
||||
return env.PATH ?? env.Path ?? env.path ?? "";
|
||||
}
|
||||
|
||||
export function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
|
||||
const rawValue = env.PATHEXT;
|
||||
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
|
||||
if (!rawValue) return fallback;
|
||||
|
||||
const parsed = rawValue
|
||||
.split(";")
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0)
|
||||
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
|
||||
|
||||
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
|
||||
}
|
||||
|
||||
export function resolveCommandCandidates(
|
||||
command: string,
|
||||
platform: NodeJS.Platform,
|
||||
windowsPathExtensions: ReadonlyArray<string>,
|
||||
): ReadonlyArray<string> {
|
||||
if (platform !== "win32") {
|
||||
return [command];
|
||||
}
|
||||
|
||||
const extension = extname(command);
|
||||
const normalizedExtension = extension.toUpperCase();
|
||||
|
||||
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
|
||||
const commandWithoutExtension = command.slice(0, -extension.length);
|
||||
return Array.from(
|
||||
new Set([
|
||||
command,
|
||||
`${commandWithoutExtension}${normalizedExtension}`,
|
||||
`${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
const candidates: string[] = [command];
|
||||
for (const candidateExtension of windowsPathExtensions) {
|
||||
candidates.push(`${command}${candidateExtension}`);
|
||||
candidates.push(`${command}${candidateExtension.toLowerCase()}`);
|
||||
}
|
||||
return Array.from(new Set(candidates));
|
||||
}
|
||||
|
||||
interface ResolveExecutableFileOptions {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly windowsPathExtensions: ReadonlyArray<string>;
|
||||
readonly cwd?: string | undefined;
|
||||
}
|
||||
|
||||
export function resolveExecutableFile(
|
||||
filePath: string,
|
||||
options: ResolveExecutableFileOptions,
|
||||
): string | null {
|
||||
const candidatePath =
|
||||
options.cwd !== undefined && !isAbsolute(filePath) ? resolve(options.cwd, filePath) : filePath;
|
||||
|
||||
try {
|
||||
const stat = statSync(candidatePath);
|
||||
if (!stat.isFile()) return null;
|
||||
|
||||
if (options.platform === "win32") {
|
||||
const extension = extname(candidatePath);
|
||||
if (extension.length === 0) return null;
|
||||
return options.windowsPathExtensions.includes(extension.toUpperCase()) ? candidatePath : null;
|
||||
}
|
||||
|
||||
accessSync(candidatePath, constants.X_OK);
|
||||
return candidatePath;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function isExecutableFile(
|
||||
filePath: string,
|
||||
options: ResolveExecutableFileOptions,
|
||||
): boolean {
|
||||
return resolveExecutableFile(filePath, options) !== null;
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
/**
|
||||
* ServerConfig - Runtime configuration services.
|
||||
* ServerConfig and NetService - Runtime configuration services.
|
||||
*
|
||||
* Defines process-level server configuration and networking helpers used by
|
||||
* startup and runtime layers.
|
||||
*
|
||||
* @module ServerConfig
|
||||
*/
|
||||
import { Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
|
||||
import * as Net from "node:net";
|
||||
import { Data, Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
|
||||
|
||||
export const DEFAULT_PORT = 3773;
|
||||
|
||||
@@ -59,6 +60,68 @@ 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 without branch by default", () =>
|
||||
it.effect("generates and sanitizes commit messages", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
@@ -197,7 +197,6 @@ 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;
|
||||
@@ -212,34 +211,6 @@ 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,12 +1,10 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { Effect, FileSystem, Layer, Path, Schema } from "effect";
|
||||
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import {
|
||||
type BranchNameGenerationInput,
|
||||
@@ -95,15 +93,52 @@ 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 = (
|
||||
@@ -184,59 +219,67 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
);
|
||||
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
||||
|
||||
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 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 child = yield* commandSpawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCodexError(operation, cause, "Failed to spawn Codex CLI process"),
|
||||
),
|
||||
);
|
||||
|
||||
if (result.timedOut) {
|
||||
throw new TextGenerationError({ operation, detail: "Codex CLI request timed out." });
|
||||
}
|
||||
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" },
|
||||
);
|
||||
|
||||
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"),
|
||||
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 cleanup = Effect.all(
|
||||
@@ -247,7 +290,19 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
yield* runCodexCommand;
|
||||
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,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* fileSystem.readFileString(outputPath).pipe(
|
||||
Effect.mapError(
|
||||
@@ -273,19 +328,12 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = (input) => {
|
||||
const wantsBranch = input.includeBranch === true;
|
||||
|
||||
const prompt = [
|
||||
"You write concise git commit messages.",
|
||||
wantsBranch
|
||||
? "Return a JSON object with keys: subject, body, branch."
|
||||
: "Return a JSON object with keys: subject, body.",
|
||||
"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)"}`,
|
||||
@@ -297,31 +345,20 @@ 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,
|
||||
outputSchemaJson: Schema.Struct({
|
||||
subject: Schema.String,
|
||||
body: Schema.String,
|
||||
}),
|
||||
}).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,
|
||||
),
|
||||
);
|
||||
@@ -371,10 +408,7 @@ 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)`,
|
||||
@@ -412,7 +446,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
return {
|
||||
branch: sanitizeBranchFragment(generated.branch),
|
||||
branch: sanitizeBranchName(generated.branch),
|
||||
} satisfies BranchNameGenerationResult;
|
||||
});
|
||||
};
|
||||
|
||||
@@ -110,7 +110,6 @@ 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;
|
||||
});
|
||||
|
||||
|
||||
@@ -126,7 +126,10 @@ function parseRemoteRefWithRemoteNames(
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null {
|
||||
function parseTrackingBranchByUpstreamRef(
|
||||
stdout: string,
|
||||
upstreamRef: string,
|
||||
): string | null {
|
||||
for (const line of stdout.split("\n")) {
|
||||
const trimmedLine = line.trim();
|
||||
if (trimmedLine.length === 0) {
|
||||
@@ -386,12 +389,9 @@ const makeGitCore = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const resolveDefaultBranchName = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
|
||||
executeGit(
|
||||
"GitCore.resolveDefaultBranchName",
|
||||
cwd,
|
||||
["symbolic-ref", "refs/remotes/origin/HEAD"],
|
||||
{ allowNonZeroExit: true },
|
||||
).pipe(
|
||||
executeGit("GitCore.resolveDefaultBranchName", cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"], {
|
||||
allowNonZeroExit: true,
|
||||
}).pipe(
|
||||
Effect.map((result) => {
|
||||
if (result.code !== 0) {
|
||||
return null;
|
||||
@@ -888,34 +888,33 @@ const makeGitCore = Effect.gen(function* () {
|
||||
|
||||
const [defaultRef, worktreeList, remoteBranchResult, remoteNamesResult, branchLastCommit] =
|
||||
yield* Effect.all(
|
||||
[
|
||||
executeGit(
|
||||
"GitCore.listBranches.defaultRef",
|
||||
input.cwd,
|
||||
["symbolic-ref", "refs/remotes/origin/HEAD"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
executeGit(
|
||||
"GitCore.listBranches.worktreeList",
|
||||
input.cwd,
|
||||
["worktree", "list", "--porcelain"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
remoteBranchResultEffect,
|
||||
remoteNamesResultEffect,
|
||||
branchRecencyPromise,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
[
|
||||
executeGit(
|
||||
"GitCore.listBranches.defaultRef",
|
||||
input.cwd,
|
||||
["symbolic-ref", "refs/remotes/origin/HEAD"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
executeGit(
|
||||
"GitCore.listBranches.worktreeList",
|
||||
input.cwd,
|
||||
["worktree", "list", "--porcelain"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
remoteBranchResultEffect,
|
||||
remoteNamesResultEffect,
|
||||
branchRecencyPromise,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const remoteNames =
|
||||
remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : [];
|
||||
const remoteNames = remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : [];
|
||||
if (remoteBranchResult.code !== 0 && remoteBranchResult.stderr.trim().length > 0) {
|
||||
yield* Effect.logWarning(
|
||||
`GitCore.listBranches: remote branch lookup returned code ${remoteBranchResult.code} for ${input.cwd}: ${remoteBranchResult.stderr.trim()}. Falling back to an empty remote branch list.`,
|
||||
@@ -1113,23 +1112,24 @@ const makeGitCore = Effect.gen(function* () {
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const localTrackingBranch = remoteExists
|
||||
? yield* executeGit(
|
||||
"GitCore.checkoutBranch.localTrackingBranch",
|
||||
input.cwd,
|
||||
["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.map((result) =>
|
||||
result.code === 0
|
||||
? parseTrackingBranchByUpstreamRef(result.stdout, input.branch)
|
||||
: null,
|
||||
),
|
||||
)
|
||||
: null;
|
||||
const localTrackingBranch =
|
||||
remoteExists
|
||||
? yield* executeGit(
|
||||
"GitCore.checkoutBranch.localTrackingBranch",
|
||||
input.cwd,
|
||||
["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.map((result) =>
|
||||
result.code === 0
|
||||
? parseTrackingBranchByUpstreamRef(result.stdout, input.branch)
|
||||
: null,
|
||||
),
|
||||
)
|
||||
: null;
|
||||
|
||||
const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch);
|
||||
const localTrackedBranchTargetExists =
|
||||
@@ -1145,15 +1145,16 @@ const makeGitCore = Effect.gen(function* () {
|
||||
).pipe(Effect.map((result) => result.code === 0))
|
||||
: false;
|
||||
|
||||
const checkoutArgs = localInputExists
|
||||
? ["checkout", input.branch]
|
||||
: remoteExists && !localTrackingBranch && localTrackedBranchTargetExists
|
||||
const checkoutArgs =
|
||||
localInputExists
|
||||
? ["checkout", input.branch]
|
||||
: remoteExists && !localTrackingBranch && localTrackedBranchTargetExists
|
||||
? ["checkout", input.branch]
|
||||
: remoteExists && !localTrackingBranch
|
||||
? ["checkout", "--track", input.branch]
|
||||
: remoteExists && localTrackingBranch
|
||||
? ["checkout", localTrackingBranch]
|
||||
: ["checkout", input.branch];
|
||||
? ["checkout", "--track", input.branch]
|
||||
: remoteExists && localTrackingBranch
|
||||
? ["checkout", localTrackingBranch]
|
||||
: ["checkout", input.branch];
|
||||
|
||||
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, checkoutArgs, {
|
||||
timeoutMs: 10_000,
|
||||
@@ -1172,20 +1173,6 @@ 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,
|
||||
@@ -1202,7 +1189,6 @@ const makeGitCore = Effect.gen(function* () {
|
||||
createBranch,
|
||||
checkoutBranch,
|
||||
initRepo,
|
||||
listLocalBranchNames,
|
||||
} satisfies GitCoreShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -32,11 +32,7 @@ interface FakeGitTextGeneration {
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
includeBranch?: boolean;
|
||||
}) => Effect.Effect<
|
||||
{ subject: string; body: string; branch?: string | undefined },
|
||||
TextGenerationError
|
||||
>;
|
||||
}) => Effect.Effect<{ subject: string; body: string }, TextGenerationError>;
|
||||
generatePrContent: (input: {
|
||||
cwd: string;
|
||||
baseBranch: string;
|
||||
@@ -108,13 +104,10 @@ function createBareRemote(): Effect.Effect<
|
||||
|
||||
function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): TextGenerationShape {
|
||||
const implementation: FakeGitTextGeneration = {
|
||||
generateCommitMessage: (input) =>
|
||||
generateCommitMessage: () =>
|
||||
Effect.succeed({
|
||||
subject: "Implement stacked git actions",
|
||||
body: "",
|
||||
...(input.includeBranch
|
||||
? { branch: "feature/implement-stacked-git-actions" }
|
||||
: {}),
|
||||
}),
|
||||
generatePrContent: () =>
|
||||
Effect.succeed({
|
||||
@@ -290,7 +283,6 @@ function runStackedAction(
|
||||
cwd: string;
|
||||
action: "commit" | "commit_push" | "commit_push_pr";
|
||||
commitMessage?: string;
|
||||
featureBranch?: boolean;
|
||||
},
|
||||
) {
|
||||
return manager.runStackedAction(input);
|
||||
@@ -483,7 +475,6 @@ 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");
|
||||
@@ -504,13 +495,12 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) =>
|
||||
generateCommitMessage: () =>
|
||||
Effect.sync(() => {
|
||||
generatedCount += 1;
|
||||
return {
|
||||
subject: "this should not be used",
|
||||
body: "",
|
||||
...(input.includeBranch ? { branch: "feature/unused" } : {}),
|
||||
};
|
||||
}),
|
||||
},
|
||||
@@ -521,7 +511,6 @@ 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);
|
||||
@@ -538,101 +527,6 @@ 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-");
|
||||
@@ -644,32 +538,12 @@ 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-");
|
||||
@@ -685,7 +559,6 @@ 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);
|
||||
@@ -730,7 +603,6 @@ 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);
|
||||
@@ -763,7 +635,6 @@ 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");
|
||||
}),
|
||||
@@ -798,7 +669,6 @@ 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);
|
||||
@@ -839,7 +709,6 @@ 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,7 +1,6 @@
|
||||
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";
|
||||
@@ -86,14 +85,9 @@ function limitContext(value: string, maxChars: number): string {
|
||||
return `${value.slice(0, maxChars)}\n\n[truncated]`;
|
||||
}
|
||||
|
||||
function sanitizeCommitMessage(generated: {
|
||||
function sanitizeCommitMessage(generated: { subject: string; body: string }): {
|
||||
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();
|
||||
@@ -101,25 +95,9 @@ function sanitizeCommitMessage(generated: {
|
||||
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) {
|
||||
@@ -275,72 +253,30 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
return "main";
|
||||
});
|
||||
|
||||
const resolveCommitAndBranchSuggestion = (input: {
|
||||
cwd: string;
|
||||
branch: string | null;
|
||||
commitMessage?: string;
|
||||
/** When true, also produce a semantic feature branch name. */
|
||||
includeBranch?: boolean;
|
||||
}) =>
|
||||
const runCommitStep = (cwd: string, branch: string | null, commitMessage?: string) =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* gitCore.prepareCommitContext(input.cwd);
|
||||
const context = yield* gitCore.prepareCommitContext(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 };
|
||||
}
|
||||
|
||||
const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body);
|
||||
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);
|
||||
return {
|
||||
status: "created" as const,
|
||||
commitSha,
|
||||
subject: suggestion.subject,
|
||||
subject: generated.subject,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -445,88 +381,34 @@ 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 (!input.featureBranch && wantsPush && !initialStatus.branch) {
|
||||
if (wantsPush && !initialStatus.branch) {
|
||||
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
|
||||
}
|
||||
if (!input.featureBranch && wantsPr && !initialStatus.branch) {
|
||||
if (wantsPr && !initialStatus.branch) {
|
||||
return yield* gitManagerError(
|
||||
"runStackedAction",
|
||||
"Cannot create a pull request from detached HEAD.",
|
||||
);
|
||||
}
|
||||
|
||||
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 commit = yield* runCommitStep(input.cwd, initialStatus.branch, input.commitMessage);
|
||||
|
||||
const push = wantsPush
|
||||
? yield* gitCore.pushCurrentBranch(input.cwd, currentBranch)
|
||||
? yield* gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
const pr = wantsPr
|
||||
? yield* runPrStep(input.cwd, currentBranch)
|
||||
? yield* runPrStep(input.cwd, initialStatus.branch)
|
||||
: { 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, normalizeGitProcessResult } from "./GitService.ts";
|
||||
import { GitServiceLive } from "./GitService.ts";
|
||||
import { GitService } from "../Services/GitService.ts";
|
||||
|
||||
const layer = it.layer(Layer.provideMerge(GitServiceLive, NodeServices.layer));
|
||||
@@ -56,31 +56,4 @@ 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 - runtime-aware git execution with typed errors.
|
||||
* Git process helpers - Effect-native 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, Schema } from "effect";
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import { Effect, Layer, Option, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { GitCommandError } from "../Errors.ts";
|
||||
import {
|
||||
ExecuteGitInput,
|
||||
@@ -39,60 +39,37 @@ function toGitCommandError(
|
||||
});
|
||||
}
|
||||
|
||||
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.`,
|
||||
});
|
||||
}
|
||||
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 = "";
|
||||
|
||||
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.`,
|
||||
});
|
||||
}
|
||||
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.")));
|
||||
|
||||
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}.`,
|
||||
});
|
||||
}
|
||||
text += decoder.decode();
|
||||
return text;
|
||||
});
|
||||
|
||||
return {
|
||||
code: exitCode,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
} satisfies ExecuteGitResult;
|
||||
}
|
||||
const makeGitService = Effect.gen(function* () {
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const makeGitService = Effect.sync(() => {
|
||||
const execute: GitServiceShape["execute"] = Effect.fnUntraced(function* (input) {
|
||||
const commandInput = {
|
||||
...input,
|
||||
@@ -101,21 +78,62 @@ const makeGitService = Effect.sync(() => {
|
||||
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
|
||||
return yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
const result = await runProcess("git", commandInput.args, {
|
||||
cwd: commandInput.cwd,
|
||||
...(input.env ? { env: input.env } : {}),
|
||||
timeoutMs,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: maxOutputBytes,
|
||||
outputMode: "error",
|
||||
});
|
||||
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.")));
|
||||
|
||||
return normalizeGitProcessResult(commandInput, input, result);
|
||||
},
|
||||
catch: toGitCommandError(commandInput, "failed to run."),
|
||||
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),
|
||||
cwd: commandInput.cwd,
|
||||
detail:
|
||||
trimmedStderr.length > 0
|
||||
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
|
||||
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
|
||||
return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
|
||||
});
|
||||
|
||||
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 {
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* @module GitCore
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect, Scope } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type {
|
||||
GitCheckoutInput,
|
||||
GitCreateBranchInput,
|
||||
@@ -149,19 +149,12 @@ export interface GitCoreShape {
|
||||
/**
|
||||
* Checkout an existing branch and refresh its upstream metadata in background.
|
||||
*/
|
||||
readonly checkoutBranch: (
|
||||
input: GitCheckoutInput,
|
||||
) => Effect.Effect<void, GitCommandError, Scope.Scope>;
|
||||
readonly checkoutBranch: (input: GitCheckoutInput) => Effect.Effect<void, GitCommandError>;
|
||||
|
||||
/**
|
||||
* 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,7 +29,6 @@ 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,15 +17,11 @@ 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 "@t3tools/shared/Net";
|
||||
import { NetService } from "./config";
|
||||
|
||||
const RuntimeLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(CliConfig.layer),
|
||||
|
||||
@@ -6,10 +6,9 @@ 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 { ServerConfig, type ServerConfigShape } from "./config";
|
||||
import { NetService, ServerConfig, type ServerConfigShape } from "./config";
|
||||
import { Open, type OpenShape } from "./open";
|
||||
import { Server, type ServerShape } from "./wsServer";
|
||||
|
||||
@@ -34,9 +33,6 @@ 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,7 +21,6 @@ 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")<{
|
||||
@@ -198,7 +197,6 @@ const LayerLive = (input: CliInput) =>
|
||||
Layer.empty.pipe(
|
||||
Layer.provideMerge(makeServerRuntimeServicesLayer()),
|
||||
Layer.provideMerge(makeServerProviderLayer()),
|
||||
Layer.provideMerge(ProviderHealthLive),
|
||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||
Layer.provideMerge(ServerConfigLive(input)),
|
||||
);
|
||||
|
||||
+71
-401
@@ -1,425 +1,95 @@
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
isCommandAvailable,
|
||||
launchDetached,
|
||||
resolveBrowserLaunch,
|
||||
resolveAvailableEditors,
|
||||
resolveEditorLaunch,
|
||||
} from "./open";
|
||||
import { launchDetached, resolveEditorLaunch } from "./open";
|
||||
import { Effect } from "effect";
|
||||
import { assertSuccess } from "@effect/vitest/utils";
|
||||
|
||||
describe("resolveEditorLaunch", () => {
|
||||
it("returns commands for command-based editors", async () => {
|
||||
const cursorLaunch = await Effect.runPromise(
|
||||
resolveEditorLaunch(
|
||||
it.effect("returns cursor command for cursor editor", () =>
|
||||
Effect.gen(function* () {
|
||||
const launch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "cursor" },
|
||||
{ platform: "darwin" },
|
||||
),
|
||||
);
|
||||
assert.deepEqual(cursorLaunch, {
|
||||
command: "cursor",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(launch, {
|
||||
command: "cursor",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const vscodeLaunch = await Effect.runPromise(
|
||||
resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode" },
|
||||
{ platform: "darwin" },
|
||||
),
|
||||
);
|
||||
assert.deepEqual(vscodeLaunch, {
|
||||
command: "code",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const zedLaunch = await Effect.runPromise(
|
||||
resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "zed" },
|
||||
{ platform: "darwin" },
|
||||
),
|
||||
);
|
||||
assert.deepEqual(zedLaunch, {
|
||||
command: "zed",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
});
|
||||
|
||||
it("uses --goto when editor supports line/column suffixes", async () => {
|
||||
const lineOnly = await Effect.runPromise(
|
||||
resolveEditorLaunch(
|
||||
it.effect("uses --goto when cursor target includes line/column suffixes", () =>
|
||||
Effect.gen(function* () {
|
||||
const lineOnly = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
|
||||
{ platform: "darwin" },
|
||||
),
|
||||
);
|
||||
assert.deepEqual(lineOnly, {
|
||||
command: "cursor",
|
||||
args: ["--goto", "/tmp/workspace/AGENTS.md:48"],
|
||||
});
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(lineOnly, {
|
||||
command: "cursor",
|
||||
args: ["--goto", "/tmp/workspace/AGENTS.md:48"],
|
||||
});
|
||||
|
||||
const lineAndColumn = await Effect.runPromise(
|
||||
resolveEditorLaunch(
|
||||
const lineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
|
||||
{ platform: "darwin" },
|
||||
),
|
||||
);
|
||||
assert.deepEqual(lineAndColumn, {
|
||||
command: "cursor",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(lineAndColumn, {
|
||||
command: "cursor",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const vscodeLineAndColumn = await Effect.runPromise(
|
||||
resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
||||
{ platform: "darwin" },
|
||||
),
|
||||
);
|
||||
assert.deepEqual(vscodeLineAndColumn, {
|
||||
command: "code",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const zedLineAndColumn = await Effect.runPromise(
|
||||
resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
|
||||
{ platform: "darwin" },
|
||||
),
|
||||
);
|
||||
assert.deepEqual(zedLineAndColumn, {
|
||||
command: "zed",
|
||||
args: ["/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
});
|
||||
|
||||
it("maps file-manager editor to OS open commands", async () => {
|
||||
const launch1 = await Effect.runPromise(
|
||||
resolveEditorLaunch(
|
||||
it.effect("maps file-manager editor to OS open commands", () =>
|
||||
Effect.gen(function* () {
|
||||
const launch1 = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||
{ platform: "darwin" },
|
||||
),
|
||||
);
|
||||
assert.deepEqual(launch1, {
|
||||
command: "open",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(launch1, {
|
||||
command: "open",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const launch2 = await Effect.runPromise(
|
||||
resolveEditorLaunch(
|
||||
const launch2 = yield* resolveEditorLaunch(
|
||||
{ cwd: "C:\\workspace", editor: "file-manager" },
|
||||
{ platform: "win32" },
|
||||
),
|
||||
);
|
||||
assert.deepEqual(launch2, {
|
||||
command: "explorer",
|
||||
args: ["C:\\workspace"],
|
||||
});
|
||||
"win32",
|
||||
);
|
||||
assert.deepEqual(launch2, {
|
||||
command: "explorer",
|
||||
args: ["C:\\workspace"],
|
||||
});
|
||||
|
||||
const launch3 = await Effect.runPromise(
|
||||
resolveEditorLaunch(
|
||||
const launch3 = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||
{ platform: "linux" },
|
||||
),
|
||||
);
|
||||
assert.deepEqual(launch3, {
|
||||
command: "xdg-open",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
});
|
||||
|
||||
it("prefers linux editor shims in wsl-hosted mode when available", async () => {
|
||||
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 = await Effect.runPromise(
|
||||
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,
|
||||
},
|
||||
},
|
||||
),
|
||||
"linux",
|
||||
);
|
||||
assert.deepEqual(launch, {
|
||||
command: "code",
|
||||
args: ["--goto", "/home/julius/project/src/open.ts:71:5"],
|
||||
assert.deepEqual(launch3, {
|
||||
command: "xdg-open",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back to windows editor executables in wsl-hosted mode", async () => {
|
||||
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 = await Effect.runPromise(
|
||||
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("translates file-manager targets for wsl-hosted mode", async () => {
|
||||
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 = await Effect.runPromise(
|
||||
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", () => {
|
||||
it("resolves when command can be spawned", async () => {
|
||||
await expect(
|
||||
Effect.runPromise(
|
||||
launchDetached({
|
||||
command: process.execPath,
|
||||
args: ["-e", "process.exit(0)"],
|
||||
}),
|
||||
),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
it.effect("resolves when command can be spawned", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* launchDetached({
|
||||
command: process.execPath,
|
||||
args: ["-e", "process.exit(0)"],
|
||||
}).pipe(Effect.result);
|
||||
assertSuccess(result, undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it("rejects when command does not exist", async () => {
|
||||
const result = await Effect.runPromise(
|
||||
launchDetached({
|
||||
it.effect("rejects when command does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* launchDetached({
|
||||
command: `t3code-no-such-command-${Date.now()}`,
|
||||
args: [],
|
||||
}).pipe(Effect.result),
|
||||
);
|
||||
assert.equal(result._tag, "Failure");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isCommandAvailable", () => {
|
||||
function withTempDir(run: (dir: string) => void): void {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-"));
|
||||
try {
|
||||
run(dir);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
it("resolves win32 commands with PATHEXT", () => {
|
||||
withTempDir((dir) => {
|
||||
fs.writeFileSync(path.join(dir, "code.CMD"), "@echo off\r\n", "utf8");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
|
||||
});
|
||||
});
|
||||
|
||||
it("returns false when a command is not on PATH", () => {
|
||||
const env = {
|
||||
PATH: "",
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("definitely-not-installed", { platform: "win32", env }), false);
|
||||
});
|
||||
|
||||
it("does not treat bare files without executable extension as available on win32", () => {
|
||||
withTempDir((dir) => {
|
||||
fs.writeFileSync(path.join(dir, "npm"), "echo nope\r\n", "utf8");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("npm", { platform: "win32", env }), false);
|
||||
});
|
||||
});
|
||||
|
||||
it("appends PATHEXT for commands with non-executable extensions on win32", () => {
|
||||
withTempDir((dir) => {
|
||||
fs.writeFileSync(path.join(dir, "my.tool.CMD"), "@echo off\r\n", "utf8");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("my.tool", { platform: "win32", env }), true);
|
||||
});
|
||||
});
|
||||
|
||||
it("uses platform-specific PATH delimiter for platform overrides", () => {
|
||||
withTempDir((firstDir) => {
|
||||
withTempDir((secondDir) => {
|
||||
fs.writeFileSync(path.join(secondDir, "code.CMD"), "@echo off\r\n", "utf8");
|
||||
const env = {
|
||||
PATH: `${firstDir};${secondDir}`,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAvailableEditors", () => {
|
||||
it("returns only editors whose launch commands are available", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-editors-"));
|
||||
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({
|
||||
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 });
|
||||
}
|
||||
});
|
||||
}).pipe(Effect.result);
|
||||
assert.equal(result._tag, "Failure");
|
||||
}),
|
||||
);
|
||||
});
|
||||
+38
-308
@@ -6,19 +6,10 @@
|
||||
*
|
||||
* @module Open
|
||||
*/
|
||||
import { join } from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
import { EDITORS, type EditorId, type ServerRuntimeEnvironment } from "@t3tools/contracts";
|
||||
import { EDITORS, type EditorId } from "@t3tools/contracts";
|
||||
import { ServiceMap, Schema, Effect, Layer } from "effect";
|
||||
import {
|
||||
isExecutableFile,
|
||||
resolveCommandCandidates,
|
||||
resolvePathEnvironmentVariable,
|
||||
resolveWindowsPathExtensions,
|
||||
stripWrappingQuotes,
|
||||
} from "./commandResolution";
|
||||
import { spawnDetachedProcess, spawnProcessSync } from "./processRunner";
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
|
||||
// ==============================
|
||||
// Definitions
|
||||
@@ -39,101 +30,10 @@ interface EditorLaunch {
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
interface CommandAvailabilityOptions {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
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);
|
||||
}
|
||||
|
||||
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return "open";
|
||||
case "win32":
|
||||
return "explorer";
|
||||
default:
|
||||
return "xdg-open";
|
||||
}
|
||||
}
|
||||
|
||||
function resolvePathDelimiter(platform: NodeJS.Platform): string {
|
||||
return platform === "win32" ? ";" : ":";
|
||||
}
|
||||
|
||||
export function isCommandAvailable(
|
||||
command: string,
|
||||
options: CommandAvailabilityOptions = {},
|
||||
): boolean {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
|
||||
const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
|
||||
|
||||
if (command.includes("/") || command.includes("\\")) {
|
||||
return commandCandidates.some((candidate) =>
|
||||
isExecutableFile(candidate, { platform, windowsPathExtensions }),
|
||||
);
|
||||
}
|
||||
|
||||
const pathValue = resolvePathEnvironmentVariable(env);
|
||||
if (pathValue.length === 0) return false;
|
||||
const pathEntries = pathValue
|
||||
.split(resolvePathDelimiter(platform))
|
||||
.map((entry) => stripWrappingQuotes(entry.trim()))
|
||||
.filter((entry) => entry.length > 0);
|
||||
|
||||
for (const pathEntry of pathEntries) {
|
||||
for (const candidate of commandCandidates) {
|
||||
if (isExecutableFile(join(pathEntry, candidate), { platform, windowsPathExtensions })) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function resolveAvailableEditors(
|
||||
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 launch = resolveOpenCommand(editor.id, {
|
||||
platform,
|
||||
env,
|
||||
runtimeEnvironment,
|
||||
});
|
||||
if (launch.some((entry) => isCommandAvailable(entry, { platform, env }))) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
}
|
||||
|
||||
return available;
|
||||
return editorId === "cursor" && LINE_COLUMN_SUFFIX_PATTERN.test(target);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -162,223 +62,58 @@ 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,
|
||||
options: ResolveOpenOptions = {},
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): 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) {
|
||||
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] };
|
||||
return shouldUseGotoFlag(editorDef.id, input.cwd)
|
||||
? { command: editorDef.command, args: ["--goto", input.cwd] }
|
||||
: { command: editorDef.command, args: [input.cwd] };
|
||||
}
|
||||
|
||||
if (editorDef.id !== "file-manager") {
|
||||
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
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" });
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return { command: "open", args: [input.cwd] };
|
||||
case "win32":
|
||||
return { command: "explorer", args: [input.cwd] };
|
||||
default:
|
||||
return { command: "xdg-open", args: [input.cwd] };
|
||||
}
|
||||
|
||||
let target = stripLineColumnSuffix(input.cwd);
|
||||
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted" && command === "explorer.exe") {
|
||||
target = yield* Effect.try({
|
||||
try: () => 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.tryPromise({
|
||||
try: async () => {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
throw new OpenError({ message: `Editor command not found: ${launch.command}` });
|
||||
}
|
||||
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 })),
|
||||
);
|
||||
}
|
||||
|
||||
await spawnDetachedProcess(launch.command, [...launch.args]);
|
||||
},
|
||||
catch: (cause) =>
|
||||
Schema.is(OpenError)(cause)
|
||||
? cause
|
||||
: new OpenError({ message: "failed to spawn detached process", cause }),
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
};
|
||||
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (cause) =>
|
||||
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
|
||||
);
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
@@ -388,16 +123,11 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
return {
|
||||
openBrowser: (target) => {
|
||||
const launch = resolveBrowserLaunch(target);
|
||||
if (launch) {
|
||||
return launchDetached(launch);
|
||||
}
|
||||
return Effect.tryPromise({
|
||||
openBrowser: (target) =>
|
||||
Effect.tryPromise({
|
||||
try: () => open.default(target),
|
||||
catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
|
||||
});
|
||||
},
|
||||
}),
|
||||
openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
|
||||
} satisfies OpenShape;
|
||||
});
|
||||
|
||||
@@ -415,7 +415,8 @@ const make = Effect.gen(function* () {
|
||||
: event.threadId !== undefined
|
||||
? ProviderThreadId.makeUnsafe(event.threadId)
|
||||
: null;
|
||||
const providerThreadId = providerThreadIdFromEvent ?? sessionProviderThreadId ?? null;
|
||||
const providerThreadId =
|
||||
providerThreadIdFromEvent ?? sessionProviderThreadId ?? null;
|
||||
const status =
|
||||
event.type === "turn.started"
|
||||
? "running"
|
||||
|
||||
@@ -1,25 +1,6 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
makeRuntimeCommand,
|
||||
resolveProcessLaunchPlan,
|
||||
runProcess,
|
||||
spawnDetachedProcess,
|
||||
spawnProcessSync,
|
||||
} from "./processRunner";
|
||||
|
||||
function withTempDir(run: (dir: string) => void): void {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-process-runner-"));
|
||||
try {
|
||||
run(dir);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
import { runProcess } from "./processRunner";
|
||||
|
||||
describe("runProcess", () => {
|
||||
it("fails when output exceeds max buffer in default mode", async () => {
|
||||
@@ -39,161 +20,4 @@ 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();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveProcessLaunchPlan", () => {
|
||||
it("resolves native windows executables without using a shell", () => {
|
||||
withTempDir((dir) => {
|
||||
fs.writeFileSync(path.join(dir, "git.EXE"), "MZ");
|
||||
const plan = resolveProcessLaunchPlan("git", ["status"], {
|
||||
env: {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
},
|
||||
inheritParentEnv: false,
|
||||
runtimeEnvironment: {
|
||||
platform: "windows",
|
||||
pathStyle: "windows",
|
||||
isWsl: false,
|
||||
windowsInteropMode: "windows-native",
|
||||
wslDistroName: null,
|
||||
},
|
||||
});
|
||||
|
||||
expect(plan.command).toBe(path.join(dir, "git.EXE"));
|
||||
expect(plan.args).toEqual(["status"]);
|
||||
expect(plan.shell).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it("wraps windows batch launchers through cmd.exe without default shell mode", () => {
|
||||
withTempDir((dir) => {
|
||||
const wrapperPath = path.join(dir, "code.CMD");
|
||||
fs.writeFileSync(wrapperPath, "@echo off\r\n");
|
||||
const plan = resolveProcessLaunchPlan("code", ["C:\\repo\\a&b.ts"], {
|
||||
env: {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
COMSPEC: "C:\\Windows\\System32\\cmd.exe",
|
||||
},
|
||||
inheritParentEnv: false,
|
||||
runtimeEnvironment: {
|
||||
platform: "windows",
|
||||
pathStyle: "windows",
|
||||
isWsl: false,
|
||||
windowsInteropMode: "windows-native",
|
||||
wslDistroName: null,
|
||||
},
|
||||
});
|
||||
|
||||
expect(plan.command).toBe("C:\\Windows\\System32\\cmd.exe");
|
||||
expect(plan.args.slice(0, 3)).toEqual(["/d", "/s", "/c"]);
|
||||
expect(plan.args[3]).toBe(`"${wrapperPath}" "C:\\repo\\a&b.ts"`);
|
||||
expect(plan.shell).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves relative batch launchers against the configured cwd", () => {
|
||||
withTempDir((dir) => {
|
||||
const wrapperPath = path.join(dir, "code.CMD");
|
||||
fs.writeFileSync(wrapperPath, "@echo off\r\n");
|
||||
|
||||
const plan = resolveProcessLaunchPlan("./code", ["pkg@^1.0"], {
|
||||
cwd: dir,
|
||||
env: {
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
COMSPEC: "C:\\Windows\\System32\\cmd.exe",
|
||||
},
|
||||
inheritParentEnv: false,
|
||||
runtimeEnvironment: {
|
||||
platform: "windows",
|
||||
pathStyle: "windows",
|
||||
isWsl: false,
|
||||
windowsInteropMode: "windows-native",
|
||||
wslDistroName: null,
|
||||
},
|
||||
});
|
||||
|
||||
expect(plan.command).toBe("C:\\Windows\\System32\\cmd.exe");
|
||||
expect(plan.args[3]).toBe(`"${wrapperPath}" "pkg@^1.0"`);
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps wsl-hosted commands on the linux direct exec path", () => {
|
||||
const plan = resolveProcessLaunchPlan("code", ["/home/julius/repo"], {
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
});
|
||||
|
||||
expect(plan.command).toBe("code");
|
||||
expect(plan.args).toEqual(["/home/julius/repo"]);
|
||||
expect(plan.shell).toBe(false);
|
||||
});
|
||||
|
||||
it("preserves explicit shell configuration", () => {
|
||||
const plan = resolveProcessLaunchPlan("git", ["status"], {
|
||||
shell: true,
|
||||
runtimeEnvironment: {
|
||||
platform: "windows",
|
||||
pathStyle: "windows",
|
||||
isWsl: false,
|
||||
windowsInteropMode: "windows-native",
|
||||
wslDistroName: null,
|
||||
},
|
||||
});
|
||||
|
||||
expect(plan.command).toBe("git");
|
||||
expect(plan.args).toEqual(["status"]);
|
||||
expect(plan.shell).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("makeRuntimeCommand", () => {
|
||||
it("uses the shared launch plan for batch commands on windows", () => {
|
||||
withTempDir((dir) => {
|
||||
const wrapperPath = path.join(dir, "code.CMD");
|
||||
fs.writeFileSync(wrapperPath, "@echo off\r\n");
|
||||
|
||||
const command = makeRuntimeCommand("code", ["C:\\repo\\a&b.ts"], {
|
||||
env: {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
COMSPEC: "C:\\Windows\\System32\\cmd.exe",
|
||||
},
|
||||
extendEnv: false,
|
||||
runtimeEnvironment: {
|
||||
platform: "windows",
|
||||
pathStyle: "windows",
|
||||
isWsl: false,
|
||||
windowsInteropMode: "windows-native",
|
||||
wslDistroName: null,
|
||||
},
|
||||
});
|
||||
|
||||
expect(command.command).toBe("C:\\Windows\\System32\\cmd.exe");
|
||||
expect(command.args).toEqual(["/d", "/s", "/c", `"${wrapperPath}" "C:\\repo\\a&b.ts"`]);
|
||||
expect(command.options.shell).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,58 +1,4 @@
|
||||
import {
|
||||
type ChildProcess as ChildProcessHandle,
|
||||
type ChildProcessWithoutNullStreams,
|
||||
spawn,
|
||||
spawnSync,
|
||||
type StdioOptions,
|
||||
} from "node:child_process";
|
||||
import { extname, join } from "node:path";
|
||||
|
||||
import type { ServerRuntimeEnvironment } from "@t3tools/contracts";
|
||||
import { Effect, Exit, Scope } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
resolveCommandCandidates,
|
||||
resolveExecutableFile,
|
||||
resolvePathEnvironmentVariable,
|
||||
resolveWindowsPathExtensions,
|
||||
stripWrappingQuotes,
|
||||
} from "./commandResolution";
|
||||
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 ProcessLaunchPlanOptions extends RuntimeShellOptions {
|
||||
cwd?: string | undefined;
|
||||
env?: NodeJS.ProcessEnv | Record<string, string | undefined> | undefined;
|
||||
inheritParentEnv?: boolean | undefined;
|
||||
}
|
||||
|
||||
interface ProcessSpawnOptions extends ProcessSpawnBaseOptions {
|
||||
stdio?: StdioOptions | undefined;
|
||||
detached?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface RuntimeCommandOptions extends ChildProcess.CommandOptions {
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
}
|
||||
|
||||
interface ProcessSpawnSyncOptions extends ProcessSpawnBaseOptions {
|
||||
stdio?: StdioOptions | undefined;
|
||||
detached?: boolean | undefined;
|
||||
encoding?: BufferEncoding | undefined;
|
||||
input?: string | undefined;
|
||||
}
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
export interface ProcessRunOptions {
|
||||
cwd?: string | undefined;
|
||||
@@ -62,8 +8,6 @@ export interface ProcessRunOptions {
|
||||
allowNonZeroExit?: boolean | undefined;
|
||||
maxBufferBytes?: number | undefined;
|
||||
outputMode?: "error" | "truncate" | undefined;
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
shell?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface ProcessRunResult {
|
||||
@@ -76,305 +20,10 @@ export interface ProcessRunResult {
|
||||
stderrTruncated?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface ProcessLaunchPlan {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly shell: boolean | string;
|
||||
readonly runtimeEnvironment: ServerRuntimeEnvironment;
|
||||
}
|
||||
|
||||
interface ResolvedWindowsCommand {
|
||||
readonly path: string;
|
||||
readonly kind: "native" | "batch";
|
||||
}
|
||||
|
||||
const WINDOWS_BATCH_EXECUTABLE_EXTENSIONS = new Set([".CMD", ".BAT"]);
|
||||
|
||||
function commandLabel(command: string, args: readonly string[]): string {
|
||||
return [command, ...args].join(" ");
|
||||
}
|
||||
|
||||
function resolveRuntimeEnvironment(
|
||||
runtimeEnvironment: ServerRuntimeEnvironment | undefined,
|
||||
): ServerRuntimeEnvironment {
|
||||
return runtimeEnvironment ?? detectServerRuntimeEnvironment();
|
||||
}
|
||||
|
||||
function resolveEffectiveEnvironment(options: ProcessLaunchPlanOptions): NodeJS.ProcessEnv {
|
||||
const env = (options.env ?? {}) as NodeJS.ProcessEnv;
|
||||
if (options.inheritParentEnv === false) {
|
||||
return { ...env };
|
||||
}
|
||||
|
||||
return {
|
||||
...process.env,
|
||||
...env,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveWindowsCommand(
|
||||
command: string,
|
||||
env: NodeJS.ProcessEnv,
|
||||
cwd?: string,
|
||||
): ResolvedWindowsCommand | null {
|
||||
const windowsPathExtensions = resolveWindowsPathExtensions(env);
|
||||
const candidates = resolveCommandCandidates(command, "win32", windowsPathExtensions);
|
||||
|
||||
const classify = (filePath: string): ResolvedWindowsCommand => {
|
||||
const extension = extname(filePath).toUpperCase();
|
||||
return {
|
||||
path: filePath,
|
||||
kind: WINDOWS_BATCH_EXECUTABLE_EXTENSIONS.has(extension) ? "batch" : "native",
|
||||
};
|
||||
};
|
||||
|
||||
if (command.includes("/") || command.includes("\\")) {
|
||||
for (const candidate of candidates) {
|
||||
const resolvedCandidate = resolveExecutableFile(candidate, {
|
||||
platform: "win32",
|
||||
windowsPathExtensions,
|
||||
cwd,
|
||||
});
|
||||
if (resolvedCandidate) {
|
||||
return classify(resolvedCandidate);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const pathEntries = resolvePathEnvironmentVariable(env)
|
||||
.split(";")
|
||||
.map((entry) => stripWrappingQuotes(entry.trim()))
|
||||
.filter((entry) => entry.length > 0);
|
||||
|
||||
for (const pathEntry of pathEntries) {
|
||||
for (const candidate of candidates) {
|
||||
const candidatePath = join(pathEntry, candidate);
|
||||
if (
|
||||
resolveExecutableFile(candidatePath, {
|
||||
platform: "win32",
|
||||
windowsPathExtensions,
|
||||
})
|
||||
) {
|
||||
return classify(candidatePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function quoteWindowsBatchArgument(argument: string): string {
|
||||
if (argument.length === 0) {
|
||||
return '""';
|
||||
}
|
||||
|
||||
const escaped = argument
|
||||
.replaceAll("%", "%%")
|
||||
.replace(/(\\*)"/g, (_match, slashes: string) => `${slashes}${slashes}\\"`)
|
||||
.replace(/(\\+)$/g, "$1$1");
|
||||
return `"${escaped}"`;
|
||||
}
|
||||
|
||||
function buildWindowsBatchCommandLine(
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
): string {
|
||||
return [quoteWindowsBatchArgument(command), ...args.map(quoteWindowsBatchArgument)].join(" ");
|
||||
}
|
||||
|
||||
function resolveWindowsCommandShell(env: NodeJS.ProcessEnv): string {
|
||||
return env.ComSpec ?? env.COMSPEC ?? process.env.ComSpec ?? process.env.COMSPEC ?? "cmd.exe";
|
||||
}
|
||||
|
||||
export function resolveProcessLaunchPlan(
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options: ProcessLaunchPlanOptions = {},
|
||||
): ProcessLaunchPlan {
|
||||
const runtimeEnvironment = resolveRuntimeEnvironment(options.runtimeEnvironment);
|
||||
if (options.shell !== undefined) {
|
||||
return {
|
||||
command,
|
||||
args: [...args],
|
||||
shell: options.shell,
|
||||
runtimeEnvironment,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtimeEnvironment.platform !== "windows") {
|
||||
return {
|
||||
command,
|
||||
args: [...args],
|
||||
shell: false,
|
||||
runtimeEnvironment,
|
||||
};
|
||||
}
|
||||
|
||||
const env = resolveEffectiveEnvironment(options);
|
||||
const resolved = resolveWindowsCommand(command, env, options.cwd);
|
||||
if (!resolved) {
|
||||
return {
|
||||
command,
|
||||
args: [...args],
|
||||
shell: false,
|
||||
runtimeEnvironment,
|
||||
};
|
||||
}
|
||||
|
||||
if (resolved.kind === "batch") {
|
||||
return {
|
||||
command: resolveWindowsCommandShell(env),
|
||||
args: ["/d", "/s", "/c", buildWindowsBatchCommandLine(resolved.path, args)],
|
||||
shell: false,
|
||||
runtimeEnvironment,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
command: resolved.path,
|
||||
args: [...args],
|
||||
shell: false,
|
||||
runtimeEnvironment,
|
||||
};
|
||||
}
|
||||
|
||||
function toSpawnOptions(
|
||||
options: ProcessSpawnOptions,
|
||||
launchPlan: ProcessLaunchPlan,
|
||||
) {
|
||||
return {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
shell: launchPlan.shell,
|
||||
...(options.stdio !== undefined ? { stdio: options.stdio } : {}),
|
||||
...(options.detached !== undefined ? { detached: options.detached } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function toRuntimeCommandOptions(
|
||||
options: RuntimeCommandOptions = {},
|
||||
shell: boolean | string,
|
||||
): ChildProcess.CommandOptions {
|
||||
const { runtimeEnvironment: _runtimeEnvironment, shell: _shell, ...commandOptions } = options;
|
||||
return {
|
||||
...commandOptions,
|
||||
shell,
|
||||
};
|
||||
}
|
||||
|
||||
export function makeRuntimeCommand(
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options: RuntimeCommandOptions = {},
|
||||
): ChildProcess.StandardCommand {
|
||||
const launchPlan = resolveProcessLaunchPlan(command, args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
shell: options.shell,
|
||||
inheritParentEnv: options.extendEnv !== false,
|
||||
});
|
||||
return ChildProcess.make(launchPlan.command, launchPlan.args, {
|
||||
...toRuntimeCommandOptions(options, launchPlan.shell),
|
||||
});
|
||||
}
|
||||
|
||||
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 {
|
||||
const launchPlan = resolveProcessLaunchPlan(command, args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
shell: options.shell,
|
||||
inheritParentEnv: options.env === undefined,
|
||||
});
|
||||
|
||||
return spawn(launchPlan.command, launchPlan.args, toSpawnOptions(options, launchPlan));
|
||||
}
|
||||
|
||||
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 = {},
|
||||
) {
|
||||
const launchPlan = resolveProcessLaunchPlan(command, args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
shell: options.shell,
|
||||
inheritParentEnv: options.env === undefined,
|
||||
});
|
||||
|
||||
return spawnSync(launchPlan.command, launchPlan.args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
shell: launchPlan.shell,
|
||||
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)}.`);
|
||||
@@ -388,26 +37,11 @@ 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"})`;
|
||||
@@ -436,43 +70,6 @@ function normalizeBufferError(
|
||||
|
||||
const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* On Windows, commands may still execute through a `cmd.exe` wrapper for
|
||||
* explicit shell usage or `.cmd` / `.bat` launchers. `child.kill()` only
|
||||
* terminates the 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,
|
||||
@@ -511,7 +108,11 @@ export async function runProcess(
|
||||
const outputMode = options.outputMode ?? "error";
|
||||
|
||||
return new Promise<ProcessRunResult>((resolve, reject) => {
|
||||
const child = spawnPipedProcess(command, args, options);
|
||||
const child = spawn(command, args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
stdio: "pipe",
|
||||
});
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
@@ -525,15 +126,9 @@ export async function runProcess(
|
||||
|
||||
const timeoutTimer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
killProcessTree(child, {
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
signal: "SIGTERM",
|
||||
});
|
||||
child.kill("SIGTERM");
|
||||
forceKillTimer = setTimeout(() => {
|
||||
killProcessTree(child, {
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
signal: "SIGKILL",
|
||||
});
|
||||
child.kill("SIGKILL");
|
||||
}, 1_000);
|
||||
}, timeoutMs);
|
||||
|
||||
@@ -548,10 +143,7 @@ export async function runProcess(
|
||||
};
|
||||
|
||||
const fail = (error: Error): void => {
|
||||
killProcessTree(child, {
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
signal: "SIGTERM",
|
||||
});
|
||||
child.kill("SIGTERM");
|
||||
finalize(() => {
|
||||
reject(error);
|
||||
});
|
||||
@@ -624,7 +216,7 @@ export async function runProcess(
|
||||
|
||||
finalize(() => {
|
||||
if (!options.allowNonZeroExit && (timedOut || (code !== null && code !== 0))) {
|
||||
reject(normalizeExitError(command, args, result, options.runtimeEnvironment));
|
||||
reject(normalizeExitError(command, args, result));
|
||||
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, Option, Stream } from "effect";
|
||||
import { Effect, Fiber, Layer, Stream } from "effect";
|
||||
|
||||
import {
|
||||
CodexAppServerManager,
|
||||
@@ -24,7 +24,6 @@ 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);
|
||||
@@ -122,21 +121,10 @@ 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),
|
||||
),
|
||||
);
|
||||
@@ -171,7 +159,6 @@ 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),
|
||||
),
|
||||
);
|
||||
@@ -208,7 +195,6 @@ 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, Option, Queue, Schema, Stream } from "effect";
|
||||
import { Effect, FileSystem, Layer, Queue, Schema, Stream } from "effect";
|
||||
|
||||
import {
|
||||
ProviderAdapterProcessError,
|
||||
@@ -28,12 +28,10 @@ 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 { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
|
||||
const PROVIDER = "codex" as const;
|
||||
|
||||
@@ -41,7 +39,6 @@ export interface CodexAdapterLiveOptions {
|
||||
readonly manager?: CodexAppServerManager;
|
||||
readonly makeManager?: () => CodexAppServerManager;
|
||||
readonly nativeEventLogPath?: string;
|
||||
readonly nativeEventLogger?: EventNdjsonLogger;
|
||||
}
|
||||
|
||||
function toMessage(cause: unknown, fallback: string): string {
|
||||
@@ -433,15 +430,10 @@ 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?.nativeEventLogger ??
|
||||
(options?.nativeEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
|
||||
stream: "native",
|
||||
})
|
||||
: undefined);
|
||||
options?.nativeEventLogPath !== undefined
|
||||
? makeEventNdjsonLogger(options.nativeEventLogPath)
|
||||
: undefined;
|
||||
|
||||
const manager = yield* Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
@@ -451,7 +443,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
if (options?.makeManager) {
|
||||
return options.makeManager();
|
||||
}
|
||||
return new CodexAppServerManager(services);
|
||||
return new CodexAppServerManager();
|
||||
}),
|
||||
(manager) =>
|
||||
Effect.sync(() => {
|
||||
@@ -497,17 +489,17 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* toRequestError(
|
||||
input.sessionId,
|
||||
"turn/start",
|
||||
new Error(`Invalid attachment id '${attachment.id}'.`),
|
||||
return yield* Effect.fail(
|
||||
toRequestError(
|
||||
input.sessionId,
|
||||
"turn/start",
|
||||
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")}`,
|
||||
@@ -590,29 +582,13 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
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);
|
||||
const listener = (event: ProviderEvent) => {
|
||||
nativeEventLogger?.write({
|
||||
observedAt: new Date().toISOString(),
|
||||
event,
|
||||
});
|
||||
|
||||
const listener = (event: ProviderEvent) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeNativeEvent(event);
|
||||
yield* Queue.offerAll(runtimeEventQueue, mapToRuntimeEvents(event));
|
||||
}).pipe(Effect.runPromiseWith(services));
|
||||
Queue.offerAllUnsafe(runtimeEventQueue, mapToRuntimeEvents(event));
|
||||
};
|
||||
manager.on("event", listener);
|
||||
return listener;
|
||||
}),
|
||||
|
||||
@@ -2,165 +2,36 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
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.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");
|
||||
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");
|
||||
|
||||
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 });
|
||||
try {
|
||||
const logger = makeEventNdjsonLogger(filePath);
|
||||
expect(logger).toBeDefined();
|
||||
if (!logger) {
|
||||
return;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
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");
|
||||
logger.write({ type: "native", payload: { id: "evt-1" } });
|
||||
logger.write({ type: "canonical", payload: { id: "evt-2" } });
|
||||
logger.close();
|
||||
|
||||
try {
|
||||
const logger = yield* makeEventNdjsonLogger(basePath, { stream: "orchestration" });
|
||||
assert.notEqual(logger, undefined);
|
||||
if (!logger) {
|
||||
return;
|
||||
}
|
||||
const raw = fs.readFileSync(filePath, "utf8").trim();
|
||||
const lines = raw.split("\n");
|
||||
expect(lines.length).toBe(2);
|
||||
|
||||
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 });
|
||||
}
|
||||
}),
|
||||
);
|
||||
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 });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,257 +1,66 @@
|
||||
/**
|
||||
* Provider event logger helper.
|
||||
* Provider event NDJSON logger helper.
|
||||
*
|
||||
* 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.
|
||||
* Best-effort writer for observability logs. Failures are downgraded to warnings
|
||||
* so provider runtime behavior is unaffected.
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import type { ThreadId } from "@t3tools/contracts";
|
||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import { Effect, Exit, Logger, Scope } from "effect";
|
||||
import { createLogger } from "../../logger.ts";
|
||||
|
||||
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";
|
||||
const logger = createLogger("provider-observability");
|
||||
|
||||
export interface EventNdjsonLogger {
|
||||
readonly filePath: string;
|
||||
write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void>;
|
||||
close: () => Effect.Effect<void>;
|
||||
write: (record: unknown) => void;
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
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";
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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 };
|
||||
}
|
||||
});
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
});
|
||||
try {
|
||||
let broken = false;
|
||||
|
||||
return {
|
||||
filePath,
|
||||
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);
|
||||
});
|
||||
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 });
|
||||
}
|
||||
},
|
||||
close() {
|
||||
return Effect.gen(function* () {
|
||||
for (const writer of threadWriters.values()) {
|
||||
yield* writer.close();
|
||||
}
|
||||
threadWriters.clear();
|
||||
});
|
||||
// no-op for sync append logger
|
||||
},
|
||||
} satisfies EventNdjsonLogger;
|
||||
});
|
||||
};
|
||||
} catch (error) {
|
||||
logger.warn("failed to create provider event log file", { filePath, error });
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -1,198 +0,0 @@
|
||||
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;
|
||||
signal?: NodeJS.Signals | 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.");
|
||||
});
|
||||
|
||||
it.effect("reports signal-based auth probe failures without 'code null'", () =>
|
||||
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: "", code: null, signal: "SIGTERM" };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
);
|
||||
assert.strictEqual(status.status, "warning");
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Could not verify Codex authentication status. Command exited from signal SIGTERM.",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
// ── 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");
|
||||
});
|
||||
@@ -1,315 +0,0 @@
|
||||
/**
|
||||
* ProviderHealthLive - Startup-time provider health checks.
|
||||
*
|
||||
* Performs one-time provider readiness probes when the server starts and
|
||||
* keeps the resulting snapshot in memory for `server.getConfig`.
|
||||
*
|
||||
* Uses 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 signal?: NodeJS.Signals | 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 result.signal
|
||||
? `Command exited from signal ${result.signal}.`
|
||||
: "Command exited without 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,
|
||||
signal: result.signal,
|
||||
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,11 +30,10 @@ import {
|
||||
ProviderSessionDirectory,
|
||||
type ProviderSessionBinding,
|
||||
} from "../Services/ProviderSessionDirectory.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
|
||||
export interface ProviderServiceLiveOptions {
|
||||
readonly canonicalEventLogPath?: string;
|
||||
readonly canonicalEventLogger?: EventNdjsonLogger;
|
||||
}
|
||||
|
||||
const ProviderRollbackConversationInput = Schema.Struct({
|
||||
@@ -109,12 +108,9 @@ function readPersistedCwd(
|
||||
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const canonicalEventLogger =
|
||||
options?.canonicalEventLogger ??
|
||||
(options?.canonicalEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, {
|
||||
stream: "canonical",
|
||||
})
|
||||
: undefined);
|
||||
options?.canonicalEventLogPath !== undefined
|
||||
? makeEventNdjsonLogger(options.canonicalEventLogPath)
|
||||
: undefined;
|
||||
|
||||
const registry = yield* ProviderAdapterRegistry;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
@@ -144,20 +140,12 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
canonicalizeRuntimeEventSession(event).pipe(
|
||||
Effect.tap((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.sync(() => {
|
||||
canonicalEventLogger?.write({
|
||||
observedAt: new Date().toISOString(),
|
||||
event: canonicalEvent,
|
||||
});
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
|
||||
Effect.asVoid,
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
/**
|
||||
* 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",
|
||||
) {}
|
||||
@@ -1,72 +0,0 @@
|
||||
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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,54 +0,0 @@
|
||||
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,7 +23,6 @@ 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";
|
||||
@@ -38,31 +37,21 @@ import { NodePtyAdapterLive } from "./terminal/Layers/NodePTY";
|
||||
export function makeServerProviderLayer(): Layer.Layer<
|
||||
ProviderService,
|
||||
ProviderUnsupportedError,
|
||||
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem | NodeServices.NodeServices
|
||||
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const { stateDir } = yield* ServerConfig;
|
||||
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 providerLogsDir = path.join(stateDir, "logs", "providers");
|
||||
const codexAdapterLayer = makeCodexAdapterLive({
|
||||
nativeEventLogPath: path.join(providerLogsDir, "provider-native.ndjson"),
|
||||
});
|
||||
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(Layer.provide(codexAdapterLayer));
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
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));
|
||||
return makeProviderServiceLive({
|
||||
canonicalEventLogPath: path.join(providerLogsDir, "provider-canonical.ndjson"),
|
||||
}).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer));
|
||||
}).pipe(Layer.unwrap);
|
||||
}
|
||||
|
||||
@@ -105,11 +94,7 @@ export function makeServerRuntimeServicesLayer() {
|
||||
);
|
||||
|
||||
const terminalLayer = TerminalManagerLive.pipe(
|
||||
Layer.provide(
|
||||
typeof Bun !== "undefined" && process.platform !== "win32"
|
||||
? BunPtyAdapterLive
|
||||
: NodePtyAdapterLive,
|
||||
),
|
||||
Layer.provide(typeof Bun !== "undefined" ? BunPtyAdapterLive : NodePtyAdapterLive),
|
||||
);
|
||||
|
||||
const gitManagerLayer = GitManagerLive.pipe(
|
||||
|
||||
@@ -4,7 +4,6 @@ import path from "node:path";
|
||||
|
||||
import {
|
||||
DEFAULT_TERMINAL_ID,
|
||||
type ServerRuntimeEnvironment,
|
||||
type TerminalEvent,
|
||||
type TerminalOpenInput,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -17,11 +16,7 @@ import {
|
||||
type PtyProcess,
|
||||
type PtySpawnInput,
|
||||
} from "../Services/PTY";
|
||||
import {
|
||||
resolveShellCandidates,
|
||||
TerminalManagerRuntime,
|
||||
validateTerminalCwdForRuntime,
|
||||
} from "./Manager";
|
||||
import { TerminalManagerRuntime } from "./Manager";
|
||||
import { Effect, Encoding } from "effect";
|
||||
|
||||
class FakePtyProcess implements PtyProcess {
|
||||
@@ -177,7 +172,6 @@ describe("TerminalManager", () => {
|
||||
options: {
|
||||
shellResolver?: () => string;
|
||||
subprocessChecker?: (terminalPid: number) => Promise<boolean>;
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment;
|
||||
subprocessPollIntervalMs?: number;
|
||||
processKillGraceMs?: number;
|
||||
maxRetainedInactiveSessions?: number;
|
||||
@@ -192,7 +186,6 @@ describe("TerminalManager", () => {
|
||||
ptyAdapter,
|
||||
historyLineLimit,
|
||||
shellResolver: options.shellResolver ?? (() => "/bin/bash"),
|
||||
...(options.runtimeEnvironment ? { runtimeEnvironment: options.runtimeEnvironment } : {}),
|
||||
...(options.subprocessChecker ? { subprocessChecker: options.subprocessChecker } : {}),
|
||||
...(options.subprocessPollIntervalMs
|
||||
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
|
||||
@@ -676,93 +669,4 @@ 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,14 +9,12 @@ 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";
|
||||
@@ -37,8 +35,6 @@ 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);
|
||||
@@ -48,22 +44,19 @@ const decodeTerminalCloseInput = Schema.decodeUnknownSync(TerminalCloseInput);
|
||||
|
||||
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
|
||||
|
||||
function defaultShellResolver(runtimeEnvironment: ServerRuntimeEnvironment): string {
|
||||
if (runtimeEnvironment.platform === "windows") {
|
||||
function defaultShellResolver(): string {
|
||||
if (process.platform === "win32") {
|
||||
return process.env.ComSpec ?? "cmd.exe";
|
||||
}
|
||||
return process.env.SHELL ?? "bash";
|
||||
}
|
||||
|
||||
function normalizeShellCommand(
|
||||
value: string | undefined,
|
||||
runtimeEnvironment: ServerRuntimeEnvironment,
|
||||
): string | null {
|
||||
function normalizeShellCommand(value: string | undefined): string | null {
|
||||
if (!value) return null;
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) return null;
|
||||
|
||||
if (runtimeEnvironment.platform === "windows") {
|
||||
if (process.platform === "win32") {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
@@ -72,13 +65,10 @@ function normalizeShellCommand(
|
||||
return firstToken.replace(/^['"]|['"]$/g, "");
|
||||
}
|
||||
|
||||
function shellCandidateFromCommand(
|
||||
command: string | null,
|
||||
runtimeEnvironment: ServerRuntimeEnvironment,
|
||||
): ShellCandidate | null {
|
||||
function shellCandidateFromCommand(command: string | null): ShellCandidate | null {
|
||||
if (!command || command.length === 0) return null;
|
||||
const shellName = path.basename(command).toLowerCase();
|
||||
if (runtimeEnvironment.platform !== "windows" && shellName === "zsh") {
|
||||
if (process.platform !== "win32" && shellName === "zsh") {
|
||||
return { shell: command, args: ["-o", "nopromptsp"] };
|
||||
}
|
||||
return { shell: command };
|
||||
@@ -102,36 +92,27 @@ function uniqueShellCandidates(candidates: Array<ShellCandidate | null>): ShellC
|
||||
return ordered;
|
||||
}
|
||||
|
||||
export function resolveShellCandidates(
|
||||
shellResolver: () => string,
|
||||
runtimeEnvironment: ServerRuntimeEnvironment = detectServerRuntimeEnvironment(),
|
||||
): ShellCandidate[] {
|
||||
const requested = shellCandidateFromCommand(
|
||||
normalizeShellCommand(shellResolver(), runtimeEnvironment),
|
||||
runtimeEnvironment,
|
||||
);
|
||||
function resolveShellCandidates(shellResolver: () => string): ShellCandidate[] {
|
||||
const requested = shellCandidateFromCommand(normalizeShellCommand(shellResolver()));
|
||||
|
||||
if (runtimeEnvironment.platform === "windows") {
|
||||
if (process.platform === "win32") {
|
||||
return uniqueShellCandidates([
|
||||
requested,
|
||||
shellCandidateFromCommand(process.env.ComSpec ?? null, runtimeEnvironment),
|
||||
shellCandidateFromCommand("powershell.exe", runtimeEnvironment),
|
||||
shellCandidateFromCommand("cmd.exe", runtimeEnvironment),
|
||||
shellCandidateFromCommand(process.env.ComSpec ?? null),
|
||||
shellCandidateFromCommand("powershell.exe"),
|
||||
shellCandidateFromCommand("cmd.exe"),
|
||||
]);
|
||||
}
|
||||
|
||||
return uniqueShellCandidates([
|
||||
requested,
|
||||
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),
|
||||
shellCandidateFromCommand(normalizeShellCommand(process.env.SHELL)),
|
||||
shellCandidateFromCommand("/bin/zsh"),
|
||||
shellCandidateFromCommand("/bin/bash"),
|
||||
shellCandidateFromCommand("/bin/sh"),
|
||||
shellCandidateFromCommand("zsh"),
|
||||
shellCandidateFromCommand("bash"),
|
||||
shellCandidateFromCommand("sh"),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -197,13 +178,6 @@ 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;
|
||||
@@ -256,37 +230,14 @@ async function checkPosixSubprocessActivity(terminalPid: number): Promise<boolea
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
async function defaultSubprocessChecker(terminalPid: number): Promise<boolean> {
|
||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isWindowsPath(cwd)) {
|
||||
return `Terminal cwd does not match POSIX runtime path style: ${cwd}`;
|
||||
if (process.platform === "win32") {
|
||||
return checkWindowsSubprocessActivity(terminalPid);
|
||||
}
|
||||
return null;
|
||||
return checkPosixSubprocessActivity(terminalPid);
|
||||
}
|
||||
|
||||
function capHistory(history: string, maxLines: number): string {
|
||||
@@ -365,7 +316,6 @@ interface TerminalManagerOptions {
|
||||
ptyAdapter: PtyAdapterShape;
|
||||
shellResolver?: () => string;
|
||||
subprocessChecker?: TerminalSubprocessChecker;
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment;
|
||||
subprocessPollIntervalMs?: number;
|
||||
processKillGraceMs?: number;
|
||||
maxRetainedInactiveSessions?: number;
|
||||
@@ -383,7 +333,6 @@ 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;
|
||||
@@ -394,15 +343,12 @@ 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.runtimeEnvironment));
|
||||
this.shellResolver = options.shellResolver ?? defaultShellResolver;
|
||||
this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS;
|
||||
this.subprocessChecker =
|
||||
options.subprocessChecker ?? createDefaultSubprocessChecker(this.runtimeEnvironment);
|
||||
this.subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
|
||||
this.subprocessPollIntervalMs =
|
||||
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
|
||||
this.processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;
|
||||
@@ -643,7 +589,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
let ptyProcess: PtyProcess | null = null;
|
||||
let startedShell: string | null = null;
|
||||
try {
|
||||
const shellCandidates = resolveShellCandidates(this.shellResolver, this.runtimeEnvironment);
|
||||
const shellCandidates = resolveShellCandidates(this.shellResolver);
|
||||
const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv);
|
||||
let lastSpawnError: unknown = null;
|
||||
|
||||
@@ -1105,11 +1051,6 @@ 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);
|
||||
@@ -1232,11 +1173,10 @@ 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, runtimeEnvironment })),
|
||||
Effect.sync(() => new TerminalManagerRuntime({ logsDir, ptyAdapter })),
|
||||
(r) => Effect.sync(() => r.dispose()),
|
||||
);
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@ import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serve
|
||||
|
||||
import {
|
||||
DEFAULT_TERMINAL_ID,
|
||||
EDITORS,
|
||||
EventId,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
@@ -25,7 +24,6 @@ import {
|
||||
WS_METHODS,
|
||||
type WebSocketResponse,
|
||||
type ProviderRuntimeEvent,
|
||||
type ServerProviderStatus,
|
||||
type KeybindingsConfig,
|
||||
type ResolvedKeybindingsConfig,
|
||||
type WsPush,
|
||||
@@ -44,14 +42,12 @@ 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[];
|
||||
@@ -72,22 +68,6 @@ 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>();
|
||||
@@ -360,15 +340,6 @@ function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsCon
|
||||
}
|
||||
|
||||
const DEFAULT_RESOLVED_KEYBINDINGS = compileKeybindings([...DEFAULT_KEYBINDINGS]);
|
||||
const VALID_EDITOR_IDS = new Set(EDITORS.map((editor) => editor.id));
|
||||
|
||||
function expectAvailableEditors(value: unknown): void {
|
||||
expect(Array.isArray(value)).toBe(true);
|
||||
for (const editorId of value as unknown[]) {
|
||||
expect(typeof editorId).toBe("string");
|
||||
expect(VALID_EDITOR_IDS.has(editorId as (typeof EDITORS)[number]["id"])).toBe(true);
|
||||
}
|
||||
}
|
||||
|
||||
describe("WebSocket Server", () => {
|
||||
let server: Http.Server | null = null;
|
||||
@@ -396,7 +367,6 @@ describe("WebSocket Server", () => {
|
||||
stateDir?: string;
|
||||
staticDir?: string;
|
||||
providerLayer?: Layer.Layer<ProviderService, never>;
|
||||
providerHealth?: ProviderHealthShape;
|
||||
open?: OpenShape;
|
||||
gitManager?: GitManagerShape;
|
||||
gitCore?: Pick<
|
||||
@@ -414,10 +384,6 @@ 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",
|
||||
@@ -452,7 +418,6 @@ describe("WebSocket Server", () => {
|
||||
);
|
||||
const dependenciesLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(runtimeLayer),
|
||||
Layer.provideMerge(providerHealthLayer),
|
||||
Layer.provideMerge(openLayer),
|
||||
Layer.provideMerge(serverConfigLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
@@ -761,11 +726,7 @@ 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);
|
||||
});
|
||||
|
||||
it("bootstraps default keybindings file when missing", async () => {
|
||||
@@ -788,11 +749,7 @@ 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);
|
||||
|
||||
const persistedConfig = JSON.parse(
|
||||
fs.readFileSync(keybindingsPath, "utf8"),
|
||||
@@ -825,11 +782,7 @@ 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");
|
||||
});
|
||||
|
||||
@@ -861,9 +814,6 @@ 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);
|
||||
@@ -882,9 +832,6 @@ 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 () => {
|
||||
@@ -912,7 +859,6 @@ describe("WebSocket Server", () => {
|
||||
);
|
||||
expect(malformedPush.data).toEqual({
|
||||
issues: [{ kind: "keybindings.malformed-config", message: expect.any(String) }],
|
||||
providers: defaultProviderStatuses,
|
||||
});
|
||||
|
||||
fs.writeFileSync(keybindingsPath, "[]", "utf8");
|
||||
@@ -923,7 +869,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: [], providers: defaultProviderStatuses });
|
||||
expect(successPush.data).toEqual({ issues: [] });
|
||||
});
|
||||
|
||||
it("routes shell.openInEditor through the injected open service", async () => {
|
||||
@@ -983,11 +929,7 @@ describe("WebSocket Server", () => {
|
||||
keybindingsConfigPath: keybindingsPath,
|
||||
keybindings: compileKeybindings(persistedConfig),
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
});
|
||||
|
||||
it("upserts keybinding rules and updates cached server config", async () => {
|
||||
@@ -1032,13 +974,7 @@ describe("WebSocket Server", () => {
|
||||
keybindingsConfigPath: keybindingsPath,
|
||||
keybindings: compileKeybindings(persistedConfig),
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors(
|
||||
(configResponse.result as { availableEditors: unknown }).availableEditors,
|
||||
);
|
||||
});
|
||||
|
||||
it("returns error for unknown methods", async () => {
|
||||
|
||||
@@ -52,24 +52,18 @@ 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 { Open } 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,
|
||||
resolveAttachmentRelativePath,
|
||||
} from "./attachmentPaths";
|
||||
import {
|
||||
createAttachmentId,
|
||||
resolveAttachmentPath,
|
||||
resolveAttachmentPathById,
|
||||
} from "./attachmentStore.ts";
|
||||
import { createAttachmentId, resolveAttachmentPath, resolveAttachmentPathById } from "./attachmentStore.ts";
|
||||
import { parseBase64DataUrl } from "./imageMime.ts";
|
||||
|
||||
/**
|
||||
@@ -156,8 +150,7 @@ export type ServerCoreRuntimeServices =
|
||||
| ProjectionSnapshotQuery
|
||||
| CheckpointDiffQuery
|
||||
| OrchestrationReactor
|
||||
| ProviderService
|
||||
| ProviderHealth;
|
||||
| ProviderService;
|
||||
|
||||
export type ServerRuntimeServices =
|
||||
| ServerCoreRuntimeServices
|
||||
@@ -196,13 +189,10 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
logWebSocketEvents,
|
||||
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;
|
||||
@@ -217,8 +207,6 @@ 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");
|
||||
|
||||
@@ -544,10 +532,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
broadcastPush({
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.serverConfigUpdated,
|
||||
data: {
|
||||
issues: event.issues,
|
||||
providers: providerStatuses,
|
||||
},
|
||||
data: event,
|
||||
}),
|
||||
).pipe(Effect.forkIn(subscriptionsScope));
|
||||
|
||||
@@ -700,7 +685,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
|
||||
case WS_METHODS.gitCheckout: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* Effect.scoped(git.checkoutBranch(body));
|
||||
return yield* git.checkoutBranch(body);
|
||||
}
|
||||
|
||||
case WS_METHODS.gitInit: {
|
||||
@@ -745,9 +730,6 @@ 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", "../../scripts/lib"]
|
||||
"include": ["src", "tsdown.config.ts", "scripts", "integration"]
|
||||
}
|
||||
@@ -3,13 +3,10 @@ import { defineConfig } from "tsdown";
|
||||
export default defineConfig({
|
||||
entry: ["src/index.ts"],
|
||||
format: ["esm", "cjs"],
|
||||
checks: {
|
||||
legacyCjs: false,
|
||||
},
|
||||
outDir: "dist",
|
||||
sourcemap: true,
|
||||
clean: true,
|
||||
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||
noExternal: ["@t3tools/contracts"],
|
||||
inlineOnly: false,
|
||||
banner: {
|
||||
js: "#!/usr/bin/env node\n",
|
||||
|
||||
+4
-13
@@ -1,24 +1,20 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"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",
|
||||
"test:browser": "vitest run --config vitest.browser.config.ts",
|
||||
"test:browser:install": "playwright install --with-deps chromium"
|
||||
"test": "vitest run --passWithNoTests"
|
||||
},
|
||||
"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",
|
||||
@@ -43,14 +39,9 @@
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^5.1.4",
|
||||
"@vitest/browser-playwright": "^4.0.18",
|
||||
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
|
||||
"msw": "^2.12.10",
|
||||
"playwright": "^1.58.2",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "catalog:",
|
||||
"vite": "^8.0.0-beta.12",
|
||||
"vitest": "catalog:",
|
||||
"vitest-browser-react": "^2.0.5"
|
||||
"typescript": "^5.7.3",
|
||||
"vite": "^8.0.0-beta.12"
|
||||
}
|
||||
}
|
||||
@@ -1,349 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* tslint:disable */
|
||||
|
||||
/**
|
||||
* Mock Service Worker.
|
||||
* @see https://github.com/mswjs/msw
|
||||
* - Please do NOT modify this file.
|
||||
*/
|
||||
|
||||
const PACKAGE_VERSION = '2.12.10'
|
||||
const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
|
||||
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
|
||||
const activeClientIds = new Set()
|
||||
|
||||
addEventListener('install', function () {
|
||||
self.skipWaiting()
|
||||
})
|
||||
|
||||
addEventListener('activate', function (event) {
|
||||
event.waitUntil(self.clients.claim())
|
||||
})
|
||||
|
||||
addEventListener('message', async function (event) {
|
||||
const clientId = Reflect.get(event.source || {}, 'id')
|
||||
|
||||
if (!clientId || !self.clients) {
|
||||
return
|
||||
}
|
||||
|
||||
const client = await self.clients.get(clientId)
|
||||
|
||||
if (!client) {
|
||||
return
|
||||
}
|
||||
|
||||
const allClients = await self.clients.matchAll({
|
||||
type: 'window',
|
||||
})
|
||||
|
||||
switch (event.data) {
|
||||
case 'KEEPALIVE_REQUEST': {
|
||||
sendToClient(client, {
|
||||
type: 'KEEPALIVE_RESPONSE',
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'INTEGRITY_CHECK_REQUEST': {
|
||||
sendToClient(client, {
|
||||
type: 'INTEGRITY_CHECK_RESPONSE',
|
||||
payload: {
|
||||
packageVersion: PACKAGE_VERSION,
|
||||
checksum: INTEGRITY_CHECKSUM,
|
||||
},
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'MOCK_ACTIVATE': {
|
||||
activeClientIds.add(clientId)
|
||||
|
||||
sendToClient(client, {
|
||||
type: 'MOCKING_ENABLED',
|
||||
payload: {
|
||||
client: {
|
||||
id: client.id,
|
||||
frameType: client.frameType,
|
||||
},
|
||||
},
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'CLIENT_CLOSED': {
|
||||
activeClientIds.delete(clientId)
|
||||
|
||||
const remainingClients = allClients.filter((client) => {
|
||||
return client.id !== clientId
|
||||
})
|
||||
|
||||
// Unregister itself when there are no more clients
|
||||
if (remainingClients.length === 0) {
|
||||
self.registration.unregister()
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
addEventListener('fetch', function (event) {
|
||||
const requestInterceptedAt = Date.now()
|
||||
|
||||
// Bypass navigation requests.
|
||||
if (event.request.mode === 'navigate') {
|
||||
return
|
||||
}
|
||||
|
||||
// Opening the DevTools triggers the "only-if-cached" request
|
||||
// that cannot be handled by the worker. Bypass such requests.
|
||||
if (
|
||||
event.request.cache === 'only-if-cached' &&
|
||||
event.request.mode !== 'same-origin'
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
// Bypass all requests when there are no active clients.
|
||||
// Prevents the self-unregistered worked from handling requests
|
||||
// after it's been terminated (still remains active until the next reload).
|
||||
if (activeClientIds.size === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const requestId = crypto.randomUUID()
|
||||
event.respondWith(handleRequest(event, requestId, requestInterceptedAt))
|
||||
})
|
||||
|
||||
/**
|
||||
* @param {FetchEvent} event
|
||||
* @param {string} requestId
|
||||
* @param {number} requestInterceptedAt
|
||||
*/
|
||||
async function handleRequest(event, requestId, requestInterceptedAt) {
|
||||
const client = await resolveMainClient(event)
|
||||
const requestCloneForEvents = event.request.clone()
|
||||
const response = await getResponse(
|
||||
event,
|
||||
client,
|
||||
requestId,
|
||||
requestInterceptedAt,
|
||||
)
|
||||
|
||||
// Send back the response clone for the "response:*" life-cycle events.
|
||||
// Ensure MSW is active and ready to handle the message, otherwise
|
||||
// this message will pend indefinitely.
|
||||
if (client && activeClientIds.has(client.id)) {
|
||||
const serializedRequest = await serializeRequest(requestCloneForEvents)
|
||||
|
||||
// Clone the response so both the client and the library could consume it.
|
||||
const responseClone = response.clone()
|
||||
|
||||
sendToClient(
|
||||
client,
|
||||
{
|
||||
type: 'RESPONSE',
|
||||
payload: {
|
||||
isMockedResponse: IS_MOCKED_RESPONSE in response,
|
||||
request: {
|
||||
id: requestId,
|
||||
...serializedRequest,
|
||||
},
|
||||
response: {
|
||||
type: responseClone.type,
|
||||
status: responseClone.status,
|
||||
statusText: responseClone.statusText,
|
||||
headers: Object.fromEntries(responseClone.headers.entries()),
|
||||
body: responseClone.body,
|
||||
},
|
||||
},
|
||||
},
|
||||
responseClone.body ? [serializedRequest.body, responseClone.body] : [],
|
||||
)
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the main client for the given event.
|
||||
* Client that issues a request doesn't necessarily equal the client
|
||||
* that registered the worker. It's with the latter the worker should
|
||||
* communicate with during the response resolving phase.
|
||||
* @param {FetchEvent} event
|
||||
* @returns {Promise<Client | undefined>}
|
||||
*/
|
||||
async function resolveMainClient(event) {
|
||||
const client = await self.clients.get(event.clientId)
|
||||
|
||||
if (activeClientIds.has(event.clientId)) {
|
||||
return client
|
||||
}
|
||||
|
||||
if (client?.frameType === 'top-level') {
|
||||
return client
|
||||
}
|
||||
|
||||
const allClients = await self.clients.matchAll({
|
||||
type: 'window',
|
||||
})
|
||||
|
||||
return allClients
|
||||
.filter((client) => {
|
||||
// Get only those clients that are currently visible.
|
||||
return client.visibilityState === 'visible'
|
||||
})
|
||||
.find((client) => {
|
||||
// Find the client ID that's recorded in the
|
||||
// set of clients that have registered the worker.
|
||||
return activeClientIds.has(client.id)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {FetchEvent} event
|
||||
* @param {Client | undefined} client
|
||||
* @param {string} requestId
|
||||
* @param {number} requestInterceptedAt
|
||||
* @returns {Promise<Response>}
|
||||
*/
|
||||
async function getResponse(event, client, requestId, requestInterceptedAt) {
|
||||
// Clone the request because it might've been already used
|
||||
// (i.e. its body has been read and sent to the client).
|
||||
const requestClone = event.request.clone()
|
||||
|
||||
function passthrough() {
|
||||
// Cast the request headers to a new Headers instance
|
||||
// so the headers can be manipulated with.
|
||||
const headers = new Headers(requestClone.headers)
|
||||
|
||||
// Remove the "accept" header value that marked this request as passthrough.
|
||||
// This prevents request alteration and also keeps it compliant with the
|
||||
// user-defined CORS policies.
|
||||
const acceptHeader = headers.get('accept')
|
||||
if (acceptHeader) {
|
||||
const values = acceptHeader.split(',').map((value) => value.trim())
|
||||
const filteredValues = values.filter(
|
||||
(value) => value !== 'msw/passthrough',
|
||||
)
|
||||
|
||||
if (filteredValues.length > 0) {
|
||||
headers.set('accept', filteredValues.join(', '))
|
||||
} else {
|
||||
headers.delete('accept')
|
||||
}
|
||||
}
|
||||
|
||||
return fetch(requestClone, { headers })
|
||||
}
|
||||
|
||||
// Bypass mocking when the client is not active.
|
||||
if (!client) {
|
||||
return passthrough()
|
||||
}
|
||||
|
||||
// Bypass initial page load requests (i.e. static assets).
|
||||
// The absence of the immediate/parent client in the map of the active clients
|
||||
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
|
||||
// and is not ready to handle requests.
|
||||
if (!activeClientIds.has(client.id)) {
|
||||
return passthrough()
|
||||
}
|
||||
|
||||
// Notify the client that a request has been intercepted.
|
||||
const serializedRequest = await serializeRequest(event.request)
|
||||
const clientMessage = await sendToClient(
|
||||
client,
|
||||
{
|
||||
type: 'REQUEST',
|
||||
payload: {
|
||||
id: requestId,
|
||||
interceptedAt: requestInterceptedAt,
|
||||
...serializedRequest,
|
||||
},
|
||||
},
|
||||
[serializedRequest.body],
|
||||
)
|
||||
|
||||
switch (clientMessage.type) {
|
||||
case 'MOCK_RESPONSE': {
|
||||
return respondWithMock(clientMessage.data)
|
||||
}
|
||||
|
||||
case 'PASSTHROUGH': {
|
||||
return passthrough()
|
||||
}
|
||||
}
|
||||
|
||||
return passthrough()
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Client} client
|
||||
* @param {any} message
|
||||
* @param {Array<Transferable>} transferrables
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
function sendToClient(client, message, transferrables = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const channel = new MessageChannel()
|
||||
|
||||
channel.port1.onmessage = (event) => {
|
||||
if (event.data && event.data.error) {
|
||||
return reject(event.data.error)
|
||||
}
|
||||
|
||||
resolve(event.data)
|
||||
}
|
||||
|
||||
client.postMessage(message, [
|
||||
channel.port2,
|
||||
...transferrables.filter(Boolean),
|
||||
])
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Response} response
|
||||
* @returns {Response}
|
||||
*/
|
||||
function respondWithMock(response) {
|
||||
// Setting response status code to 0 is a no-op.
|
||||
// However, when responding with a "Response.error()", the produced Response
|
||||
// instance will have status code set to 0. Since it's not possible to create
|
||||
// a Response instance with status code 0, handle that use-case separately.
|
||||
if (response.status === 0) {
|
||||
return Response.error()
|
||||
}
|
||||
|
||||
const mockedResponse = new Response(response.body, response)
|
||||
|
||||
Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
|
||||
value: true,
|
||||
enumerable: true,
|
||||
})
|
||||
|
||||
return mockedResponse
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Request} request
|
||||
*/
|
||||
async function serializeRequest(request) {
|
||||
return {
|
||||
url: request.url,
|
||||
mode: request.mode,
|
||||
method: request.method,
|
||||
headers: Object.fromEntries(request.headers.entries()),
|
||||
cache: request.cache,
|
||||
credentials: request.credentials,
|
||||
destination: request.destination,
|
||||
integrity: request.integrity,
|
||||
redirect: request.redirect,
|
||||
referrer: request.referrer,
|
||||
referrerPolicy: request.referrerPolicy,
|
||||
body: await request.arrayBuffer(),
|
||||
keepalive: request.keepalive,
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { getAppModelOptions, getSlashModelOptions, normalizeCustomModelSlugs } from "./appSettings";
|
||||
import { getAppModelOptions, normalizeCustomModelSlugs } from "./appSettings";
|
||||
|
||||
describe("normalizeCustomModelSlugs", () => {
|
||||
it("normalizes aliases, removes built-ins, and deduplicates values", () => {
|
||||
@@ -40,17 +40,3 @@ 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,24 +105,6 @@ 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();
|
||||
|
||||
@@ -1,76 +1,64 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
import { ThreadId, type GitBranch } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
resolveDraftEnvModeAfterBranchChange,
|
||||
resolveBranchToolbarValue,
|
||||
deriveSyncedLocalBranch,
|
||||
} 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");
|
||||
const branches: GitBranch[] = [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
isDefault: true,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "feature/demo",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
describe("deriveSyncedLocalBranch", () => {
|
||||
it("syncs to git current branch in local mode", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: threadId,
|
||||
activeWorktreePath: null,
|
||||
envMode: "local",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBe("main");
|
||||
});
|
||||
|
||||
it("keeps new-worktree mode when selecting a base branch before worktree creation", () => {
|
||||
expect(
|
||||
resolveDraftEnvModeAfterBranchChange({
|
||||
nextWorktreePath: null,
|
||||
currentWorktreePath: null,
|
||||
effectiveEnvMode: "worktree",
|
||||
}),
|
||||
).toBe("worktree");
|
||||
it("does not sync when creating a new worktree", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: threadId,
|
||||
activeWorktreePath: null,
|
||||
envMode: "worktree",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
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");
|
||||
});
|
||||
});
|
||||
it("does not sync when thread already targets a worktree path", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: threadId,
|
||||
activeWorktreePath: "/tmp/repo/worktrees/feature-demo",
|
||||
envMode: "local",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
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");
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,44 +1,11 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
import type { GitBranch, ThreadId } 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;
|
||||
interface DeriveSyncedLocalBranchInput {
|
||||
activeThreadId: ThreadId | undefined;
|
||||
activeWorktreePath: string | null;
|
||||
envMode: "local" | "worktree";
|
||||
activeThreadBranch: string | null;
|
||||
currentGitBranch: string | null;
|
||||
}): string | null {
|
||||
const { envMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
|
||||
if (envMode === "worktree" && !activeWorktreePath) {
|
||||
return activeThreadBranch ?? currentGitBranch;
|
||||
}
|
||||
return currentGitBranch ?? activeThreadBranch;
|
||||
queryBranches: ReadonlyArray<GitBranch> | undefined;
|
||||
}
|
||||
|
||||
export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
|
||||
@@ -88,3 +55,22 @@ export function dedupeRemoteBranchesWithLocalMatches(
|
||||
return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
|
||||
});
|
||||
}
|
||||
|
||||
export function deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
}: DeriveSyncedLocalBranchInput): string | null {
|
||||
if (!activeThreadId || activeWorktreePath || envMode !== "local") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const currentBranch = queryBranches?.find((branch) => branch.current);
|
||||
if (!currentBranch || currentBranch.name === activeThreadBranch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return currentBranch.name;
|
||||
}
|
||||
@@ -1,27 +1,44 @@
|
||||
import type { ThreadId } from "@t3tools/contracts";
|
||||
import { useCallback } from "react";
|
||||
import type { GitBranch, ThreadId } from "@t3tools/contracts";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { newCommandId } from "../lib/utils";
|
||||
import {
|
||||
gitBranchesQueryOptions,
|
||||
gitCheckoutMutationOptions,
|
||||
gitCreateBranchAndCheckoutMutationOptions,
|
||||
} from "../lib/gitReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { useStore } from "../store";
|
||||
import {
|
||||
EnvMode,
|
||||
resolveDraftEnvModeAfterBranchChange,
|
||||
resolveEffectiveEnvMode,
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
deriveSyncedLocalBranch,
|
||||
} 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";
|
||||
|
||||
interface BranchToolbarProps {
|
||||
threadId: ThreadId;
|
||||
onEnvModeChange: (mode: EnvMode) => void;
|
||||
envMode: "local" | "worktree";
|
||||
onEnvModeChange: (mode: "local" | "worktree") => void;
|
||||
envLocked: boolean;
|
||||
onComposerFocusRequest?: () => void;
|
||||
}
|
||||
|
||||
export default function BranchToolbar({
|
||||
threadId,
|
||||
envMode,
|
||||
onEnvModeChange,
|
||||
envLocked,
|
||||
onComposerFocusRequest,
|
||||
@@ -29,8 +46,13 @@ 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;
|
||||
@@ -40,64 +62,191 @@ export default function BranchToolbar({
|
||||
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
|
||||
const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null;
|
||||
const hasServerThread = serverThread !== undefined;
|
||||
const effectiveEnvMode = resolveEffectiveEnvMode({
|
||||
activeWorktreePath,
|
||||
hasServerThread,
|
||||
draftThreadEnvMode: draftThread?.envMode,
|
||||
});
|
||||
const effectiveEnvMode: "local" | "worktree" =
|
||||
activeWorktreePath || (!hasServerThread && draftThread?.envMode === "worktree")
|
||||
? "worktree"
|
||||
: envMode;
|
||||
|
||||
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",
|
||||
// ── Queries ───────────────────────────────────────────────────────────
|
||||
|
||||
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
|
||||
|
||||
const branches = dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []);
|
||||
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;
|
||||
// ── Mutations ─────────────────────────────────────────────────────────
|
||||
|
||||
const checkoutMutation = useMutation(gitCheckoutMutationOptions({ cwd: branchCwd, queryClient }));
|
||||
|
||||
const createBranchMutation = useMutation(
|
||||
gitCreateBranchAndCheckoutMutationOptions({ cwd: branchCwd, queryClient }),
|
||||
);
|
||||
|
||||
// ── Effects ───────────────────────────────────────────────────────────
|
||||
|
||||
// Keep thread branch synced to git current branch for local threads.
|
||||
const queryBranches = branchesQuery.data?.branches;
|
||||
useEffect(() => {
|
||||
const syncedBranch = deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode: effectiveEnvMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
});
|
||||
if (!activeThreadId || !syncedBranch) return;
|
||||
const api = readNativeApi();
|
||||
|
||||
if (api && hasServerThread) {
|
||||
void api.orchestration.dispatchCommand({
|
||||
type: "thread.meta.update",
|
||||
commandId: newCommandId(),
|
||||
threadId: activeThreadId,
|
||||
branch: syncedBranch,
|
||||
worktreePath: null,
|
||||
});
|
||||
}
|
||||
if (hasServerThread) {
|
||||
setThreadBranchAction(activeThreadId, syncedBranch, null);
|
||||
return;
|
||||
}
|
||||
setDraftThreadContext(threadId, {
|
||||
branch: syncedBranch,
|
||||
worktreePath: null,
|
||||
});
|
||||
}, [
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
effectiveEnvMode,
|
||||
setThreadBranchAction,
|
||||
hasServerThread,
|
||||
setDraftThreadContext,
|
||||
threadId,
|
||||
]);
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
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",
|
||||
commandId: newCommandId(),
|
||||
threadId: activeThreadId,
|
||||
branch,
|
||||
worktreePath,
|
||||
});
|
||||
}
|
||||
if (hasServerThread) {
|
||||
setThreadBranchAction(activeThreadId, branch, worktreePath);
|
||||
return;
|
||||
}
|
||||
const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({
|
||||
nextWorktreePath: worktreePath,
|
||||
currentWorktreePath: activeWorktreePath,
|
||||
effectiveEnvMode,
|
||||
});
|
||||
setDraftThreadContext(threadId, {
|
||||
createdAt: new Date().toISOString(),
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
if (api && hasServerThread) {
|
||||
void api.orchestration.dispatchCommand({
|
||||
type: "thread.meta.update",
|
||||
commandId: newCommandId(),
|
||||
threadId: activeThreadId,
|
||||
branch,
|
||||
worktreePath,
|
||||
envMode: nextDraftEnvMode,
|
||||
});
|
||||
},
|
||||
[
|
||||
activeThreadId,
|
||||
serverThread?.session?.sessionId,
|
||||
activeWorktreePath,
|
||||
hasServerThread,
|
||||
setThreadBranchAction,
|
||||
setDraftThreadContext,
|
||||
threadId,
|
||||
effectiveEnvMode,
|
||||
],
|
||||
);
|
||||
}
|
||||
if (hasServerThread) {
|
||||
setThreadBranchAction(activeThreadId, branch, worktreePath);
|
||||
return;
|
||||
}
|
||||
setDraftThreadContext(threadId, {
|
||||
branch,
|
||||
worktreePath,
|
||||
envMode: effectiveEnvMode,
|
||||
});
|
||||
};
|
||||
|
||||
const selectBranch = (branch: GitBranch) => {
|
||||
const api = readNativeApi();
|
||||
if (!api || !activeThreadId || !branchCwd) return;
|
||||
|
||||
// For new worktree mode, selecting a branch picks the base branch.
|
||||
if (effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath) {
|
||||
setThreadError(null);
|
||||
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;
|
||||
setThreadError(null);
|
||||
// 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;
|
||||
|
||||
checkoutMutation.mutate(branch.name, {
|
||||
onSuccess: async () => {
|
||||
setThreadError(null);
|
||||
let nextBranchName = selectedBranchName;
|
||||
if (branch.isRemote) {
|
||||
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
|
||||
if (status?.branch) {
|
||||
nextBranchName = status.branch;
|
||||
}
|
||||
}
|
||||
setThreadBranch(nextBranchName, activeWorktreePath);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
},
|
||||
onError: (error) => {
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch.");
|
||||
setIsBranchMenuOpen(true);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const createBranch = (rawName: string) => {
|
||||
const name = rawName.trim();
|
||||
const api = readNativeApi();
|
||||
if (!api || !activeThreadId || !branchCwd || !name || createBranchMutation.isPending) return;
|
||||
createBranchMutation.mutate(name, {
|
||||
onSuccess: () => {
|
||||
setThreadError(null);
|
||||
setThreadBranch(name, activeWorktreePath);
|
||||
setBranchQuery("");
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
},
|
||||
onError: (error) => {
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to create branch.");
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
if (!activeThreadId || !activeProject) return null;
|
||||
|
||||
@@ -114,23 +263,104 @@ export default function BranchToolbar({
|
||||
variant="ghost"
|
||||
className="text-muted-foreground/70 hover:text-foreground/80"
|
||||
size="xs"
|
||||
onClick={() => onEnvModeChange(effectiveEnvMode === "local" ? "worktree" : "local")}
|
||||
onClick={() =>
|
||||
onEnvModeChange(effectiveEnvMode === "local" ? "worktree" : "local")
|
||||
}
|
||||
>
|
||||
{effectiveEnvMode === "worktree" ? "New worktree" : "Local"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<BranchToolbarBranchSelector
|
||||
activeProjectCwd={activeProject.cwd}
|
||||
activeThreadBranch={activeThreadBranch}
|
||||
activeWorktreePath={activeWorktreePath}
|
||||
branchCwd={branchCwd}
|
||||
effectiveEnvMode={effectiveEnvMode}
|
||||
envLocked={envLocked}
|
||||
onSetThreadBranch={setThreadBranch}
|
||||
{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
|
||||
/>
|
||||
<Combobox
|
||||
items={branchPickerItems}
|
||||
autoHighlight
|
||||
onOpenChange={(open) => {
|
||||
setIsBranchMenuOpen(open);
|
||||
if (!open) {
|
||||
setBranchQuery("");
|
||||
}
|
||||
}}
|
||||
open={isBranchMenuOpen}
|
||||
value={activeThreadBranch}
|
||||
>
|
||||
<ComboboxTrigger
|
||||
render={<Button variant="ghost" size="xs" />}
|
||||
className="text-muted-foreground/70 hover:text-foreground/80"
|
||||
disabled={branchesQuery.isLoading}
|
||||
>
|
||||
<span className="max-w-[240px] truncate">
|
||||
{activeThreadBranch
|
||||
? effectiveEnvMode === "worktree" && !activeWorktreePath
|
||||
? `From ${activeThreadBranch}`
|
||||
: activeThreadBranch
|
||||
: "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 === activeThreadBranch ? "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>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,408 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,713 +0,0 @@
|
||||
// Production CSS is part of the behavior under test because row height depends on it.
|
||||
import "../index.css";
|
||||
|
||||
import {
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type MessageId,
|
||||
type OrchestrationReadModel,
|
||||
type ProjectId,
|
||||
type ProviderSessionId,
|
||||
type ServerConfig,
|
||||
type ThreadId,
|
||||
type WsWelcomePayload,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
} from "@t3tools/contracts";
|
||||
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
|
||||
import { HttpResponse, http, ws } from "msw";
|
||||
import { setupWorker } from "msw/browser";
|
||||
import { page } from "vitest/browser";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { getRouter } from "../router";
|
||||
import { useStore } from "../store";
|
||||
import { estimateTimelineMessageHeight } from "./timelineHeight";
|
||||
|
||||
const THREAD_ID = "thread-browser-test" as ThreadId;
|
||||
const PROJECT_ID = "project-1" as ProjectId;
|
||||
const NOW_ISO = "2026-03-04T12:00:00.000Z";
|
||||
const BASE_TIME_MS = Date.parse(NOW_ISO);
|
||||
const ATTACHMENT_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='120' height='300'></svg>";
|
||||
|
||||
interface WsRequestEnvelope {
|
||||
id: string;
|
||||
body: {
|
||||
_tag: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
interface TestFixture {
|
||||
snapshot: OrchestrationReadModel;
|
||||
serverConfig: ServerConfig;
|
||||
welcome: WsWelcomePayload;
|
||||
}
|
||||
|
||||
let fixture: TestFixture;
|
||||
const wsLink = ws.link(/ws(s)?:\/\/.*/);
|
||||
|
||||
interface ViewportSpec {
|
||||
name: string;
|
||||
width: number;
|
||||
height: number;
|
||||
textTolerancePx: number;
|
||||
attachmentTolerancePx: number;
|
||||
}
|
||||
|
||||
const DEFAULT_VIEWPORT: ViewportSpec = {
|
||||
name: "desktop",
|
||||
width: 960,
|
||||
height: 1_100,
|
||||
textTolerancePx: 44,
|
||||
attachmentTolerancePx: 56,
|
||||
};
|
||||
const TEXT_VIEWPORT_MATRIX = [
|
||||
DEFAULT_VIEWPORT,
|
||||
{ name: "tablet", width: 720, height: 1_024, textTolerancePx: 44, attachmentTolerancePx: 56 },
|
||||
{ name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 56 },
|
||||
{ name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 },
|
||||
] as const satisfies readonly ViewportSpec[];
|
||||
const ATTACHMENT_VIEWPORT_MATRIX = [
|
||||
DEFAULT_VIEWPORT,
|
||||
{ name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 56 },
|
||||
{ name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 },
|
||||
] as const satisfies readonly ViewportSpec[];
|
||||
|
||||
interface UserRowMeasurement {
|
||||
measuredRowHeightPx: number;
|
||||
timelineWidthMeasuredPx: number;
|
||||
renderedInVirtualizedRegion: boolean;
|
||||
}
|
||||
|
||||
interface MountedChatView {
|
||||
cleanup: () => Promise<void>;
|
||||
measureUserRow: (targetMessageId: MessageId) => Promise<UserRowMeasurement>;
|
||||
setViewport: (viewport: ViewportSpec) => Promise<void>;
|
||||
}
|
||||
|
||||
function isoAt(offsetSeconds: number): string {
|
||||
return new Date(BASE_TIME_MS + offsetSeconds * 1_000).toISOString();
|
||||
}
|
||||
|
||||
function createBaseServerConfig(): ServerConfig {
|
||||
return {
|
||||
cwd: "/repo/project",
|
||||
keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
|
||||
keybindings: [],
|
||||
issues: [],
|
||||
providers: [
|
||||
{
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
available: true,
|
||||
authStatus: "authenticated",
|
||||
checkedAt: NOW_ISO,
|
||||
},
|
||||
],
|
||||
availableEditors: [],
|
||||
};
|
||||
}
|
||||
|
||||
function createUserMessage(options: {
|
||||
id: MessageId;
|
||||
text: string;
|
||||
offsetSeconds: number;
|
||||
attachments?: Array<{
|
||||
type: "image";
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
}>;
|
||||
}) {
|
||||
return {
|
||||
id: options.id,
|
||||
role: "user" as const,
|
||||
text: options.text,
|
||||
...(options.attachments ? { attachments: options.attachments } : {}),
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: isoAt(options.offsetSeconds),
|
||||
updatedAt: isoAt(options.offsetSeconds + 1),
|
||||
};
|
||||
}
|
||||
|
||||
function createAssistantMessage(options: { id: MessageId; text: string; offsetSeconds: number }) {
|
||||
return {
|
||||
id: options.id,
|
||||
role: "assistant" as const,
|
||||
text: options.text,
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: isoAt(options.offsetSeconds),
|
||||
updatedAt: isoAt(options.offsetSeconds + 1),
|
||||
};
|
||||
}
|
||||
|
||||
function createSnapshotForTargetUser(options: {
|
||||
targetMessageId: MessageId;
|
||||
targetText: string;
|
||||
targetAttachmentCount?: number;
|
||||
}): OrchestrationReadModel {
|
||||
const messages: Array<OrchestrationReadModel["threads"][number]["messages"][number]> = [];
|
||||
|
||||
for (let index = 0; index < 22; index += 1) {
|
||||
const isTarget = index === 3;
|
||||
const userId = `msg-user-${index}` as MessageId;
|
||||
const assistantId = `msg-assistant-${index}` as MessageId;
|
||||
const attachments =
|
||||
isTarget && (options.targetAttachmentCount ?? 0) > 0
|
||||
? Array.from({ length: options.targetAttachmentCount ?? 0 }, (_, attachmentIndex) => ({
|
||||
type: "image" as const,
|
||||
id: `attachment-${attachmentIndex + 1}`,
|
||||
name: `attachment-${attachmentIndex + 1}.png`,
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 128,
|
||||
}))
|
||||
: undefined;
|
||||
|
||||
messages.push(
|
||||
createUserMessage({
|
||||
id: isTarget ? options.targetMessageId : userId,
|
||||
text: isTarget ? options.targetText : `filler user message ${index}`,
|
||||
offsetSeconds: messages.length * 3,
|
||||
...(attachments ? { attachments } : {}),
|
||||
}),
|
||||
);
|
||||
messages.push(
|
||||
createAssistantMessage({
|
||||
id: assistantId,
|
||||
text: `assistant filler ${index}`,
|
||||
offsetSeconds: messages.length * 3,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
snapshotSequence: 1,
|
||||
projects: [
|
||||
{
|
||||
id: PROJECT_ID,
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo/project",
|
||||
defaultModel: "gpt-5",
|
||||
scripts: [],
|
||||
createdAt: NOW_ISO,
|
||||
updatedAt: NOW_ISO,
|
||||
deletedAt: null,
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Browser test thread",
|
||||
model: "gpt-5",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: NOW_ISO,
|
||||
updatedAt: NOW_ISO,
|
||||
deletedAt: null,
|
||||
messages,
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: {
|
||||
threadId: THREAD_ID,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerSessionId: "session-1" as ProviderSessionId,
|
||||
providerThreadId: null,
|
||||
approvalPolicy: "on-failure",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: NOW_ISO,
|
||||
},
|
||||
},
|
||||
],
|
||||
updatedAt: NOW_ISO,
|
||||
};
|
||||
}
|
||||
|
||||
function buildFixture(snapshot: OrchestrationReadModel): TestFixture {
|
||||
return {
|
||||
snapshot,
|
||||
serverConfig: createBaseServerConfig(),
|
||||
welcome: {
|
||||
cwd: "/repo/project",
|
||||
projectName: "Project",
|
||||
bootstrapProjectId: PROJECT_ID,
|
||||
bootstrapThreadId: THREAD_ID,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function resolveWsRpc(tag: string): unknown {
|
||||
if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
|
||||
return fixture.snapshot;
|
||||
}
|
||||
if (tag === WS_METHODS.serverGetConfig) {
|
||||
return fixture.serverConfig;
|
||||
}
|
||||
if (tag === WS_METHODS.gitListBranches) {
|
||||
return {
|
||||
isRepo: true,
|
||||
branches: [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
isDefault: true,
|
||||
worktreePath: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (tag === WS_METHODS.gitStatus) {
|
||||
return {
|
||||
branch: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
};
|
||||
}
|
||||
if (tag === WS_METHODS.projectsSearchEntries) {
|
||||
return {
|
||||
entries: [],
|
||||
truncated: false,
|
||||
};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
const worker = setupWorker(
|
||||
wsLink.addEventListener("connection", ({ client }) => {
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.serverWelcome,
|
||||
data: fixture.welcome,
|
||||
}),
|
||||
);
|
||||
client.addEventListener("message", (event) => {
|
||||
const rawData = event.data;
|
||||
if (typeof rawData !== "string") return;
|
||||
let request: WsRequestEnvelope;
|
||||
try {
|
||||
request = JSON.parse(rawData) as WsRequestEnvelope;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const method = request.body?._tag;
|
||||
if (typeof method !== "string") return;
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
id: request.id,
|
||||
result: resolveWsRpc(method),
|
||||
}),
|
||||
);
|
||||
});
|
||||
}),
|
||||
http.get("*/attachments/:attachmentId", () =>
|
||||
HttpResponse.text(ATTACHMENT_SVG, {
|
||||
headers: {
|
||||
"Content-Type": "image/svg+xml",
|
||||
},
|
||||
}),
|
||||
),
|
||||
http.get("*/api/project-favicon", () => new HttpResponse(null, { status: 204 })),
|
||||
);
|
||||
|
||||
async function nextFrame(): Promise<void> {
|
||||
await new Promise<void>((resolve) => {
|
||||
window.requestAnimationFrame(() => resolve());
|
||||
});
|
||||
}
|
||||
|
||||
async function waitForLayout(): Promise<void> {
|
||||
await nextFrame();
|
||||
await nextFrame();
|
||||
await nextFrame();
|
||||
}
|
||||
|
||||
async function setViewport(viewport: ViewportSpec): Promise<void> {
|
||||
await page.viewport(viewport.width, viewport.height);
|
||||
await waitForLayout();
|
||||
}
|
||||
|
||||
async function waitForProductionStyles(): Promise<void> {
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(getComputedStyle(document.documentElement).getPropertyValue("--background").trim()).not.toBe(
|
||||
"",
|
||||
);
|
||||
expect(getComputedStyle(document.body).marginTop).toBe("0px");
|
||||
},
|
||||
{
|
||||
timeout: 4_000,
|
||||
interval: 16,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function waitForElement<T extends Element>(
|
||||
query: () => T | null,
|
||||
errorMessage: string,
|
||||
): Promise<T> {
|
||||
let element: T | null = null;
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
element = query();
|
||||
expect(element, errorMessage).toBeTruthy();
|
||||
},
|
||||
{
|
||||
timeout: 8_000,
|
||||
interval: 16,
|
||||
},
|
||||
);
|
||||
if (!element) {
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
return element;
|
||||
}
|
||||
|
||||
async function waitForImagesToLoad(scope: ParentNode): Promise<void> {
|
||||
const images = Array.from(scope.querySelectorAll("img"));
|
||||
if (images.length === 0) {
|
||||
return;
|
||||
}
|
||||
await Promise.all(
|
||||
images.map(
|
||||
(image) =>
|
||||
new Promise<void>((resolve) => {
|
||||
if (image.complete) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
image.addEventListener("load", () => resolve(), { once: true });
|
||||
image.addEventListener("error", () => resolve(), { once: true });
|
||||
}),
|
||||
),
|
||||
);
|
||||
await waitForLayout();
|
||||
}
|
||||
|
||||
async function measureUserRow(options: {
|
||||
host: HTMLElement;
|
||||
targetMessageId: MessageId;
|
||||
}): Promise<UserRowMeasurement> {
|
||||
const { host, targetMessageId } = options;
|
||||
const rowSelector = `[data-message-id="${targetMessageId}"][data-message-role="user"]`;
|
||||
|
||||
const scrollContainer = await waitForElement(
|
||||
() => host.querySelector<HTMLDivElement>("div.overflow-y-auto.overscroll-y-contain"),
|
||||
"Unable to find ChatView message scroll container.",
|
||||
);
|
||||
|
||||
let row: HTMLElement | null = null;
|
||||
await vi.waitFor(
|
||||
async () => {
|
||||
scrollContainer.scrollTop = 0;
|
||||
scrollContainer.dispatchEvent(new Event("scroll"));
|
||||
await waitForLayout();
|
||||
row = host.querySelector<HTMLElement>(rowSelector);
|
||||
expect(row, "Unable to locate targeted user message row.").toBeTruthy();
|
||||
},
|
||||
{
|
||||
timeout: 8_000,
|
||||
interval: 16,
|
||||
},
|
||||
);
|
||||
|
||||
await waitForImagesToLoad(row!);
|
||||
scrollContainer.scrollTop = 0;
|
||||
scrollContainer.dispatchEvent(new Event("scroll"));
|
||||
await nextFrame();
|
||||
|
||||
const timelineRoot =
|
||||
row!.closest<HTMLElement>('[data-timeline-root="true"]') ??
|
||||
host.querySelector<HTMLElement>('[data-timeline-root="true"]');
|
||||
if (!(timelineRoot instanceof HTMLElement)) {
|
||||
throw new Error("Unable to locate timeline root container.");
|
||||
}
|
||||
|
||||
let timelineWidthMeasuredPx = 0;
|
||||
let measuredRowHeightPx = 0;
|
||||
let renderedInVirtualizedRegion = false;
|
||||
await vi.waitFor(
|
||||
async () => {
|
||||
scrollContainer.scrollTop = 0;
|
||||
scrollContainer.dispatchEvent(new Event("scroll"));
|
||||
await nextFrame();
|
||||
const measuredRow = host.querySelector<HTMLElement>(rowSelector);
|
||||
expect(measuredRow, "Unable to measure targeted user row height.").toBeTruthy();
|
||||
timelineWidthMeasuredPx = timelineRoot.getBoundingClientRect().width;
|
||||
measuredRowHeightPx = measuredRow!.getBoundingClientRect().height;
|
||||
renderedInVirtualizedRegion = measuredRow!.closest("[data-index]") instanceof HTMLElement;
|
||||
expect(timelineWidthMeasuredPx, "Unable to measure timeline width.").toBeGreaterThan(0);
|
||||
expect(measuredRowHeightPx, "Unable to measure targeted user row height.").toBeGreaterThan(0);
|
||||
},
|
||||
{
|
||||
timeout: 4_000,
|
||||
interval: 16,
|
||||
},
|
||||
);
|
||||
|
||||
return { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion };
|
||||
}
|
||||
|
||||
async function mountChatView(options: {
|
||||
viewport: ViewportSpec;
|
||||
snapshot: OrchestrationReadModel;
|
||||
}): Promise<MountedChatView> {
|
||||
fixture = buildFixture(options.snapshot);
|
||||
await setViewport(options.viewport);
|
||||
await waitForProductionStyles();
|
||||
|
||||
const host = document.createElement("div");
|
||||
host.style.position = "fixed";
|
||||
host.style.inset = "0";
|
||||
host.style.width = "100vw";
|
||||
host.style.height = "100vh";
|
||||
host.style.display = "grid";
|
||||
host.style.overflow = "hidden";
|
||||
document.body.append(host);
|
||||
|
||||
const router = getRouter(
|
||||
createMemoryHistory({
|
||||
initialEntries: [`/${THREAD_ID}`],
|
||||
}),
|
||||
);
|
||||
|
||||
const screen = await render(<RouterProvider router={router} />, {
|
||||
container: host,
|
||||
});
|
||||
|
||||
await waitForLayout();
|
||||
|
||||
return {
|
||||
cleanup: async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
},
|
||||
measureUserRow: async (targetMessageId: MessageId) => measureUserRow({ host, targetMessageId }),
|
||||
setViewport: async (viewport: ViewportSpec) => {
|
||||
await setViewport(viewport);
|
||||
await waitForProductionStyles();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function measureUserRowAtViewport(options: {
|
||||
snapshot: OrchestrationReadModel;
|
||||
targetMessageId: MessageId;
|
||||
viewport: ViewportSpec;
|
||||
}): Promise<UserRowMeasurement> {
|
||||
const mounted = await mountChatView({
|
||||
viewport: options.viewport,
|
||||
snapshot: options.snapshot,
|
||||
});
|
||||
|
||||
try {
|
||||
return await mounted.measureUserRow(options.targetMessageId);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
describe("ChatView timeline estimator parity (full app)", () => {
|
||||
beforeAll(async () => {
|
||||
fixture = buildFixture(
|
||||
createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-bootstrap" as MessageId,
|
||||
targetText: "bootstrap",
|
||||
}),
|
||||
);
|
||||
await worker.start({
|
||||
onUnhandledRequest: "bypass",
|
||||
quiet: true,
|
||||
serviceWorker: {
|
||||
url: "/mockServiceWorker.js",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await worker.stop();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await setViewport(DEFAULT_VIEWPORT);
|
||||
localStorage.clear();
|
||||
document.body.innerHTML = "";
|
||||
useStore.setState({
|
||||
projects: [],
|
||||
threads: [],
|
||||
threadsHydrated: false,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
it.each(TEXT_VIEWPORT_MATRIX)(
|
||||
"keeps long user message estimate close at the $name viewport",
|
||||
async (viewport) => {
|
||||
const userText = "x".repeat(3_200);
|
||||
const targetMessageId = `msg-user-target-long-${viewport.name}` as MessageId;
|
||||
const mounted = await mountChatView({
|
||||
viewport,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId,
|
||||
targetText: userText,
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion } =
|
||||
await mounted.measureUserRow(targetMessageId);
|
||||
|
||||
expect(renderedInVirtualizedRegion).toBe(true);
|
||||
|
||||
const estimatedHeightPx = estimateTimelineMessageHeight(
|
||||
{ role: "user", text: userText, attachments: [] },
|
||||
{ timelineWidthPx: timelineWidthMeasuredPx },
|
||||
);
|
||||
|
||||
expect(Math.abs(measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
|
||||
viewport.textTolerancePx,
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("tracks wrapping parity while resizing an existing ChatView across the viewport matrix", async () => {
|
||||
const userText = "x".repeat(3_200);
|
||||
const targetMessageId = "msg-user-target-resize" as MessageId;
|
||||
const mounted = await mountChatView({
|
||||
viewport: TEXT_VIEWPORT_MATRIX[0],
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId,
|
||||
targetText: userText,
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const measurements: Array<UserRowMeasurement & { viewport: ViewportSpec; estimatedHeightPx: number }> = [];
|
||||
|
||||
for (const viewport of TEXT_VIEWPORT_MATRIX) {
|
||||
await mounted.setViewport(viewport);
|
||||
const measurement = await mounted.measureUserRow(targetMessageId);
|
||||
const estimatedHeightPx = estimateTimelineMessageHeight(
|
||||
{ role: "user", text: userText, attachments: [] },
|
||||
{ timelineWidthPx: measurement.timelineWidthMeasuredPx },
|
||||
);
|
||||
|
||||
expect(measurement.renderedInVirtualizedRegion).toBe(true);
|
||||
expect(Math.abs(measurement.measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
|
||||
viewport.textTolerancePx,
|
||||
);
|
||||
measurements.push({ ...measurement, viewport, estimatedHeightPx });
|
||||
}
|
||||
|
||||
expect(new Set(measurements.map((measurement) => Math.round(measurement.timelineWidthMeasuredPx))).size).toBeGreaterThanOrEqual(3);
|
||||
|
||||
const byMeasuredWidth = measurements.toSorted(
|
||||
(left, right) => left.timelineWidthMeasuredPx - right.timelineWidthMeasuredPx,
|
||||
);
|
||||
const narrowest = byMeasuredWidth[0]!;
|
||||
const widest = byMeasuredWidth.at(-1)!;
|
||||
expect(narrowest.timelineWidthMeasuredPx).toBeLessThan(widest.timelineWidthMeasuredPx);
|
||||
expect(narrowest.measuredRowHeightPx).toBeGreaterThan(widest.measuredRowHeightPx);
|
||||
expect(narrowest.estimatedHeightPx).toBeGreaterThan(widest.estimatedHeightPx);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("tracks additional rendered wrapping when ChatView width narrows between desktop and mobile viewports", async () => {
|
||||
const userText = "x".repeat(2_400);
|
||||
const targetMessageId = "msg-user-target-wrap" as MessageId;
|
||||
const snapshot = createSnapshotForTargetUser({
|
||||
targetMessageId,
|
||||
targetText: userText,
|
||||
});
|
||||
const desktopMeasurement = await measureUserRowAtViewport({
|
||||
viewport: TEXT_VIEWPORT_MATRIX[0],
|
||||
snapshot,
|
||||
targetMessageId,
|
||||
});
|
||||
const mobileMeasurement = await measureUserRowAtViewport({
|
||||
viewport: TEXT_VIEWPORT_MATRIX[2],
|
||||
snapshot,
|
||||
targetMessageId,
|
||||
});
|
||||
|
||||
const estimatedDesktopPx = estimateTimelineMessageHeight(
|
||||
{ role: "user", text: userText, attachments: [] },
|
||||
{ timelineWidthPx: desktopMeasurement.timelineWidthMeasuredPx },
|
||||
);
|
||||
const estimatedMobilePx = estimateTimelineMessageHeight(
|
||||
{ role: "user", text: userText, attachments: [] },
|
||||
{ timelineWidthPx: mobileMeasurement.timelineWidthMeasuredPx },
|
||||
);
|
||||
|
||||
const measuredDeltaPx = mobileMeasurement.measuredRowHeightPx - desktopMeasurement.measuredRowHeightPx;
|
||||
const estimatedDeltaPx = estimatedMobilePx - estimatedDesktopPx;
|
||||
expect(measuredDeltaPx).toBeGreaterThan(0);
|
||||
expect(estimatedDeltaPx).toBeGreaterThan(0);
|
||||
const ratio = estimatedDeltaPx / measuredDeltaPx;
|
||||
expect(ratio).toBeGreaterThan(0.65);
|
||||
expect(ratio).toBeLessThan(1.35);
|
||||
});
|
||||
|
||||
it.each(ATTACHMENT_VIEWPORT_MATRIX)(
|
||||
"keeps user attachment estimate close at the $name viewport",
|
||||
async (viewport) => {
|
||||
const targetMessageId = `msg-user-target-attachments-${viewport.name}` as MessageId;
|
||||
const userText = "message with image attachments";
|
||||
const mounted = await mountChatView({
|
||||
viewport,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId,
|
||||
targetText: userText,
|
||||
targetAttachmentCount: 3,
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion } =
|
||||
await mounted.measureUserRow(targetMessageId);
|
||||
|
||||
expect(renderedInVirtualizedRegion).toBe(true);
|
||||
|
||||
const estimatedHeightPx = estimateTimelineMessageHeight(
|
||||
{
|
||||
role: "user",
|
||||
text: userText,
|
||||
attachments: [{ id: "attachment-1" }, { id: "attachment-2" }, { id: "attachment-3" }],
|
||||
},
|
||||
{ timelineWidthPx: timelineWidthMeasuredPx },
|
||||
);
|
||||
|
||||
expect(Math.abs(measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
|
||||
viewport.attachmentTolerancePx,
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
type ReasoningEffort,
|
||||
type ResolvedKeybindingsConfig,
|
||||
type ProviderApprovalDecision,
|
||||
type ServerProviderStatus,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
normalizeModelSlug,
|
||||
@@ -101,7 +100,7 @@ import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./u
|
||||
import { Separator } from "./ui/separator";
|
||||
import { Group, GroupSeparator } from "./ui/group";
|
||||
import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu";
|
||||
import { CursorIcon, Icon, VisualStudioCode, Zed } from "./Icons";
|
||||
import { CursorIcon, Icon } from "./Icons";
|
||||
import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
|
||||
import { Badge } from "./ui/badge";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
@@ -119,7 +118,7 @@ import { Toggle } from "./ui/toggle";
|
||||
import { SidebarTrigger } from "./ui/sidebar";
|
||||
import { newCommandId, newMessageId } from "~/lib/utils";
|
||||
import { readNativeApi } from "~/nativeApi";
|
||||
import { getAppModelOptions, getSlashModelOptions, useAppSettings } from "../appSettings";
|
||||
import { getAppModelOptions, useAppSettings } from "../appSettings";
|
||||
import {
|
||||
type ComposerImageAttachment,
|
||||
type DraftThreadEnvMode,
|
||||
@@ -131,7 +130,6 @@ import {
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { clamp } from "effect/Number";
|
||||
import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "./ComposerPromptEditor";
|
||||
import { estimateTimelineMessageHeight } from "./timelineHeight";
|
||||
|
||||
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
||||
if (!duration) return formatTimestamp(createdAt);
|
||||
@@ -149,8 +147,6 @@ const IMAGE_ONLY_BOOTSTRAP_PROMPT =
|
||||
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;
|
||||
@@ -521,12 +517,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const messagesScrollRef = useRef<HTMLDivElement>(null);
|
||||
const [messagesScrollElement, setMessagesScrollElement] = useState<HTMLDivElement | null>(null);
|
||||
const shouldAutoScrollRef = useRef(true);
|
||||
const lastKnownScrollTopRef = useRef(0);
|
||||
const isPointerScrollActiveRef = useRef(false);
|
||||
const lastTouchClientYRef = useRef<number | null>(null);
|
||||
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[]>([]);
|
||||
@@ -634,11 +627,6 @@ 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";
|
||||
@@ -877,7 +865,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : "";
|
||||
const branchesQuery = useQuery(gitBranchesQueryOptions(gitCwd));
|
||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||
const keybindingsQuery = useQuery({
|
||||
...serverConfigQueryOptions(),
|
||||
select: (config) => config.keybindings,
|
||||
});
|
||||
const workspaceEntriesQuery = useQuery(
|
||||
projectSearchEntriesQueryOptions({
|
||||
cwd: gitCwd,
|
||||
@@ -914,14 +905,26 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
];
|
||||
}
|
||||
|
||||
return slashModelOptions.map(({ slug, name }) => ({
|
||||
id: `model:${slug}`,
|
||||
type: "model" as const,
|
||||
model: slug,
|
||||
label: name,
|
||||
description: slug,
|
||||
}));
|
||||
}, [composerTrigger, slashModelOptions, workspaceEntries]);
|
||||
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]);
|
||||
const composerMenuOpen = Boolean(composerTrigger);
|
||||
const activeComposerMenuItem = useMemo(
|
||||
() =>
|
||||
@@ -937,14 +940,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
() => new Set(nonPersistedComposerImageIds),
|
||||
[nonPersistedComposerImageIds],
|
||||
);
|
||||
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 keybindings = keybindingsQuery.data ?? EMPTY_KEYBINDINGS;
|
||||
const activeProjectCwd = activeProject?.cwd ?? null;
|
||||
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
|
||||
const threadTerminalRuntimeEnv = useMemo(() => {
|
||||
@@ -1328,15 +1324,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const scrollContainer = messagesScrollRef.current;
|
||||
if (!scrollContainer) return;
|
||||
scrollContainer.scrollTo({ top: scrollContainer.scrollHeight, behavior });
|
||||
lastKnownScrollTopRef.current = scrollContainer.scrollTop;
|
||||
shouldAutoScrollRef.current = true;
|
||||
}, []);
|
||||
const cancelPendingStickToBottom = useCallback(() => {
|
||||
const pendingFrame = pendingAutoScrollFrameRef.current;
|
||||
if (pendingFrame === null) return;
|
||||
pendingAutoScrollFrameRef.current = null;
|
||||
window.cancelAnimationFrame(pendingFrame);
|
||||
}, []);
|
||||
const scheduleStickToBottom = useCallback(() => {
|
||||
if (pendingAutoScrollFrameRef.current !== null) return;
|
||||
pendingAutoScrollFrameRef.current = window.requestAnimationFrame(() => {
|
||||
@@ -1344,77 +1333,19 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
scrollMessagesToBottom();
|
||||
});
|
||||
}, [scrollMessagesToBottom]);
|
||||
const forceStickToBottom = useCallback(() => {
|
||||
cancelPendingStickToBottom();
|
||||
scrollMessagesToBottom();
|
||||
scheduleStickToBottom();
|
||||
}, [cancelPendingStickToBottom, scheduleStickToBottom, scrollMessagesToBottom]);
|
||||
const onMessagesScroll = useCallback(() => {
|
||||
const scrollContainer = messagesScrollRef.current;
|
||||
if (!scrollContainer) return;
|
||||
const currentScrollTop = scrollContainer.scrollTop;
|
||||
const isNearBottom = isScrollContainerNearBottom(scrollContainer);
|
||||
|
||||
if (!shouldAutoScrollRef.current && isNearBottom) {
|
||||
shouldAutoScrollRef.current = true;
|
||||
pendingUserScrollUpIntentRef.current = false;
|
||||
} else if (shouldAutoScrollRef.current && pendingUserScrollUpIntentRef.current) {
|
||||
const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - 1;
|
||||
if (scrolledUp) {
|
||||
shouldAutoScrollRef.current = false;
|
||||
}
|
||||
pendingUserScrollUpIntentRef.current = false;
|
||||
} else if (shouldAutoScrollRef.current && isPointerScrollActiveRef.current) {
|
||||
const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - 1;
|
||||
if (scrolledUp) {
|
||||
shouldAutoScrollRef.current = false;
|
||||
}
|
||||
} else if (shouldAutoScrollRef.current && !isNearBottom) {
|
||||
// Catch-all for keyboard/assistive scroll interactions.
|
||||
const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - 1;
|
||||
if (scrolledUp) {
|
||||
shouldAutoScrollRef.current = false;
|
||||
}
|
||||
}
|
||||
|
||||
lastKnownScrollTopRef.current = currentScrollTop;
|
||||
}, []);
|
||||
const onMessagesWheel = useCallback((event: React.WheelEvent<HTMLDivElement>) => {
|
||||
if (event.deltaY < 0) {
|
||||
pendingUserScrollUpIntentRef.current = true;
|
||||
}
|
||||
}, []);
|
||||
const onMessagesPointerDown = useCallback((_event: React.PointerEvent<HTMLDivElement>) => {
|
||||
isPointerScrollActiveRef.current = true;
|
||||
}, []);
|
||||
const onMessagesPointerUp = useCallback((_event: React.PointerEvent<HTMLDivElement>) => {
|
||||
isPointerScrollActiveRef.current = false;
|
||||
}, []);
|
||||
const onMessagesPointerCancel = useCallback((_event: React.PointerEvent<HTMLDivElement>) => {
|
||||
isPointerScrollActiveRef.current = false;
|
||||
}, []);
|
||||
const onMessagesTouchStart = useCallback((event: React.TouchEvent<HTMLDivElement>) => {
|
||||
const touch = event.touches[0];
|
||||
if (!touch) return;
|
||||
lastTouchClientYRef.current = touch.clientY;
|
||||
}, []);
|
||||
const onMessagesTouchMove = useCallback((event: React.TouchEvent<HTMLDivElement>) => {
|
||||
const touch = event.touches[0];
|
||||
if (!touch) return;
|
||||
const previousTouchY = lastTouchClientYRef.current;
|
||||
if (previousTouchY !== null && touch.clientY > previousTouchY + 1) {
|
||||
pendingUserScrollUpIntentRef.current = true;
|
||||
}
|
||||
lastTouchClientYRef.current = touch.clientY;
|
||||
}, []);
|
||||
const onMessagesTouchEnd = useCallback((_event: React.TouchEvent<HTMLDivElement>) => {
|
||||
lastTouchClientYRef.current = null;
|
||||
shouldAutoScrollRef.current = isScrollContainerNearBottom(scrollContainer);
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
cancelPendingStickToBottom();
|
||||
const frame = pendingAutoScrollFrameRef.current;
|
||||
if (frame !== null) {
|
||||
window.cancelAnimationFrame(frame);
|
||||
}
|
||||
};
|
||||
}, [cancelPendingStickToBottom]);
|
||||
}, []);
|
||||
useLayoutEffect(() => {
|
||||
if (!activeThread?.id) return;
|
||||
shouldAutoScrollRef.current = true;
|
||||
@@ -1991,7 +1922,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
]);
|
||||
// Sending a message should always bring the latest user turn into view.
|
||||
shouldAutoScrollRef.current = true;
|
||||
forceStickToBottom();
|
||||
scheduleStickToBottom();
|
||||
|
||||
setThreadError(threadIdForSend, null);
|
||||
promptRef.current = "";
|
||||
@@ -2321,9 +2252,12 @@ 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);
|
||||
}
|
||||
@@ -2366,27 +2300,18 @@ 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;
|
||||
|
||||
@@ -2492,7 +2417,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null
|
||||
}
|
||||
keybindings={keybindings}
|
||||
availableEditors={availableEditors}
|
||||
diffToggleShortcutLabel={diffPanelShortcutLabel}
|
||||
gitCwd={gitCwd}
|
||||
diffOpen={diffOpen}
|
||||
@@ -2506,7 +2430,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
</header>
|
||||
|
||||
{/* Error banner */}
|
||||
<ProviderHealthBanner status={activeProviderStatus} />
|
||||
<ThreadErrorBanner error={activeThread.error} />
|
||||
<PendingApprovalsPanel
|
||||
pendingApprovals={pendingApprovals}
|
||||
@@ -2519,14 +2442,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
ref={setMessagesScrollContainerRef}
|
||||
className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-y-contain px-3 py-3 sm:px-5 sm:py-4"
|
||||
onScroll={onMessagesScroll}
|
||||
onWheel={onMessagesWheel}
|
||||
onPointerDown={onMessagesPointerDown}
|
||||
onPointerUp={onMessagesPointerUp}
|
||||
onPointerCancel={onMessagesPointerCancel}
|
||||
onTouchStart={onMessagesTouchStart}
|
||||
onTouchMove={onMessagesTouchMove}
|
||||
onTouchEnd={onMessagesTouchEnd}
|
||||
onTouchCancel={onMessagesTouchEnd}
|
||||
>
|
||||
<MessagesTimeline
|
||||
key={activeThread.id}
|
||||
@@ -2794,6 +2709,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
{isGitRepo && (
|
||||
<BranchToolbar
|
||||
threadId={activeThread.id}
|
||||
envMode={envMode}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
envLocked={envLocked}
|
||||
onComposerFocusRequest={scheduleComposerFocus}
|
||||
@@ -2906,7 +2822,6 @@ interface ChatHeaderProps {
|
||||
activeProjectScripts: ProjectScript[] | undefined;
|
||||
preferredScriptId: string | null;
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
availableEditors: ReadonlyArray<EditorId>;
|
||||
diffToggleShortcutLabel: string | null;
|
||||
gitCwd: string | null;
|
||||
diffOpen: boolean;
|
||||
@@ -2923,7 +2838,6 @@ const ChatHeader = memo(function ChatHeader({
|
||||
activeProjectScripts,
|
||||
preferredScriptId,
|
||||
keybindings,
|
||||
availableEditors,
|
||||
diffToggleShortcutLabel,
|
||||
gitCwd,
|
||||
diffOpen,
|
||||
@@ -2960,11 +2874,7 @@ const ChatHeader = memo(function ChatHeader({
|
||||
/>
|
||||
)}
|
||||
{activeProjectName && (
|
||||
<OpenInPicker
|
||||
keybindings={keybindings}
|
||||
availableEditors={availableEditors}
|
||||
activeThreadId={activeThreadId}
|
||||
/>
|
||||
<OpenInPicker keybindings={keybindings} activeThreadId={activeThreadId} />
|
||||
)}
|
||||
{activeProjectName && <GitActionsControl gitCwd={gitCwd} activeThreadId={activeThreadId} />}
|
||||
<Tooltip>
|
||||
@@ -3007,35 +2917,6 @@ 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[];
|
||||
@@ -3167,6 +3048,20 @@ type TimelineRow =
|
||||
}
|
||||
| { kind: "working"; id: string; createdAt: string | null };
|
||||
|
||||
function estimateTimelineMessageHeight(message: TimelineMessage): number {
|
||||
const textLength = message.text.length;
|
||||
if (message.role === "assistant") {
|
||||
const estimatedLines = Math.max(1, Math.ceil(textLength / 72));
|
||||
return 78 + Math.min(estimatedLines * 22, 820);
|
||||
}
|
||||
|
||||
const estimatedLines = Math.max(1, Math.ceil(textLength / 56));
|
||||
const attachmentCount = message.attachments?.length ?? 0;
|
||||
const attachmentRows = Math.ceil(attachmentCount / 2);
|
||||
const attachmentHeight = attachmentRows * 124;
|
||||
return 96 + Math.min(estimatedLines * 22, 620) + attachmentHeight;
|
||||
}
|
||||
|
||||
const MessagesTimeline = memo(function MessagesTimeline({
|
||||
hasMessages,
|
||||
isWorking,
|
||||
@@ -3187,34 +3082,6 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
onImageExpand,
|
||||
markdownCwd,
|
||||
}: MessagesTimelineProps) {
|
||||
const timelineRootRef = useRef<HTMLDivElement | null>(null);
|
||||
const [timelineWidthPx, setTimelineWidthPx] = useState<number | null>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const timelineRoot = timelineRootRef.current;
|
||||
if (!timelineRoot) return;
|
||||
|
||||
const updateWidth = (nextWidth: number) => {
|
||||
setTimelineWidthPx((previousWidth) => {
|
||||
if (previousWidth !== null && Math.abs(previousWidth - nextWidth) < 0.5) {
|
||||
return previousWidth;
|
||||
}
|
||||
return nextWidth;
|
||||
});
|
||||
};
|
||||
|
||||
updateWidth(timelineRoot.getBoundingClientRect().width);
|
||||
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
const observer = new ResizeObserver(() => {
|
||||
updateWidth(timelineRoot.getBoundingClientRect().width);
|
||||
});
|
||||
observer.observe(timelineRoot);
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
};
|
||||
}, [hasMessages, isWorking]);
|
||||
|
||||
const rows = useMemo<TimelineRow[]>(() => {
|
||||
const nextRows: TimelineRow[] = [];
|
||||
|
||||
@@ -3318,16 +3185,12 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
if (!row) return 96;
|
||||
if (row.kind === "work") return 112;
|
||||
if (row.kind === "working") return 40;
|
||||
return estimateTimelineMessageHeight(row.message, { timelineWidthPx });
|
||||
return estimateTimelineMessageHeight(row.message);
|
||||
},
|
||||
measureElement: measureVirtualElement,
|
||||
useAnimationFrameWithResizeObserver: true,
|
||||
overscan: 8,
|
||||
});
|
||||
useEffect(() => {
|
||||
if (timelineWidthPx === null) return;
|
||||
rowVirtualizer.measure();
|
||||
}, [rowVirtualizer, timelineWidthPx]);
|
||||
useEffect(() => {
|
||||
rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = (_item, _delta, instance) => {
|
||||
const viewportHeight = instance.scrollRect?.height ?? 0;
|
||||
@@ -3360,12 +3223,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
const nonVirtualizedRows = rows.slice(virtualizedRowCount);
|
||||
|
||||
const renderRowContent = (row: TimelineRow) => (
|
||||
<div
|
||||
className="pb-4"
|
||||
data-timeline-row-kind={row.kind}
|
||||
data-message-id={row.kind === "message" ? row.message.id : undefined}
|
||||
data-message-role={row.kind === "message" ? row.message.role : undefined}
|
||||
>
|
||||
<div className="pb-4">
|
||||
{row.kind === "work" &&
|
||||
(() => {
|
||||
const groupId = row.id;
|
||||
@@ -3648,11 +3506,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={timelineRootRef}
|
||||
data-timeline-root="true"
|
||||
className="mx-auto w-full min-w-0 max-w-3xl overflow-x-hidden"
|
||||
>
|
||||
<div className="mx-auto w-full min-w-0 max-w-3xl overflow-x-hidden">
|
||||
{virtualizedRowCount > 0 && (
|
||||
<div className="relative" style={{ height: `${rowVirtualizer.getTotalSize()}px` }}>
|
||||
{virtualRows.map((virtualRow: VirtualItem) => {
|
||||
@@ -3732,11 +3586,9 @@ const ReasoningEffortPicker = memo(function ReasoningEffortPicker(props: {
|
||||
|
||||
const OpenInPicker = memo(function OpenInPicker({
|
||||
keybindings,
|
||||
availableEditors,
|
||||
activeThreadId,
|
||||
}: {
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
availableEditors: ReadonlyArray<EditorId>;
|
||||
activeThreadId: ThreadId | null;
|
||||
}) {
|
||||
const [lastEditor, setLastEditor] = useState<EditorId>(() => {
|
||||
@@ -3744,44 +3596,23 @@ const OpenInPicker = memo(function OpenInPicker({
|
||||
return EDITORS.some((e) => e.id === stored) ? (stored as EditorId) : EDITORS[0].id;
|
||||
});
|
||||
|
||||
const allOptions = useMemo<Array<{ label: string; Icon: Icon; value: EditorId }>>(
|
||||
() => [
|
||||
{
|
||||
label: "Cursor",
|
||||
Icon: CursorIcon,
|
||||
value: "cursor",
|
||||
},
|
||||
{
|
||||
label: "VS Code",
|
||||
Icon: VisualStudioCode,
|
||||
value: "vscode",
|
||||
},
|
||||
{
|
||||
label: "Zed",
|
||||
Icon: Zed,
|
||||
value: "zed",
|
||||
},
|
||||
{
|
||||
label: isMacPlatform(navigator.platform)
|
||||
? "Finder"
|
||||
: isWindowsPlatform(navigator.platform)
|
||||
? "Explorer"
|
||||
: "Files",
|
||||
Icon: FolderClosedIcon,
|
||||
value: "file-manager",
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
const options = useMemo(
|
||||
() => allOptions.filter((option) => availableEditors.includes(option.value)),
|
||||
[allOptions, availableEditors],
|
||||
);
|
||||
|
||||
const effectiveEditor = options.some((option) => option.value === lastEditor)
|
||||
? lastEditor
|
||||
: (options[0]?.value ?? null);
|
||||
const primaryOption = options.find(({ value }) => value === effectiveEditor) ?? null;
|
||||
const options = [
|
||||
{
|
||||
label: "Cursor",
|
||||
Icon: CursorIcon,
|
||||
value: "cursor",
|
||||
},
|
||||
{
|
||||
label: isMacPlatform(navigator.platform)
|
||||
? "Finder"
|
||||
: isWindowsPlatform(navigator.platform)
|
||||
? "Explorer"
|
||||
: "Files",
|
||||
Icon: FolderClosedIcon,
|
||||
value: "file-manager",
|
||||
},
|
||||
] satisfies { label: string; Icon: Icon; value: EditorId }[];
|
||||
const primaryOption = options.find(({ value }) => value === lastEditor);
|
||||
|
||||
const activeThread = useStore((store) =>
|
||||
activeThreadId ? store.threads.find((thread) => thread.id === activeThreadId) : undefined,
|
||||
@@ -3795,14 +3626,13 @@ const OpenInPicker = memo(function OpenInPicker({
|
||||
(editorId: EditorId | null) => {
|
||||
const api = readNativeApi();
|
||||
if (!api || !activeProject) return;
|
||||
const editor = editorId ?? effectiveEditor;
|
||||
if (!editor) return;
|
||||
const editor = editorId ?? lastEditor;
|
||||
const cwd = activeThread?.worktreePath ?? activeProject.cwd;
|
||||
void api.shell.openInEditor(cwd, editor);
|
||||
localStorage.setItem(LAST_EDITOR_KEY, editor);
|
||||
setLastEditor(editor);
|
||||
},
|
||||
[activeProject, activeThread, effectiveEditor, setLastEditor],
|
||||
[activeProject, activeThread, lastEditor, setLastEditor],
|
||||
);
|
||||
|
||||
const openFavoriteEditorShortcutLabel = useMemo(
|
||||
@@ -3815,24 +3645,18 @@ const OpenInPicker = memo(function OpenInPicker({
|
||||
const api = readNativeApi();
|
||||
if (!isOpenFavoriteEditorShortcut(e, keybindings)) return;
|
||||
if (!api || !activeProject) return;
|
||||
if (!effectiveEditor) return;
|
||||
|
||||
e.preventDefault();
|
||||
const cwd = activeThread?.worktreePath ?? activeProject.cwd;
|
||||
void api.shell.openInEditor(cwd, effectiveEditor);
|
||||
void api.shell.openInEditor(cwd, lastEditor);
|
||||
};
|
||||
window.addEventListener("keydown", handler);
|
||||
return () => window.removeEventListener("keydown", handler);
|
||||
}, [activeProject, activeThread, keybindings, effectiveEditor]);
|
||||
}, [activeProject, activeThread, keybindings, lastEditor]);
|
||||
|
||||
return (
|
||||
<Group aria-label="Subscription actions">
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={!effectiveEditor || !activeProject}
|
||||
onClick={() => openInEditor(effectiveEditor)}
|
||||
>
|
||||
<Button size="xs" variant="outline" onClick={() => openInEditor(lastEditor)}>
|
||||
{primaryOption?.Icon && <primaryOption.Icon aria-hidden="true" className="size-3.5" />}
|
||||
<span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
|
||||
Open
|
||||
@@ -3844,12 +3668,11 @@ const OpenInPicker = memo(function OpenInPicker({
|
||||
<ChevronDownIcon aria-hidden="true" className="size-4" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="end">
|
||||
{options.length === 0 && <MenuItem disabled>No installed editors found</MenuItem>}
|
||||
{options.map(({ label, Icon, value }) => (
|
||||
<MenuItem key={value} onClick={() => openInEditor(value)}>
|
||||
<Icon aria-hidden="true" className="text-muted-foreground" />
|
||||
{label}
|
||||
{value === effectiveEditor && openFavoriteEditorShortcutLabel && (
|
||||
{value === lastEditor && openFavoriteEditorShortcutLabel && (
|
||||
<MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
|
||||
)}
|
||||
</MenuItem>
|
||||
|
||||
@@ -50,7 +50,6 @@ import {
|
||||
type Ref,
|
||||
} from "react";
|
||||
|
||||
import { isCollapsedCursorAdjacentToMention } from "~/composer-logic";
|
||||
import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { basenameOfPath, getVscodeIconUrlForEntry } from "~/vscode-icons";
|
||||
@@ -470,25 +469,16 @@ function ComposerMentionArrowPlugin() {
|
||||
useEffect(() => {
|
||||
const unregisterLeft = editor.registerCommand(
|
||||
KEY_ARROW_LEFT_COMMAND,
|
||||
(event) => {
|
||||
let nextOffset: number | null = null;
|
||||
() => {
|
||||
let currentOffset = -1;
|
||||
editor.getEditorState().read(() => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
|
||||
const currentOffset = $readSelectionOffsetFromEditorState(0);
|
||||
if (currentOffset <= 0) return;
|
||||
const promptValue = $getRoot().getTextContent();
|
||||
if (!isCollapsedCursorAdjacentToMention(promptValue, currentOffset, "left")) {
|
||||
return;
|
||||
}
|
||||
nextOffset = currentOffset - 1;
|
||||
currentOffset = $readSelectionOffsetFromEditorState(0);
|
||||
});
|
||||
if (nextOffset === null) return false;
|
||||
const selectionOffset = nextOffset;
|
||||
event?.preventDefault();
|
||||
event?.stopPropagation();
|
||||
if (currentOffset <= 0) return false;
|
||||
editor.update(() => {
|
||||
$setSelectionAtComposerOffset(selectionOffset);
|
||||
$setSelectionAtComposerOffset(currentOffset - 1);
|
||||
});
|
||||
return true;
|
||||
},
|
||||
@@ -496,26 +486,18 @@ function ComposerMentionArrowPlugin() {
|
||||
);
|
||||
const unregisterRight = editor.registerCommand(
|
||||
KEY_ARROW_RIGHT_COMMAND,
|
||||
(event) => {
|
||||
let nextOffset: number | null = null;
|
||||
() => {
|
||||
let currentOffset = -1;
|
||||
let composerLength = 0;
|
||||
editor.getEditorState().read(() => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
|
||||
const currentOffset = $readSelectionOffsetFromEditorState(0);
|
||||
const composerLength = $getComposerRootLength();
|
||||
if (currentOffset >= composerLength) return;
|
||||
const promptValue = $getRoot().getTextContent();
|
||||
if (!isCollapsedCursorAdjacentToMention(promptValue, currentOffset, "right")) {
|
||||
return;
|
||||
}
|
||||
nextOffset = currentOffset + 1;
|
||||
composerLength = $getComposerRootLength();
|
||||
currentOffset = $readSelectionOffsetFromEditorState(0);
|
||||
});
|
||||
if (nextOffset === null) return false;
|
||||
const selectionOffset = nextOffset;
|
||||
event?.preventDefault();
|
||||
event?.stopPropagation();
|
||||
if (currentOffset < 0 || currentOffset >= composerLength) return false;
|
||||
editor.update(() => {
|
||||
$setSelectionAtComposerOffset(selectionOffset);
|
||||
$setSelectionAtComposerOffset(currentOffset + 1);
|
||||
});
|
||||
return true;
|
||||
},
|
||||
@@ -558,6 +540,29 @@ function ComposerMentionSelectionNormalizePlugin() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function $isCursorAdjacentToMention(): boolean {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return false;
|
||||
const anchorNode = selection.anchor.getNode();
|
||||
|
||||
if (anchorNode instanceof ComposerMentionNode) return true;
|
||||
|
||||
if ($isElementNode(anchorNode)) {
|
||||
const childIndex = selection.anchor.offset - 1;
|
||||
if (childIndex >= 0) {
|
||||
const child = anchorNode.getChildAtIndex(childIndex);
|
||||
if (child instanceof ComposerMentionNode) return true;
|
||||
}
|
||||
}
|
||||
|
||||
if ($isTextNode(anchorNode) && selection.anchor.offset === 0) {
|
||||
const prev = anchorNode.getPreviousSibling();
|
||||
if (prev instanceof ComposerMentionNode) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function ComposerMentionBackspacePlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
@@ -733,10 +738,7 @@ function ComposerPromptEditorInner({
|
||||
value: nextValue,
|
||||
cursor: nextCursor,
|
||||
};
|
||||
const cursorAdjacentToMention =
|
||||
isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "left") ||
|
||||
isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "right");
|
||||
onChangeRef.current(nextValue, nextCursor, cursorAdjacentToMention);
|
||||
onChangeRef.current(nextValue, nextCursor, $isCursorAdjacentToMention());
|
||||
});
|
||||
}, []);
|
||||
|
||||
|
||||
@@ -737,7 +737,7 @@ describe("when: branch has no upstream configured", () => {
|
||||
});
|
||||
|
||||
describe("requiresDefaultBranchConfirmation", () => {
|
||||
it("requires confirmation for push actions on default branch", () => {
|
||||
it("requires confirmation only 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,17 +804,6 @@ 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",
|
||||
@@ -834,7 +823,6 @@ 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",
|
||||
@@ -853,7 +841,6 @@ 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",
|
||||
@@ -876,7 +863,6 @@ 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",
|
||||
@@ -902,7 +888,6 @@ describe("summarizeGitResult", () => {
|
||||
it("truncates long description text", () => {
|
||||
const result = summarizeGitResult({
|
||||
action: "commit_push_pr",
|
||||
branch: { status: "skipped_not_requested" },
|
||||
commit: {
|
||||
status: "created",
|
||||
commitSha: "89abcdef01234567",
|
||||
@@ -925,31 +910,18 @@ describe("summarizeGitResult", () => {
|
||||
});
|
||||
|
||||
describe("resolveAutoFeatureBranchName", () => {
|
||||
it("uses semantic preferred branch names when available", () => {
|
||||
const branch = resolveAutoFeatureBranchName(["main", "feature/other"], "fix toast copy");
|
||||
assert.equal(branch, "feature/fix-toast-copy");
|
||||
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("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", () => {
|
||||
it("increments suffix when the base name already exists", () => {
|
||||
const branch = resolveAutoFeatureBranchName(
|
||||
["main", "feature/fix-toast-copy", "feature/fix-toast-copy-2"],
|
||||
"fix toast copy",
|
||||
["main", "feature/stacked-20260301", "feature/stacked-20260301-2"],
|
||||
day,
|
||||
);
|
||||
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");
|
||||
assert.equal(branch, "feature/stacked-20260301-3");
|
||||
});
|
||||
});
|
||||
@@ -35,6 +35,7 @@ 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;
|
||||
@@ -57,9 +58,7 @@ 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
|
||||
@@ -69,12 +68,12 @@ export function buildGitActionProgressStages(input: {
|
||||
: ["Generating commit message...", "Committing..."];
|
||||
const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing...";
|
||||
if (input.action === "commit") {
|
||||
return [...branchStages, ...commitStages];
|
||||
return commitStages;
|
||||
}
|
||||
if (input.action === "commit_push") {
|
||||
return [...branchStages, ...commitStages, pushStage];
|
||||
return [...commitStages, pushStage];
|
||||
}
|
||||
return [...branchStages, ...commitStages, pushStage, "Creating PR..."];
|
||||
return [...commitStages, pushStage, "Creating PR..."];
|
||||
}
|
||||
|
||||
const withDescription = (title: string, description: string | undefined) =>
|
||||
@@ -322,5 +321,29 @@ export function resolveDefaultBranchActionDialogCopy(input: {
|
||||
};
|
||||
}
|
||||
|
||||
// Re-export from shared for backwards compatibility in this module's exports
|
||||
export { resolveAutoFeatureBranchName } from "@t3tools/shared/git";
|
||||
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}`;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { GitStackedAction, GitStatusResult, ThreadId } from "@t3tools/contracts";
|
||||
import { type GitStatusResult, type GitStackedAction, type 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,6 +11,7 @@ import {
|
||||
type GitQuickAction,
|
||||
type DefaultBranchConfirmableAction,
|
||||
requiresDefaultBranchConfirmation,
|
||||
resolveAutoFeatureBranchName,
|
||||
resolveDefaultBranchActionDialogCopy,
|
||||
resolveQuickAction,
|
||||
summarizeGitResult,
|
||||
@@ -33,6 +34,7 @@ import { Textarea } from "~/components/ui/textarea";
|
||||
import { toastManager } from "~/components/ui/toast";
|
||||
import {
|
||||
gitBranchesQueryOptions,
|
||||
gitCreateBranchAndCheckoutMutationOptions,
|
||||
gitInitMutationOptions,
|
||||
gitMutationKeys,
|
||||
gitPullMutationOptions,
|
||||
@@ -170,12 +172,18 @@ 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 || isPullRunning;
|
||||
const isGitActionRunning =
|
||||
isRunStackedActionRunning || isCreateBranchAndCheckoutRunning || isPullRunning;
|
||||
const isDefaultBranch = useMemo(() => {
|
||||
const branchName = gitStatusForActions?.branch;
|
||||
if (!branchName) return false;
|
||||
@@ -239,7 +247,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
onConfirmed,
|
||||
skipDefaultBranchPrompt = false,
|
||||
statusOverride,
|
||||
featureBranch = false,
|
||||
isDefaultBranchOverride,
|
||||
progressToastId,
|
||||
}: {
|
||||
@@ -249,13 +256,12 @@ 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 (
|
||||
@@ -278,13 +284,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
}
|
||||
onConfirmed?.();
|
||||
|
||||
const pushTarget = !featureBranch && actionBranch ? `origin/${actionBranch}` : undefined;
|
||||
const pushTarget = actionBranch ? `origin/${actionBranch}` : undefined;
|
||||
const progressStages = buildGitActionProgressStages({
|
||||
action,
|
||||
hasCustomCommitMessage: !!commitMessage?.trim(),
|
||||
hasWorkingTreeChanges: !!actionStatus?.hasWorkingTreeChanges,
|
||||
forcePushOnly: forcePushOnlyProgress,
|
||||
featureBranch,
|
||||
...(pushTarget ? { pushTarget } : {}),
|
||||
});
|
||||
const resolvedProgressToastId =
|
||||
@@ -323,7 +328,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
const promise = runImmediateGitActionMutation.mutateAsync({
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(featureBranch ? { featureBranch } : {}),
|
||||
});
|
||||
|
||||
try {
|
||||
@@ -337,9 +341,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
const shouldOfferOpenPrCta =
|
||||
(action === "commit_push" || action === "commit_push_pr") &&
|
||||
!!prUrl &&
|
||||
(!actionIsDefaultBranch ||
|
||||
result.pr.status === "created" ||
|
||||
result.pr.status === "opened_existing");
|
||||
!actionIsDefaultBranch;
|
||||
const shouldOfferCreatePrCta =
|
||||
action === "commit_push" &&
|
||||
!prUrl &&
|
||||
@@ -393,7 +395,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
closeResultToast();
|
||||
void runGitActionWithToast({
|
||||
action: "commit_push_pr",
|
||||
forcePushOnlyProgress: true,
|
||||
statusOverride: actionStatus,
|
||||
isDefaultBranchOverride: actionIsDefaultBranch,
|
||||
});
|
||||
@@ -442,13 +443,54 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
forcePushOnlyProgress?: boolean;
|
||||
onConfirmed?: () => void;
|
||||
}) => {
|
||||
void runGitActionWithToast({
|
||||
...actionParams,
|
||||
featureBranch: true,
|
||||
skipDefaultBranchPrompt: true,
|
||||
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 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,
|
||||
});
|
||||
});
|
||||
},
|
||||
[runGitActionWithToast],
|
||||
[
|
||||
branchList?.branches,
|
||||
createBranchAndCheckoutMutation,
|
||||
gitStatusForActions,
|
||||
runGitActionWithToast,
|
||||
threadToastData,
|
||||
],
|
||||
);
|
||||
|
||||
const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type SVGProps, useId } from "react";
|
||||
import type { SVGProps } from "react";
|
||||
|
||||
export type Icon = React.FC<SVGProps<SVGSVGElement>>;
|
||||
|
||||
@@ -19,126 +19,3 @@ export const CursorIcon: Icon = (props) => (
|
||||
<path d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const VisualStudioCode: Icon = (props) => {
|
||||
const id = useId();
|
||||
const maskId = `${id}-vscode-a`;
|
||||
const topShadowFilterId = `${id}-vscode-b`;
|
||||
const sideShadowFilterId = `${id}-vscode-c`;
|
||||
const overlayGradientId = `${id}-vscode-d`;
|
||||
|
||||
return (
|
||||
<svg {...props} fill="none" viewBox="0 0 100 100">
|
||||
<mask id={maskId} width="100" height="100" x="0" y="0" maskUnits="userSpaceOnUse">
|
||||
<path
|
||||
fill="#fff"
|
||||
fillRule="evenodd"
|
||||
d="M70.912 99.317a6.223 6.223 0 0 0 4.96-.19l20.589-9.907A6.25 6.25 0 0 0 100 83.587V16.413a6.25 6.25 0 0 0-3.54-5.632L75.874.874a6.226 6.226 0 0 0-7.104 1.21L29.355 38.04 12.187 25.01a4.162 4.162 0 0 0-5.318.236l-5.506 5.009a4.168 4.168 0 0 0-.004 6.162L16.247 50 1.36 63.583a4.168 4.168 0 0 0 .004 6.162l5.506 5.01a4.162 4.162 0 0 0 5.318.236l17.168-13.032L68.77 97.917a6.217 6.217 0 0 0 2.143 1.4ZM75.015 27.3 45.11 50l29.906 22.701V27.3Z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</mask>
|
||||
<g mask={`url(#${maskId})`}>
|
||||
<path
|
||||
fill="#0065A9"
|
||||
d="M96.461 10.796 75.857.876a6.23 6.23 0 0 0-7.107 1.207l-67.451 61.5a4.167 4.167 0 0 0 .004 6.162l5.51 5.009a4.167 4.167 0 0 0 5.32.236l81.228-61.62c2.725-2.067 6.639-.124 6.639 3.297v-.24a6.25 6.25 0 0 0-3.539-5.63Z"
|
||||
/>
|
||||
<g filter={`url(#${topShadowFilterId})`}>
|
||||
<path
|
||||
fill="#007ACC"
|
||||
d="m96.461 89.204-20.604 9.92a6.229 6.229 0 0 1-7.107-1.207l-67.451-61.5a4.167 4.167 0 0 1 .004-6.162l5.51-5.009a4.167 4.167 0 0 1 5.32-.236l81.228 61.62c2.725 2.067 6.639.124 6.639-3.297v.24a6.25 6.25 0 0 1-3.539 5.63Z"
|
||||
/>
|
||||
</g>
|
||||
<g filter={`url(#${sideShadowFilterId})`}>
|
||||
<path
|
||||
fill="#1F9CF0"
|
||||
d="M75.858 99.126a6.232 6.232 0 0 1-7.108-1.21c2.306 2.307 6.25.674 6.25-2.588V4.672c0-3.262-3.944-4.895-6.25-2.589a6.232 6.232 0 0 1 7.108-1.21l20.6 9.908A6.25 6.25 0 0 1 100 16.413v67.174a6.25 6.25 0 0 1-3.541 5.633l-20.601 9.906Z"
|
||||
/>
|
||||
</g>
|
||||
<path
|
||||
fill={`url(#${overlayGradientId})`}
|
||||
fillRule="evenodd"
|
||||
d="M70.851 99.317a6.224 6.224 0 0 0 4.96-.19L96.4 89.22a6.25 6.25 0 0 0 3.54-5.633V16.413a6.25 6.25 0 0 0-3.54-5.632L75.812.874a6.226 6.226 0 0 0-7.104 1.21L29.294 38.04 12.126 25.01a4.162 4.162 0 0 0-5.317.236l-5.507 5.009a4.168 4.168 0 0 0-.004 6.162L16.186 50 1.298 63.583a4.168 4.168 0 0 0 .004 6.162l5.507 5.009a4.162 4.162 0 0 0 5.317.236L29.294 61.96l39.414 35.958a6.218 6.218 0 0 0 2.143 1.4ZM74.954 27.3 45.048 50l29.906 22.701V27.3Z"
|
||||
clipRule="evenodd"
|
||||
opacity=".25"
|
||||
style={{ mixBlendMode: "overlay" }}
|
||||
/>
|
||||
</g>
|
||||
<defs>
|
||||
<filter
|
||||
id={topShadowFilterId}
|
||||
width="116.727"
|
||||
height="92.246"
|
||||
x="-8.394"
|
||||
y="15.829"
|
||||
colorInterpolationFilters="sRGB"
|
||||
filterUnits="userSpaceOnUse"
|
||||
>
|
||||
<feFlood floodOpacity="0" result="BackgroundImageFix" />
|
||||
<feColorMatrix
|
||||
in="SourceAlpha"
|
||||
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
|
||||
/>
|
||||
<feOffset />
|
||||
<feGaussianBlur stdDeviation="4.167" />
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0" />
|
||||
<feBlend in2="BackgroundImageFix" mode="overlay" result="effect1_dropShadow" />
|
||||
<feBlend in="SourceGraphic" in2="effect1_dropShadow" result="shape" />
|
||||
</filter>
|
||||
<filter
|
||||
id={sideShadowFilterId}
|
||||
width="47.917"
|
||||
height="116.151"
|
||||
x="60.417"
|
||||
y="-8.076"
|
||||
colorInterpolationFilters="sRGB"
|
||||
filterUnits="userSpaceOnUse"
|
||||
>
|
||||
<feFlood floodOpacity="0" result="BackgroundImageFix" />
|
||||
<feColorMatrix
|
||||
in="SourceAlpha"
|
||||
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
|
||||
/>
|
||||
<feOffset />
|
||||
<feGaussianBlur stdDeviation="4.167" />
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0" />
|
||||
<feBlend in2="BackgroundImageFix" mode="overlay" result="effect1_dropShadow" />
|
||||
<feBlend in="SourceGraphic" in2="effect1_dropShadow" result="shape" />
|
||||
</filter>
|
||||
<linearGradient
|
||||
id={overlayGradientId}
|
||||
x1="49.939"
|
||||
x2="49.939"
|
||||
y1=".258"
|
||||
y2="99.742"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop stopColor="#fff" />
|
||||
<stop offset="1" stopColor="#fff" stopOpacity="0" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export const Zed: Icon = (props) => {
|
||||
const id = useId();
|
||||
const clipPathId = `${id}-zed-logo-a`;
|
||||
|
||||
return (
|
||||
<svg {...props} fill="none" viewBox="0 0 96 96">
|
||||
<g clipPath={`url(#${clipPathId})`}>
|
||||
<path
|
||||
fill="currentColor"
|
||||
fillRule="evenodd"
|
||||
d="M9 6a3 3 0 0 0-3 3v66H0V9a9 9 0 0 1 9-9h80.379c4.009 0 6.016 4.847 3.182 7.682L43.055 57.187H57V51h6v7.688a4.5 4.5 0 0 1-4.5 4.5H37.055L26.743 73.5H73.5V36h6v37.5a6 6 0 0 1-6 6H20.743L10.243 90H87a3 3 0 0 0 3-3V21h6v66a9 9 0 0 1-9 9H6.621c-4.009 0-6.016-4.847-3.182-7.682L52.757 39H39v6h-6v-7.5a4.5 4.5 0 0 1 4.5-4.5h21.257l10.5-10.5H22.5V60h-6V22.5a6 6 0 0 1 6-6h52.757L85.757 6H9Z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id={clipPathId}>
|
||||
<path fill="#fff" d="M0 0h96v96H0z" />
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
@@ -1,14 +1,7 @@
|
||||
import {
|
||||
ChevronRightIcon,
|
||||
FolderIcon,
|
||||
GitPullRequestIcon,
|
||||
RocketIcon,
|
||||
TerminalIcon,
|
||||
} from "lucide-react";
|
||||
import { ChevronRightIcon, FolderIcon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
type DesktopUpdateState,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type GitStatusResult,
|
||||
@@ -30,15 +23,6 @@ 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 {
|
||||
@@ -286,7 +270,6 @@ 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) {
|
||||
@@ -783,7 +766,8 @@ 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, {
|
||||
@@ -799,39 +783,6 @@ 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);
|
||||
@@ -841,86 +792,6 @@ 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" />
|
||||
@@ -953,25 +824,6 @@ 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>
|
||||
</>
|
||||
|
||||
@@ -1,174 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,77 +0,0 @@
|
||||
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";
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { estimateTimelineMessageHeight } from "./timelineHeight";
|
||||
|
||||
describe("estimateTimelineMessageHeight", () => {
|
||||
it("uses assistant sizing rules for assistant messages", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "assistant",
|
||||
text: "a".repeat(144),
|
||||
}),
|
||||
).toBe(122);
|
||||
});
|
||||
|
||||
it("uses assistant sizing rules for system messages", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "system",
|
||||
text: "a".repeat(144),
|
||||
}),
|
||||
).toBe(122);
|
||||
});
|
||||
|
||||
it("adds one attachment row for one or two user attachments", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [{ id: "1" }],
|
||||
}),
|
||||
).toBe(346);
|
||||
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [{ id: "1" }, { id: "2" }],
|
||||
}),
|
||||
).toBe(346);
|
||||
});
|
||||
|
||||
it("adds a second attachment row for three or four user attachments", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [{ id: "1" }, { id: "2" }, { id: "3" }],
|
||||
}),
|
||||
).toBe(574);
|
||||
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [{ id: "1" }, { id: "2" }, { id: "3" }, { id: "4" }],
|
||||
}),
|
||||
).toBe(574);
|
||||
});
|
||||
|
||||
it("does not cap long user message estimates", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "a".repeat(56 * 120),
|
||||
}),
|
||||
).toBe(2736);
|
||||
});
|
||||
|
||||
it("counts explicit newlines for user message estimates", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "first\nsecond\nthird",
|
||||
}),
|
||||
).toBe(162);
|
||||
});
|
||||
|
||||
it("uses narrower width to increase user line wrapping", () => {
|
||||
const message = {
|
||||
role: "user" as const,
|
||||
text: "a".repeat(52),
|
||||
};
|
||||
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(140);
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 768 })).toBe(118);
|
||||
});
|
||||
|
||||
it("does not clamp user wrapping too aggressively on very narrow layouts", () => {
|
||||
const message = {
|
||||
role: "user" as const,
|
||||
text: "a".repeat(20),
|
||||
};
|
||||
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 100 })).toBe(184);
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(118);
|
||||
});
|
||||
|
||||
it("uses narrower width to increase assistant line wrapping", () => {
|
||||
const message = {
|
||||
role: "assistant" as const,
|
||||
text: "a".repeat(200),
|
||||
};
|
||||
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(188);
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 768 })).toBe(122);
|
||||
});
|
||||
});
|
||||
@@ -1,90 +0,0 @@
|
||||
const ASSISTANT_CHARS_PER_LINE_FALLBACK = 72;
|
||||
const USER_CHARS_PER_LINE_FALLBACK = 56;
|
||||
const LINE_HEIGHT_PX = 22;
|
||||
const ASSISTANT_BASE_HEIGHT_PX = 78;
|
||||
const USER_BASE_HEIGHT_PX = 96;
|
||||
const ATTACHMENTS_PER_ROW = 2;
|
||||
// Attachment thumbnails render with `max-h-[220px]` plus ~8px row gap.
|
||||
const USER_ATTACHMENT_ROW_HEIGHT_PX = 228;
|
||||
const USER_BUBBLE_WIDTH_RATIO = 0.8;
|
||||
const USER_BUBBLE_HORIZONTAL_PADDING_PX = 32;
|
||||
const ASSISTANT_MESSAGE_HORIZONTAL_PADDING_PX = 8;
|
||||
const USER_MONO_AVG_CHAR_WIDTH_PX = 8.4;
|
||||
const ASSISTANT_AVG_CHAR_WIDTH_PX = 7.2;
|
||||
const MIN_USER_CHARS_PER_LINE = 4;
|
||||
const MIN_ASSISTANT_CHARS_PER_LINE = 20;
|
||||
|
||||
interface TimelineMessageHeightInput {
|
||||
role: "user" | "assistant" | "system";
|
||||
text: string;
|
||||
attachments?: ReadonlyArray<{ id: string }>;
|
||||
}
|
||||
|
||||
interface TimelineHeightEstimateLayout {
|
||||
timelineWidthPx: number | null;
|
||||
}
|
||||
|
||||
function estimateWrappedLineCount(text: string, charsPerLine: number): number {
|
||||
if (text.length === 0) return 1;
|
||||
|
||||
// Avoid allocating via split for long logs; iterate once and count wrapped lines.
|
||||
let lines = 0;
|
||||
let currentLineLength = 0;
|
||||
for (let index = 0; index < text.length; index += 1) {
|
||||
if (text.charCodeAt(index) === 10) {
|
||||
lines += Math.max(1, Math.ceil(currentLineLength / charsPerLine));
|
||||
currentLineLength = 0;
|
||||
continue;
|
||||
}
|
||||
currentLineLength += 1;
|
||||
}
|
||||
|
||||
lines += Math.max(1, Math.ceil(currentLineLength / charsPerLine));
|
||||
return lines;
|
||||
}
|
||||
|
||||
function isFinitePositiveNumber(value: number | null | undefined): value is number {
|
||||
return typeof value === "number" && Number.isFinite(value) && value > 0;
|
||||
}
|
||||
|
||||
function estimateCharsPerLineForUser(timelineWidthPx: number | null): number {
|
||||
if (!isFinitePositiveNumber(timelineWidthPx)) return USER_CHARS_PER_LINE_FALLBACK;
|
||||
const bubbleWidthPx = timelineWidthPx * USER_BUBBLE_WIDTH_RATIO;
|
||||
const textWidthPx = Math.max(bubbleWidthPx - USER_BUBBLE_HORIZONTAL_PADDING_PX, 0);
|
||||
return Math.max(MIN_USER_CHARS_PER_LINE, Math.floor(textWidthPx / USER_MONO_AVG_CHAR_WIDTH_PX));
|
||||
}
|
||||
|
||||
function estimateCharsPerLineForAssistant(timelineWidthPx: number | null): number {
|
||||
if (!isFinitePositiveNumber(timelineWidthPx)) return ASSISTANT_CHARS_PER_LINE_FALLBACK;
|
||||
const textWidthPx = Math.max(timelineWidthPx - ASSISTANT_MESSAGE_HORIZONTAL_PADDING_PX, 0);
|
||||
return Math.max(
|
||||
MIN_ASSISTANT_CHARS_PER_LINE,
|
||||
Math.floor(textWidthPx / ASSISTANT_AVG_CHAR_WIDTH_PX),
|
||||
);
|
||||
}
|
||||
|
||||
export function estimateTimelineMessageHeight(
|
||||
message: TimelineMessageHeightInput,
|
||||
layout: TimelineHeightEstimateLayout = { timelineWidthPx: null },
|
||||
): number {
|
||||
if (message.role === "assistant") {
|
||||
const charsPerLine = estimateCharsPerLineForAssistant(layout.timelineWidthPx);
|
||||
const estimatedLines = estimateWrappedLineCount(message.text, charsPerLine);
|
||||
return ASSISTANT_BASE_HEIGHT_PX + estimatedLines * LINE_HEIGHT_PX;
|
||||
}
|
||||
|
||||
if (message.role === "user") {
|
||||
const charsPerLine = estimateCharsPerLineForUser(layout.timelineWidthPx);
|
||||
const estimatedLines = estimateWrappedLineCount(message.text, charsPerLine);
|
||||
const attachmentCount = message.attachments?.length ?? 0;
|
||||
const attachmentRows = Math.ceil(attachmentCount / ATTACHMENTS_PER_ROW);
|
||||
const attachmentHeight = attachmentRows * USER_ATTACHMENT_ROW_HEIGHT_PX;
|
||||
return USER_BASE_HEIGHT_PX + estimatedLines * LINE_HEIGHT_PX + attachmentHeight;
|
||||
}
|
||||
|
||||
// `system` messages are not rendered in the chat timeline, but keep a stable
|
||||
// explicit branch in case they are present in timeline data.
|
||||
const charsPerLine = estimateCharsPerLineForAssistant(layout.timelineWidthPx);
|
||||
const estimatedLines = estimateWrappedLineCount(message.text, charsPerLine);
|
||||
return ASSISTANT_BASE_HEIGHT_PX + estimatedLines * LINE_HEIGHT_PX;
|
||||
}
|
||||
@@ -3,7 +3,6 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
detectComposerTrigger,
|
||||
expandCollapsedComposerCursor,
|
||||
isCollapsedCursorAdjacentToMention,
|
||||
replaceTextRange,
|
||||
} from "./composer-logic";
|
||||
|
||||
@@ -78,36 +77,3 @@ describe("expandCollapsedComposerCursor", () => {
|
||||
expect(detectComposerTrigger(text, expandedCursor)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("isCollapsedCursorAdjacentToMention", () => {
|
||||
it("returns false when no mention exists", () => {
|
||||
expect(isCollapsedCursorAdjacentToMention("plain text", 6, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention("plain text", 6, "right")).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps @query typing non-adjacent while no mention pill exists", () => {
|
||||
const text = "hello @pac";
|
||||
expect(isCollapsedCursorAdjacentToMention(text, text.length, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, text.length, "right")).toBe(false);
|
||||
});
|
||||
|
||||
it("detects left adjacency only when cursor is directly after a mention", () => {
|
||||
const text = "open @AGENTS.md next";
|
||||
const mentionStart = "open ".length;
|
||||
const mentionEnd = mentionStart + 1;
|
||||
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionEnd, "left")).toBe(true);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionStart, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionEnd + 1, "left")).toBe(false);
|
||||
});
|
||||
|
||||
it("detects right adjacency only when cursor is directly before a mention", () => {
|
||||
const text = "open @AGENTS.md next";
|
||||
const mentionStart = "open ".length;
|
||||
const mentionEnd = mentionStart + 1;
|
||||
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionStart, "right")).toBe(true);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionEnd, "right")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionStart - 1, "right")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -58,52 +58,6 @@ export function expandCollapsedComposerCursor(text: string, cursorInput: number)
|
||||
return expandedCursor;
|
||||
}
|
||||
|
||||
function collapsedSegmentLength(segment: { type: "text"; text: string } | { type: "mention" }): number {
|
||||
return segment.type === "mention" ? 1 : segment.text.length;
|
||||
}
|
||||
|
||||
function clampCollapsedComposerCursor(
|
||||
segments: ReadonlyArray<{ type: "text"; text: string } | { type: "mention" }>,
|
||||
cursorInput: number,
|
||||
): number {
|
||||
const collapsedLength = segments.reduce(
|
||||
(total, segment) => total + collapsedSegmentLength(segment),
|
||||
0,
|
||||
);
|
||||
if (!Number.isFinite(cursorInput)) {
|
||||
return collapsedLength;
|
||||
}
|
||||
return Math.max(0, Math.min(collapsedLength, Math.floor(cursorInput)));
|
||||
}
|
||||
|
||||
export function isCollapsedCursorAdjacentToMention(
|
||||
text: string,
|
||||
cursorInput: number,
|
||||
direction: "left" | "right",
|
||||
): boolean {
|
||||
const segments = splitPromptIntoComposerSegments(text);
|
||||
if (!segments.some((segment) => segment.type === "mention")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const cursor = clampCollapsedComposerCursor(segments, cursorInput);
|
||||
let collapsedOffset = 0;
|
||||
|
||||
for (const segment of segments) {
|
||||
if (segment.type === "mention") {
|
||||
if (direction === "left" && cursor === collapsedOffset + 1) {
|
||||
return true;
|
||||
}
|
||||
if (direction === "right" && cursor === collapsedOffset) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
collapsedOffset += collapsedSegmentLength(segment);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null {
|
||||
const cursor = clampCursor(text, cursorInput);
|
||||
const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1;
|
||||
|
||||
@@ -16,6 +16,8 @@ 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,
|
||||
};
|
||||
@@ -87,6 +89,24 @@ 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;
|
||||
@@ -96,11 +116,9 @@ 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.");
|
||||
@@ -108,7 +126,6 @@ export function gitRunStackedActionMutationOptions(input: {
|
||||
cwd: input.cwd,
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(featureBranch ? { featureBranch } : {}),
|
||||
});
|
||||
},
|
||||
onSettled: async () => {
|
||||
|
||||
+25
-5
@@ -1,21 +1,41 @@
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { RouterProvider } from "@tanstack/react-router";
|
||||
import { createHashHistory, createBrowserHistory } from "@tanstack/react-router";
|
||||
import { createHashHistory, createRouter, createBrowserHistory } from "@tanstack/react-router";
|
||||
import { StoreProvider } from "./store";
|
||||
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
import "./index.css";
|
||||
|
||||
import { isElectron } from "./env";
|
||||
import { getRouter } from "./router";
|
||||
import { APP_DISPLAY_NAME } from "./branding";
|
||||
import { isElectron } from "./env";
|
||||
import { routeTree } from "./routeTree.gen";
|
||||
|
||||
const history = isElectron ? createHashHistory() : createBrowserHistory();
|
||||
|
||||
const router = getRouter(history);
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
document.title = APP_DISPLAY_NAME;
|
||||
|
||||
const router = createRouter({
|
||||
routeTree,
|
||||
history,
|
||||
context: {
|
||||
queryClient,
|
||||
},
|
||||
Wrap: ({ children }) => (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<StoreProvider>{children}</StoreProvider>
|
||||
</QueryClientProvider>
|
||||
),
|
||||
});
|
||||
|
||||
declare module "@tanstack/react-router" {
|
||||
interface Register {
|
||||
router: typeof router;
|
||||
}
|
||||
}
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
|
||||
<React.StrictMode>
|
||||
<RouterProvider router={router} />
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
import { createElement } from "react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { createRouter } from "@tanstack/react-router";
|
||||
|
||||
import { routeTree } from "./routeTree.gen";
|
||||
import { StoreProvider } from "./store";
|
||||
|
||||
type RouterHistory = NonNullable<Parameters<typeof createRouter>[0]["history"]>;
|
||||
|
||||
export function getRouter(history: RouterHistory) {
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
return createRouter({
|
||||
routeTree,
|
||||
history,
|
||||
context: {
|
||||
queryClient,
|
||||
},
|
||||
Wrap: ({ children }) =>
|
||||
createElement(
|
||||
QueryClientProvider,
|
||||
{ client: queryClient },
|
||||
createElement(StoreProvider, null, children),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export type AppRouter = ReturnType<typeof getRouter>;
|
||||
|
||||
declare module "@tanstack/react-router" {
|
||||
interface Register {
|
||||
router: AppRouter;
|
||||
}
|
||||
}
|
||||
@@ -26,9 +26,6 @@ export const Route = createRootRouteWithContext<{
|
||||
}>()({
|
||||
component: RootRouteView,
|
||||
errorComponent: RootRouteErrorView,
|
||||
head: () => ({
|
||||
meta: [{ name: "title", content: APP_DISPLAY_NAME }],
|
||||
}),
|
||||
});
|
||||
|
||||
function RootRouteView() {
|
||||
@@ -155,7 +152,9 @@ function EventRouter() {
|
||||
latestSequence = Math.max(latestSequence, snapshot.snapshotSequence);
|
||||
syncServerReadModel(snapshot);
|
||||
const activeThreadIds = new Set(
|
||||
snapshot.threads.filter((t) => t.deletedAt === null).map((t) => t.id),
|
||||
snapshot.threads
|
||||
.filter((t) => t.deletedAt === null)
|
||||
.map((t) => t.id),
|
||||
);
|
||||
removeOrphanedTerminalStates(activeThreadIds);
|
||||
if (pending) {
|
||||
@@ -196,13 +195,11 @@ function EventRouter() {
|
||||
if (hasRunningSubprocess === null) {
|
||||
return;
|
||||
}
|
||||
useTerminalStateStore
|
||||
.getState()
|
||||
.setTerminalActivity(
|
||||
ThreadId.makeUnsafe(event.threadId),
|
||||
event.terminalId,
|
||||
hasRunningSubprocess,
|
||||
);
|
||||
useTerminalStateStore.getState().setTerminalActivity(
|
||||
ThreadId.makeUnsafe(event.threadId),
|
||||
event.terminalId,
|
||||
hasRunningSubprocess,
|
||||
);
|
||||
});
|
||||
const unsubWelcome = onServerWelcome((payload) => {
|
||||
void (async () => {
|
||||
@@ -279,13 +276,7 @@ function EventRouter() {
|
||||
unsubWelcome();
|
||||
unsubServerConfigUpdated();
|
||||
};
|
||||
}, [
|
||||
navigate,
|
||||
queryClient,
|
||||
removeOrphanedTerminalStates,
|
||||
setProjectExpanded,
|
||||
syncServerReadModel,
|
||||
]);
|
||||
}, [navigate, queryClient, removeOrphanedTerminalStates, setProjectExpanded, syncServerReadModel]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
WS_CHANNELS,
|
||||
type ServerProviderStatus,
|
||||
} from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
@@ -63,16 +62,6 @@ 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();
|
||||
@@ -173,7 +162,6 @@ describe("wsNativeApi", () => {
|
||||
message: "Entry at index 1 is invalid.",
|
||||
},
|
||||
],
|
||||
providers: defaultProviders,
|
||||
} as const;
|
||||
emitPush(WS_CHANNELS.serverConfigUpdated, payload);
|
||||
|
||||
@@ -197,17 +185,14 @@ 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);
|
||||
});
|
||||
@@ -391,4 +376,5 @@ describe("wsNativeApi", () => {
|
||||
{ x: 20, y: 30 },
|
||||
);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -21,6 +21,5 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"include": ["src", "vite.config.ts"],
|
||||
"exclude": ["src/**/*.browser.ts", "src/**/*.browser.tsx"]
|
||||
"include": ["src", "vite.config.ts"]
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { playwright } from "@vitest/browser-playwright";
|
||||
import { defineConfig, mergeConfig } from "vitest/config";
|
||||
|
||||
import viteConfig from "./vite.config";
|
||||
|
||||
const srcPath = fileURLToPath(new URL("./src", import.meta.url));
|
||||
|
||||
export default mergeConfig(
|
||||
viteConfig,
|
||||
defineConfig({
|
||||
resolve: {
|
||||
alias: {
|
||||
"~": srcPath,
|
||||
},
|
||||
},
|
||||
test: {
|
||||
include: ["src/components/ChatView.browser.tsx"],
|
||||
browser: {
|
||||
enabled: true,
|
||||
provider: playwright(),
|
||||
instances: [{ browser: "chromium" }],
|
||||
headless: true,
|
||||
},
|
||||
testTimeout: 30_000,
|
||||
hookTimeout: 30_000,
|
||||
},
|
||||
}),
|
||||
);
|
||||
@@ -5,34 +5,34 @@
|
||||
"": {
|
||||
"name": "@t3tools/monorepo",
|
||||
"devDependencies": {
|
||||
"@types/node": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"oxfmt": "^0.35.0",
|
||||
"oxlint": "^1.50.0",
|
||||
"turbo": "^2.3.3",
|
||||
"vitest": "catalog:",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0",
|
||||
},
|
||||
},
|
||||
"apps/desktop": {
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
"electron": "40.6.0",
|
||||
"electron-updater": "^6.6.2",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@types/node": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
"@types/node": "^22.10.2",
|
||||
"electronmon": "^2.0.2",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0",
|
||||
"wait-on": "^8.0.2",
|
||||
},
|
||||
},
|
||||
"apps/server": {
|
||||
"name": "t3",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"bin": {
|
||||
"t3": "./dist/index.mjs",
|
||||
},
|
||||
@@ -46,28 +46,26 @@
|
||||
"ws": "^8.18.0",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/language-service": "0.75.1",
|
||||
"@effect/vitest": "catalog:",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/bun": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"@types/bun": "^1.3.9",
|
||||
"@types/node": "^22.10.2",
|
||||
"@types/ws": "^8.5.13",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0",
|
||||
},
|
||||
},
|
||||
"apps/web": {
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"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",
|
||||
@@ -92,73 +90,32 @@
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^5.1.4",
|
||||
"@vitest/browser-playwright": "^4.0.18",
|
||||
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
|
||||
"msw": "^2.12.10",
|
||||
"playwright": "^1.58.2",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "catalog:",
|
||||
"typescript": "^5.7.3",
|
||||
"vite": "^8.0.0-beta.12",
|
||||
"vitest": "catalog:",
|
||||
"vitest-browser-react": "^2.0.5",
|
||||
},
|
||||
},
|
||||
"packages/contracts": {
|
||||
"name": "@t3tools/contracts",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/language-service": "0.75.1",
|
||||
"@effect/vitest": "catalog:",
|
||||
"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:",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
},
|
||||
},
|
||||
},
|
||||
"catalog": {
|
||||
"@effect/language-service": "0.75.1",
|
||||
"@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",
|
||||
"@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@f591738",
|
||||
"@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@f591738",
|
||||
"@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@f591738",
|
||||
"effect": "https://pkg.pr.new/Effect-TS/effect-smol/effect@f591738",
|
||||
},
|
||||
"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=="],
|
||||
@@ -211,13 +168,13 @@
|
||||
|
||||
"@effect/language-service": ["@effect/[email protected]", "", { "bin": { "effect-language-service": "cli.js" } }, "sha512-g9xD2tAQgRFpYC2YgpZq02VeSL5fBbFJ0B/g1o+14NuNmwtaYJc7SjiLWAA9eyhJHosNrn6h1Ye+Kx6j5mN0AA=="],
|
||||
|
||||
"@effect/platform-node": ["@effect/platform-node@https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b", { "dependencies": { "@effect/platform-node-shared": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node-shared@8881a9b606d84a6f5eb6615279138322984f5368", "mime": "^4.1.0", "undici": "^7.20.0" }, "peerDependencies": { "effect": "^4.0.0-beta.25", "ioredis": "^5.7.0" } }],
|
||||
"@effect/platform-node": ["@effect/platform-node@https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@f591738", { "dependencies": { "@effect/platform-node-shared": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node-shared@f59173885df0eb490dc2e6619ae89467feac0413", "mime": "^4.1.0", "undici": "^7.20.0" }, "peerDependencies": { "effect": "^4.0.0-beta.19", "ioredis": "^5.7.0" } }],
|
||||
|
||||
"@effect/platform-node-shared": ["@effect/platform-node-shared@https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node-shared@8881a9b606d84a6f5eb6615279138322984f5368", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.25" } }],
|
||||
"@effect/platform-node-shared": ["@effect/platform-node-shared@https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node-shared@f59173885df0eb490dc2e6619ae89467feac0413", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.19" } }],
|
||||
|
||||
"@effect/sql-sqlite-bun": ["@effect/sql-sqlite-bun@https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@8881a9b", { "peerDependencies": { "effect": "^4.0.0-beta.25" } }],
|
||||
"@effect/sql-sqlite-bun": ["@effect/sql-sqlite-bun@https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@f591738", { "peerDependencies": { "effect": "^4.0.0-beta.19" } }],
|
||||
|
||||
"@effect/vitest": ["@effect/vitest@https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@8881a9b", { "peerDependencies": { "effect": "^4.0.0-beta.25", "vitest": "^3.0.0 || ^4.0.0" } }],
|
||||
"@effect/vitest": ["@effect/vitest@https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@f591738", { "peerDependencies": { "effect": "^4.0.0-beta.19", "vitest": "^3.0.0" } }],
|
||||
|
||||
"@electron/get": ["@electron/[email protected]", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ=="],
|
||||
|
||||
@@ -471,8 +428,6 @@
|
||||
|
||||
"@pierre/diffs": ["@pierre/[email protected]", "", { "dependencies": { "@shikijs/transformers": "^3.0.0", "diff": "8.0.3", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-McjTuEPuacSIcXdoI2O9W6VSHIOs9ApEHnEUwONKZnKqIo2GGv1vNg9Pr8tgBOL7lgBWNEHX5ROJ5z1X74sENQ=="],
|
||||
|
||||
"@polka/url": ["@polka/[email protected]", "", {}, "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww=="],
|
||||
|
||||
"@preact/signals-core": ["@preact/[email protected]", "", {}, "sha512-slT6XeTCAbdql61GVLlGU4x7XHI7kCZV5Um5uhE4zLX4ApgiiXc0UYFvVOKq06xcovzp7p+61l68oPi563ARKg=="],
|
||||
|
||||
"@quansync/fs": ["@quansync/[email protected]", "", { "dependencies": { "quansync": "^1.0.0" } }, "sha512-4TJ3DFtlf1L5LDMaM6CanJ/0lckGNtJcMjQ1NAV6zDmA0tEHKZtxNKin8EgPaVX1YzljbxckyT2tJrpQKAtngQ=="],
|
||||
@@ -581,10 +536,6 @@
|
||||
|
||||
"@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,7 +636,7 @@
|
||||
|
||||
"@types/ms": ["@types/[email protected]", "", {}, "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="],
|
||||
|
||||
"@types/node": ["@types/node@24.10.13", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg=="],
|
||||
"@types/node": ["@types/node@22.19.11", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w=="],
|
||||
|
||||
@@ -705,10 +656,6 @@
|
||||
|
||||
"@vitejs/plugin-react": ["@vitejs/[email protected]", "", { "dependencies": { "@babel/core": "^7.29.0", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", "@rolldown/pluginutils": "1.0.0-rc.3", "@types/babel__core": "^7.20.5", "react-refresh": "^0.18.0" }, "peerDependencies": { "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" } }, "sha512-VIcFLdRi/VYRU8OL/puL7QXMYafHmqOnwTZY50U1JPlCNj30PxCMx65c494b1K9be9hX83KVt0+gTEwTWLqToA=="],
|
||||
|
||||
"@vitest/browser": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/mocker": "4.0.18", "@vitest/utils": "4.0.18", "magic-string": "^0.30.21", "pixelmatch": "7.1.0", "pngjs": "^7.0.0", "sirv": "^3.0.2", "tinyrainbow": "^3.0.3", "ws": "^8.18.3" }, "peerDependencies": { "vitest": "4.0.18" } }, "sha512-gVQqh7paBz3gC+ZdcCmNSWJMk70IUjDeVqi+5m5vYpEHsIwRgw3Y545jljtajhkekIpIp5Gg8oK7bctgY0E2Ng=="],
|
||||
|
||||
"@vitest/browser-playwright": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/browser": "4.0.18", "@vitest/mocker": "4.0.18", "tinyrainbow": "^3.0.3" }, "peerDependencies": { "playwright": "*", "vitest": "4.0.18" } }, "sha512-gfajTHVCiwpxRj1qh0Sh/5bbGLG4F/ZH/V9xvFVoFddpITfMta9YGow0W6ZpTTORv2vdJuz9TnrNSmjKvpOf4g=="],
|
||||
|
||||
"@vitest/expect": ["@vitest/[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "@types/chai": "^5.2.2", "@vitest/spy": "4.0.18", "@vitest/utils": "4.0.18", "chai": "^6.2.1", "tinyrainbow": "^3.0.3" } }, "sha512-8sCWUyckXXYvx4opfzVY03EOiYVxyNrHS5QxX3DAIi5dpJAAkyJezHCP77VMX4HKA2LDT/Jpfo8i2r5BE3GnQQ=="],
|
||||
|
||||
"@vitest/mocker": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/spy": "4.0.18", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^6.0.0 || ^7.0.0-0" }, "optionalPeers": ["msw", "vite"] }, "sha512-HhVd0MDnzzsgevnOWCBj5Otnzobjy5wLBe4EdeeFGv8luMsGcYqDuFRMcttKWZA5vVO8RFjexVovXvAM4JoJDQ=="],
|
||||
@@ -737,8 +684,6 @@
|
||||
|
||||
"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=="],
|
||||
@@ -769,8 +714,6 @@
|
||||
|
||||
"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=="],
|
||||
@@ -789,6 +732,8 @@
|
||||
|
||||
"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=="],
|
||||
@@ -865,13 +810,13 @@
|
||||
|
||||
"dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
|
||||
|
||||
"effect": ["effect@https://pkg.pr.new/Effect-TS/effect-smol/effect@8881a9b", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }],
|
||||
"effect": ["effect@https://pkg.pr.new/Effect-TS/effect-smol/effect@f591738", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }],
|
||||
|
||||
"electron": ["[email protected]", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-ett8W+yOFGDuM0vhJMamYSkrbV3LoaffzJd9GfjI96zRAxyrNqUSKqBpf/WGbQCweDxX2pkUCUfrv4wwKpsFZA=="],
|
||||
|
||||
"electron-to-chromium": ["[email protected]", "", {}, "sha512-9tfDXhJ4RKFNerfjdCcZfufu49vg620741MNs26a9+bhLThdB+plgMeou98CAaHu/WATj2iHOOHTp1hWtABj2A=="],
|
||||
|
||||
"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=="],
|
||||
"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=="],
|
||||
|
||||
"emoji-regex": ["[email protected]", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
|
||||
|
||||
@@ -927,9 +872,9 @@
|
||||
|
||||
"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@10.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ=="],
|
||||
"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=="],
|
||||
|
||||
"fsevents": ["[email protected].2", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="],
|
||||
"fsevents": ["[email protected].3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
"function-bind": ["[email protected]", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
|
||||
|
||||
@@ -959,6 +904,8 @@
|
||||
|
||||
"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=="],
|
||||
@@ -985,6 +932,8 @@
|
||||
|
||||
"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=="],
|
||||
@@ -1031,8 +980,6 @@
|
||||
|
||||
"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=="],
|
||||
@@ -1041,14 +988,12 @@
|
||||
|
||||
"json5": ["[email protected]", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="],
|
||||
|
||||
"jsonfile": ["jsonfile@6.2.0", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg=="],
|
||||
"jsonfile": ["jsonfile@4.0.0", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="],
|
||||
|
||||
"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=="],
|
||||
@@ -1081,12 +1026,10 @@
|
||||
|
||||
"lodash.defaults": ["[email protected]", "", {}, "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ=="],
|
||||
|
||||
"lodash.escaperegexp": ["[email protected]", "", {}, "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw=="],
|
||||
"lodash.difference": ["[email protected]", "", {}, "sha512-dS2j+W26TQ7taQBGN8Lbbq04ssV3emRw4NY58WErlTO29pIqS0HmoT5aJ9+TUQ1N3G+JOZSji4eugsWwGp9yPA=="],
|
||||
|
||||
"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=="],
|
||||
@@ -1191,6 +1134,8 @@
|
||||
|
||||
"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=="],
|
||||
@@ -1201,8 +1146,6 @@
|
||||
|
||||
"minimist": ["[email protected]", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="],
|
||||
|
||||
"mrmime": ["[email protected]", "", {}, "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ=="],
|
||||
|
||||
"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
|
||||
|
||||
"msgpackr": ["[email protected]", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.2" } }, "sha512-bC4UGzHhVvgDNS7kn9tV8fAucIYUBuGojcaLiz7v+P63Lmtm0Xeji8B/8tYKddALXxJLpwIeBmUN3u64C4YkRA=="],
|
||||
@@ -1261,13 +1204,7 @@
|
||||
|
||||
"picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],
|
||||
|
||||
"pixelmatch": ["[email protected]", "", { "dependencies": { "pngjs": "^7.0.0" }, "bin": { "pixelmatch": "bin/pixelmatch" } }, "sha512-1wrVzJ2STrpmONHKBy228LM1b84msXDUoAzVEl0R8Mz4Ce6EPr+IVtxm8+yvrqLYMHswREkjYFaMxnyGnaY3Ng=="],
|
||||
|
||||
"playwright": ["[email protected]", "", { "dependencies": { "playwright-core": "1.58.2" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A=="],
|
||||
|
||||
"playwright-core": ["[email protected]", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg=="],
|
||||
|
||||
"pngjs": ["[email protected]", "", {}, "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow=="],
|
||||
"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=="],
|
||||
|
||||
@@ -1321,12 +1258,16 @@
|
||||
|
||||
"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=="],
|
||||
@@ -1343,9 +1284,9 @@
|
||||
|
||||
"run-applescript": ["[email protected]", "", {}, "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q=="],
|
||||
|
||||
"rxjs": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="],
|
||||
"runtime-required": ["[email protected]", "", {}, "sha512-yX97f5E0WfNpcQnfVjap6vzQcvErkYYCx6eTK4siqGEdC8lglwypUFgZVTX7ShvIlgfkC4XGFl9O1KTYcff0pw=="],
|
||||
|
||||
"sax": ["[email protected]", "", {}, "sha512-21IYA3Q5cQf089Z6tgaUTr7lDAyzoTPx5HRtbhsME8Udispad8dC/+sziTNugOEx54ilvatQ9YCzl4KQLPcRHA=="],
|
||||
"rxjs": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="],
|
||||
|
||||
"scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
|
||||
|
||||
@@ -1365,8 +1306,6 @@
|
||||
|
||||
"signal-exit": ["[email protected]", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
|
||||
|
||||
"sirv": ["[email protected]", "", { "dependencies": { "@polka/url": "^1.0.0-next.24", "mrmime": "^2.0.0", "totalist": "^3.0.0" } }, "sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g=="],
|
||||
|
||||
"source-map": ["[email protected]", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="],
|
||||
|
||||
"source-map-js": ["[email protected]", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
|
||||
@@ -1397,6 +1336,8 @@
|
||||
|
||||
"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=="],
|
||||
@@ -1411,8 +1352,6 @@
|
||||
|
||||
"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=="],
|
||||
@@ -1433,8 +1372,6 @@
|
||||
|
||||
"toml": ["[email protected]", "", {}, "sha512-y/mWCZinnvxjTKYhJ+pYxwD0mRLVvOtdS2Awbgxln6iEnt4rk0yBxeSBHkGJcPucRiG0e55mwWp+g/05rsrd6w=="],
|
||||
|
||||
"totalist": ["[email protected]", "", {}, "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ=="],
|
||||
|
||||
"tough-cookie": ["[email protected]", "", { "dependencies": { "tldts": "^7.0.5" } }, "sha512-kXuRi1mtaKMrsLUxz3sQYvVl37B0Ns6MzfrtV5DvJceE9bPyspOqk9xxv7XbZWcfLWbFmm997vl83qUWVJA64w=="],
|
||||
|
||||
"tree-kill": ["[email protected]", "", { "bin": { "tree-kill": "cli.js" } }, "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A=="],
|
||||
@@ -1471,7 +1408,7 @@
|
||||
|
||||
"undici": ["[email protected]", "", {}, "sha512-RqslV2Us5BrllB+JeiZnK4peryVTndy9Dnqq62S3yYRRTj0tFQCwEniUy2167skdGOy3vqRzEvl1Dm4sV2ReDg=="],
|
||||
|
||||
"undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
|
||||
"undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"unified": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="],
|
||||
|
||||
@@ -1485,7 +1422,9 @@
|
||||
|
||||
"unist-util-visit-parents": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0" } }, "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ=="],
|
||||
|
||||
"universalify": ["universalify@2.0.1", "", {}, "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw=="],
|
||||
"universalify": ["[email protected].2", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="],
|
||||
|
||||
"unixify": ["[email protected]", "", { "dependencies": { "normalize-path": "^2.1.1" } }, "sha512-6bc58dPYhCMHHuwxldQxO3RRNZ4eCogZ/st++0+fcC1nr0jiGUtAdBJ2qzmLQWSxbtz42pWt4QQMiZ9HvZf5cg=="],
|
||||
|
||||
"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=="],
|
||||
|
||||
@@ -1507,10 +1446,10 @@
|
||||
|
||||
"vitest": ["[email protected]", "", { "dependencies": { "@vitest/expect": "4.0.18", "@vitest/mocker": "4.0.18", "@vitest/pretty-format": "4.0.18", "@vitest/runner": "4.0.18", "@vitest/snapshot": "4.0.18", "@vitest/spy": "4.0.18", "@vitest/utils": "4.0.18", "es-module-lexer": "^1.7.0", "expect-type": "^1.2.2", "magic-string": "^0.30.21", "obug": "^2.1.1", "pathe": "^2.0.3", "picomatch": "^4.0.3", "std-env": "^3.10.0", "tinybench": "^2.9.0", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tinyrainbow": "^3.0.3", "vite": "^6.0.0 || ^7.0.0", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "4.0.18", "@vitest/browser-preview": "4.0.18", "@vitest/browser-webdriverio": "4.0.18", "@vitest/ui": "4.0.18", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "vitest.mjs" } }, "sha512-hOQuK7h0FGKgBAas7v0mSAsnvrIgAvWmRFjmzpJ7SwFHH3g1k2u37JtYwOwmEKhK6ZO3v9ggDBBm0La1LCK4uQ=="],
|
||||
|
||||
"vitest-browser-react": ["[email protected]", "", { "peerDependencies": { "@types/react": "^18.0.0 || ^19.0.0", "@types/react-dom": "^18.0.0 || ^19.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "vitest": "^4.0.0" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-YODQX8mHTJCyKNVYTWJrLEYrUtw+QfLl78owgvuE7C5ydgmGBq6v5s4jK2w6wdPhIZsN9PpV1rQbmAevWJjO9g=="],
|
||||
|
||||
"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=="],
|
||||
@@ -1569,8 +1508,6 @@
|
||||
|
||||
"@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=="],
|
||||
@@ -1597,30 +1534,24 @@
|
||||
|
||||
"@types/babel__template/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww=="],
|
||||
|
||||
"@types/cacheable-request/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/keyv/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/responselike/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/ws/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/yauzl/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@vitejs/plugin-react/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=="],
|
||||
|
||||
"anymatch/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
|
||||
|
||||
"babel-dead-code-elimination/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww=="],
|
||||
|
||||
"chokidar/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
"bun-types/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg=="],
|
||||
|
||||
"cliui/wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
|
||||
|
||||
"clone-response/mimic-response": ["[email protected]", "", {}, "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ=="],
|
||||
|
||||
"electron/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg=="],
|
||||
|
||||
"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=="],
|
||||
@@ -1629,13 +1560,9 @@
|
||||
|
||||
"rolldown-plugin-dts/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^8.0.0-rc.1", "@babel/helper-validator-identifier": "^8.0.0-rc.1" } }, "sha512-ubmJ6TShyaD69VE9DQrlXcdkvJbmwWPB8qYj0H2kaJi29O7vJT9ajSdBd2W8CG34pwL9pYA74fi7RHC1qbLoVQ=="],
|
||||
|
||||
"rollup/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
"serialize-error/type-fest": ["[email protected]", "", {}, "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg=="],
|
||||
|
||||
"tsx/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
"vite/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
"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=="],
|
||||
|
||||
@@ -1643,10 +1570,6 @@
|
||||
|
||||
"@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=="],
|
||||
@@ -1669,22 +1592,10 @@
|
||||
|
||||
"@tailwindcss/node/lightningcss/lightningcss-win32-x64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-5g1yc73p+iAkid5phb4oVFMB45417DkRevRbt/El/gKXJk4jid+vPFF/AXbxn05Aky8PapwzZrdJShv5C0avjw=="],
|
||||
|
||||
"@tailwindcss/vite/vite/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
"bun-types/@types/node/undici-types": ["[email protected]", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
|
||||
|
||||
"@types/cacheable-request/@types/node/undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@types/keyv/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@types/responselike/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@types/ws/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@types/yauzl/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@vitejs/plugin-react/vite/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
"electron/@types/node/undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
|
||||
|
||||
"rolldown-plugin-dts/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
|
||||
|
||||
"vitest/vite/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
}
|
||||
}
|
||||
@@ -12,29 +12,9 @@ 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
|
||||
|
||||
+16
-25
@@ -4,28 +4,22 @@
|
||||
"workspaces": {
|
||||
"packages": [
|
||||
"apps/*",
|
||||
"packages/*",
|
||||
"scripts"
|
||||
"packages/*"
|
||||
],
|
||||
"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",
|
||||
"@types/bun": "^1.3.9",
|
||||
"@types/node": "^24.10.13",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0"
|
||||
"effect": "https://pkg.pr.new/Effect-TS/effect-smol/effect@f591738",
|
||||
"@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@f591738",
|
||||
"@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@f591738",
|
||||
"@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@f591738",
|
||||
"@effect/language-service": "0.75.1"
|
||||
}
|
||||
},
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"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",
|
||||
"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",
|
||||
"start": "turbo run start --filter=t3",
|
||||
"start:desktop": "turbo run start --filter=@t3tools/desktop",
|
||||
"build": "turbo run build",
|
||||
@@ -46,20 +40,17 @@
|
||||
"sync:vscode-icons": "node scripts/sync-vscode-icons.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"oxfmt": "^0.35.0",
|
||||
"oxlint": "^1.50.0",
|
||||
"turbo": "^2.3.3",
|
||||
"vitest": "catalog:"
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"bun": "^1.3.9",
|
||||
"node": "^24.13.1"
|
||||
},
|
||||
"packageManager": "[email protected]",
|
||||
"msw": {
|
||||
"workerDirectory": [
|
||||
"apps/web/public"
|
||||
]
|
||||
}
|
||||
}
|
||||
"packageManager": "[email protected]"
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/contracts",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"private": true,
|
||||
"files": [
|
||||
"dist"
|
||||
@@ -27,10 +27,9 @@
|
||||
"effect": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/language-service": "0.75.1",
|
||||
"@effect/vitest": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3"
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,6 @@ import { TrimmedNonEmptyString } from "./baseSchemas";
|
||||
|
||||
export const EDITORS = [
|
||||
{ id: "cursor", label: "Cursor", command: "cursor" },
|
||||
{ id: "vscode", label: "VS Code", command: "code" },
|
||||
{ id: "zed", label: "Zed", command: "zed" },
|
||||
{ id: "file-manager", label: "File Manager", command: null },
|
||||
] as const;
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@ 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",
|
||||
@@ -54,7 +53,6 @@ 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;
|
||||
|
||||
@@ -141,10 +139,6 @@ 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,35 +43,6 @@ 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>;
|
||||
@@ -82,10 +53,6 @@ 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,8 +1,6 @@
|
||||
import { Schema } from "effect";
|
||||
import { IsoDateTime, TrimmedNonEmptyString } from "./baseSchemas";
|
||||
import { 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"),
|
||||
@@ -26,55 +24,11 @@ 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;
|
||||
|
||||
@@ -89,6 +43,5 @@ export type ServerUpsertKeybindingResult = typeof ServerUpsertKeybindingResult.T
|
||||
|
||||
export const ServerConfigUpdatedPayload = Schema.Struct({
|
||||
issues: ServerConfigIssues,
|
||||
providers: ServerProviderStatuses,
|
||||
});
|
||||
export type ServerConfigUpdatedPayload = typeof ServerConfigUpdatedPayload.Type;
|
||||
@@ -1,35 +0,0 @@
|
||||
{
|
||||
"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:"
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
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,
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,180 +0,0 @@
|
||||
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;
|
||||
});
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
/**
|
||||
* 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}`;
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
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}`;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user