Compare commits

..
Author SHA1 Message Date
Julius Marminge 31fe69e107 Add no-op dummy note to AGENTS docs
- Document a placeholder dummy change section in `AGENTS.md`
- Clarify it is a no-op edit
2026-03-02 19:33:09 -08:00
83 changed files with 1700 additions and 6400 deletions

No files matched your search

+38 -59
View File
@@ -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
+5 -6
View File
@@ -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)
@@ -50,3 +45,7 @@ Docs:
- Codex-Monitor (Tauri, feature-complete, strong reference implementation): https://github.com/Dimillian/CodexMonitor
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
## Dummy Change
- This line is a no-op dummy edit.
+7 -9
View File
@@ -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": "^24.10.13",
"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)"
+27 -164
View File
@@ -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);
});
+2 -2
View File
@@ -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,
});
+65 -613
View File
@@ -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,18 @@ 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 = "";
@@ -71,133 +39,8 @@ 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 +64,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,28 +84,6 @@ 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;
@@ -287,13 +96,13 @@ function normalizeCommitHash(value: unknown): string | null {
}
function resolveEmbeddedCommitHash(): string | null {
const packageJsonPath = Path.join(resolveAppRoot(), "package.json");
if (!FS.existsSync(packageJsonPath)) {
const packageJsonPath = path.join(resolveAppRoot(), "package.json");
if (!fs.existsSync(packageJsonPath)) {
return null;
}
try {
const raw = FS.readFileSync(packageJsonPath, "utf8");
const raw = fs.readFileSync(packageJsonPath, "utf8");
const parsed = JSON.parse(raw) as { t3codeCommitHash?: unknown };
return normalizeCommitHash(parsed.t3codeCommitHash);
} catch {
@@ -324,25 +133,25 @@ function resolveAboutCommitHash(): string | null {
}
function resolveBackendEntry(): string {
return Path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
return path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
}
function resolveBackendCwd(): string {
if (!app.isPackaged) {
return resolveAppRoot();
}
return OS.homedir();
return os.homedir();
}
function resolveDesktopStaticDir(): string | null {
const appRoot = resolveAppRoot();
const candidates = [
Path.join(appRoot, "apps/server/dist/client"),
Path.join(appRoot, "apps/web/dist"),
path.join(appRoot, "apps/server/dist/client"),
path.join(appRoot, "apps/web/dist"),
];
for (const candidate of candidates) {
if (FS.existsSync(Path.join(candidate, "index.html"))) {
if (fs.existsSync(path.join(candidate, "index.html"))) {
return candidate;
}
}
@@ -353,50 +162,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 +201,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 +256,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 +264,6 @@ function configureApplicationMenu(): void {
label: app.name,
submenu: [
{ role: "about" },
{
label: "Check for Updates...",
click: () => handleCheckForUpdatesMenuClick(),
},
{ type: "separator" },
{
label: "Settings...",
accelerator: "CmdOrCtrl+,",
@@ -538,15 +301,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 +308,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;
}
}
@@ -593,200 +347,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 +393,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 +406,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 +418,6 @@ function startBackend(): void {
if (backendProcess === child) {
backendProcess = null;
}
closeBackendSession(`pid=${child.pid ?? "unknown"} error=${error.message}`);
scheduleBackendRestart(error.message);
});
@@ -860,9 +425,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 +451,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 () => {
@@ -1050,36 +561,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 +583,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 +597,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 +621,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 +659,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();
});
}
-18
View File
@@ -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);
-74
View File
@@ -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);
});
});
-130
View File
@@ -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();
});
});
-155
View File
@@ -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,
};
}
-142
View File
@@ -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);
});
});
-48
View File
@@ -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;
}
+1 -1
View File
@@ -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
View File
@@ -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": "^24.10.13",
"@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"
}
}
+19
View File
@@ -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");
-170
View File
@@ -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,
);
+2 -20
View File
@@ -1,4 +1,4 @@
import { type ChildProcessWithoutNullStreams, spawn, spawnSync } from "node:child_process";
import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
import { randomUUID } from "node:crypto";
import { EventEmitter } from "node:events";
import readline from "node:readline";
@@ -104,23 +104,6 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
"does not exist",
];
/**
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
* entire process tree instead.
*/
function killChildTree(child: ChildProcessWithoutNullStreams): void {
if (process.platform === "win32" && child.pid !== undefined) {
try {
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
return;
} catch {
// fallback to direct kill
}
}
child.kill();
}
export function normalizeCodexModelSlug(
model: string | undefined | null,
preferredId?: string,
@@ -202,7 +185,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
},
stdio: ["pipe", "pipe", "pipe"],
shell: process.platform === "win32",
});
const output = readline.createInterface({ input: child.stdout });
@@ -493,7 +475,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
context.output.close();
if (!context.child.killed) {
killChildTree(context.child);
context.child.kill();
}
this.updateSession(context, {
+65 -2
View File
@@ -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");
}),
),
);
@@ -3,8 +3,6 @@ import { randomUUID } from "node:crypto";
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { TextGenerationError } from "../Errors.ts";
@@ -95,6 +93,24 @@ 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;
@@ -224,7 +240,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {
],
{
cwd,
shell: process.platform === "win32",
stdin: {
stream: Stream.make(new TextEncoder().encode(prompt)),
},
@@ -313,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)"}`,
@@ -337,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,
),
);
@@ -411,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)`,
@@ -452,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;
});
-15
View File
@@ -1172,20 +1172,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 +1188,6 @@ const makeGitCore = Effect.gen(function* () {
createBranch,
checkoutBranch,
initRepo,
listLocalBranchNames,
} satisfies GitCoreShape;
});
+3 -134
View File
@@ -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(
+22 -140
View File
@@ -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,
-5
View File
@@ -157,11 +157,6 @@ export interface GitCoreShape {
* Initialize a repository in the provided directory.
*/
readonly initRepo: (input: GitInitInput) => Effect.Effect<void, GitCommandError>;
/**
* List local branch names (short format).
*/
readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
}
/**
@@ -29,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 {
+1 -1
View File
@@ -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),
+1 -5
View File
@@ -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, {
+1 -3
View File
@@ -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)),
);
+19 -28
View File
@@ -224,37 +224,28 @@ export const resolveEditorLaunch = Effect.fnUntraced(function* (
});
export const launchDetached = (launch: EditorLaunch) =>
Effect.gen(function* () {
if (!isCommandAvailable(launch.command)) {
return yield* 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 })),
);
}
yield* Effect.callback<void, OpenError>((resume) => {
let child;
try {
child = spawn(launch.command, [...launch.args], {
detached: true,
stdio: "ignore",
shell: process.platform === "win32",
});
} catch (error) {
return resume(
Effect.fail(
new OpenError({ message: "failed to spawn detached process", cause: error }),
),
);
}
const handleSpawn = () => {
child.unref();
resume(Effect.void);
};
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 }))),
);
});
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* () {
+4 -32
View File
@@ -1,4 +1,4 @@
import { type ChildProcess as ChildProcessHandle, spawn, spawnSync } from "node:child_process";
import { spawn } from "node:child_process";
export interface ProcessRunOptions {
cwd?: string | undefined;
@@ -37,21 +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): boolean {
if (process.platform !== "win32") return false;
if (code === 9009) return true;
return /is not recognized as an internal or external command/i.test(stderr);
}
function normalizeExitError(
command: string,
args: readonly string[],
result: ProcessRunResult,
): Error {
if (isWindowsCommandNotFound(result.code, result.stderr)) {
return new Error(`Command not found: ${command}`);
}
const reason = result.timedOut
? "timed out"
: `failed (code=${result.code ?? "null"}, signal=${result.signal ?? "null"})`;
@@ -80,23 +70,6 @@ function normalizeBufferError(
const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
/**
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
* entire process tree instead.
*/
function killChild(child: ChildProcessHandle, signal: NodeJS.Signals = "SIGTERM"): void {
if (process.platform === "win32" && child.pid !== undefined) {
try {
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
return;
} catch {
// fallback to direct kill
}
}
child.kill(signal);
}
function appendChunkWithinLimit(
target: string,
currentBytes: number,
@@ -139,7 +112,6 @@ export async function runProcess(
cwd: options.cwd,
env: options.env,
stdio: "pipe",
shell: process.platform === "win32",
});
let stdout = "";
@@ -154,9 +126,9 @@ export async function runProcess(
const timeoutTimer = setTimeout(() => {
timedOut = true;
killChild(child, "SIGTERM");
child.kill("SIGTERM");
forceKillTimer = setTimeout(() => {
killChild(child, "SIGKILL");
child.kill("SIGKILL");
}, 1_000);
}, timeoutMs);
@@ -171,7 +143,7 @@ export async function runProcess(
};
const fail = (error: Error): void => {
killChild(child, "SIGTERM");
child.kill("SIGTERM");
finalize(() => {
reject(error);
});
@@ -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),
),
);
+15 -38
View File
@@ -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,11 +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 { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const PROVIDER = "codex" as const;
@@ -40,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 {
@@ -432,14 +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 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(() => {
@@ -501,11 +495,9 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
new Error(`Invalid attachment id '${attachment.id}'.`),
);
}
const bytes = yield* fileSystem
.readFile(attachmentPath)
.pipe(
Effect.mapError((cause) => toRequestError(input.sessionId, "turn/start", cause)),
);
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
Effect.mapError((cause) => toRequestError(input.sessionId, "turn/start", cause)),
);
return {
type: "image" as const,
url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`,
@@ -587,29 +579,14 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
yield* Effect.acquireRelease(
Effect.gen(function* () {
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);
Effect.sync(() => {
const listener = (event: ProviderEvent) => {
nativeEventLogger?.write({
observedAt: new Date().toISOString(),
event,
});
const services = yield* Effect.services<never>();
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,190 +0,0 @@
import assert from "node:assert/strict";
import { it } from "@effect/vitest";
import { Effect, Layer, Sink, Stream } from "effect";
import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import { checkCodexProviderStatus, parseAuthStatusFromOutput } from "./ProviderHealth";
// ── Test helpers ────────────────────────────────────────────────────
const encoder = new TextEncoder();
function mockHandle(result: { stdout: string; stderr: string; code: number }) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
stdin: Sink.drain,
stdout: Stream.make(encoder.encode(result.stdout)),
stderr: Stream.make(encoder.encode(result.stderr)),
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
}
function mockSpawnerLayer(
handler: (args: ReadonlyArray<string>) => { stdout: string; stderr: string; code: number },
) {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const cmd = command as unknown as { args: ReadonlyArray<string> };
return Effect.succeed(mockHandle(handler(cmd.args)));
}),
);
}
function failingSpawnerLayer(description: string) {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.fail(
PlatformError.systemError({
_tag: "NotFound",
module: "ChildProcess",
method: "spawn",
description,
}),
),
),
);
}
// ── Tests ───────────────────────────────────────────────────────────
it.effect("returns ready when codex is installed and authenticated", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unavailable when codex is missing", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.message, "Codex CLI (`codex`) is not installed or not on PATH.");
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
);
it.effect("returns unauthenticated when auth probe reports login required", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") {
return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect(
"returns unauthenticated when login status output includes 'not logged in'",
() =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status")
return { stdout: "Not logged in\n", stderr: "", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns warning when login status command is unsupported", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI authentication status command is unavailable in this Codex version.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") {
return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
// ── 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,303 +0,0 @@
/**
* ProviderHealthLive - Startup-time provider health checks.
*
* Performs one-time provider readiness probes when the server starts and
* keeps the resulting snapshot in memory for `server.getConfig`.
*
* Uses effect's ChildProcessSpawner to run CLI probes natively.
*
* @module ProviderHealthLive
*/
import type {
ServerProviderAuthStatus,
ServerProviderStatus,
ServerProviderStatusState,
} from "@t3tools/contracts";
import { Effect, Layer, Option, Result, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { ProviderHealth, type ProviderHealthShape } from "../Services/ProviderHealth";
const DEFAULT_TIMEOUT_MS = 4_000;
const CODEX_PROVIDER = "codex" as const;
// ── Pure helpers ────────────────────────────────────────────────────
export interface CommandResult {
readonly stdout: string;
readonly stderr: string;
readonly code: number;
}
function nonEmptyTrimmed(value: string | undefined): string | undefined {
if (!value) return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
function isCommandMissingCause(error: unknown): boolean {
if (!(error instanceof Error)) return false;
const lower = error.message.toLowerCase();
return (
lower.includes("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 !== 0) {
return `Command exited with code ${result.code}.`;
}
return undefined;
}
function extractAuthBoolean(value: unknown): boolean | undefined {
if (Array.isArray(value)) {
for (const entry of value) {
const nested = extractAuthBoolean(entry);
if (nested !== undefined) return nested;
}
return undefined;
}
if (!value || typeof value !== "object") return undefined;
const record = value as Record<string, unknown>;
for (const key of ["authenticated", "isAuthenticated", "loggedIn", "isLoggedIn"] as const) {
if (typeof record[key] === "boolean") return record[key];
}
for (const key of ["auth", "status", "session", "account"] as const) {
const nested = extractAuthBoolean(record[key]);
if (nested !== undefined) return nested;
}
return undefined;
}
export function parseAuthStatusFromOutput(result: CommandResult): {
readonly status: ServerProviderStatusState;
readonly authStatus: ServerProviderAuthStatus;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
if (
lowerOutput.includes("unknown command") ||
lowerOutput.includes("unrecognized command") ||
lowerOutput.includes("unexpected argument")
) {
return {
status: "warning",
authStatus: "unknown",
message: "Codex CLI authentication status command is unavailable in this Codex version.",
};
}
if (
lowerOutput.includes("not logged in") ||
lowerOutput.includes("login required") ||
lowerOutput.includes("authentication required") ||
lowerOutput.includes("run `codex login`") ||
lowerOutput.includes("run codex login")
) {
return {
status: "error",
authStatus: "unauthenticated",
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
const parsedAuth = (() => {
const trimmed = result.stdout.trim();
if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
try {
return {
attemptedJsonParse: true as const,
auth: extractAuthBoolean(JSON.parse(trimmed)),
};
} catch {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
})();
if (parsedAuth.auth === true) {
return { status: "ready", authStatus: "authenticated" };
}
if (parsedAuth.auth === false) {
return {
status: "error",
authStatus: "unauthenticated",
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
authStatus: "unknown",
message:
"Could not verify Codex authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", authStatus: "authenticated" };
}
const detail = detailFromResult(result);
return {
status: "warning",
authStatus: "unknown",
message: detail
? `Could not verify Codex authentication status. ${detail}`
: "Could not verify Codex authentication status.",
};
}
// ── Effect-native command execution ─────────────────────────────────
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
Stream.runFold(
stream,
() => "",
(acc, chunk) => acc + new TextDecoder().decode(chunk),
);
const runCodexCommand = (args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const command = ChildProcess.make("codex", [...args], {
shell: process.platform === "win32",
});
const child = yield* spawner.spawn(command);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectStreamAsString(child.stdout),
collectStreamAsString(child.stderr),
child.exitCode.pipe(Effect.map(Number)),
],
{ concurrency: "unbounded" },
);
return { stdout, stderr, code: exitCode } satisfies CommandResult;
}).pipe(Effect.scoped);
// ── Health check ────────────────────────────────────────────────────
export const checkCodexProviderStatus: Effect.Effect<
ServerProviderStatus,
never,
ChildProcessSpawner.ChildProcessSpawner
> = Effect.gen(function* () {
const checkedAt = new Date().toISOString();
// Probe 1: `codex --version` — is the CLI reachable?
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return {
provider: CODEX_PROVIDER,
status: "error" as const,
available: false,
authStatus: "unknown" as const,
checkedAt,
message: isCommandMissingCause(error)
? "Codex CLI (`codex`) is not installed or not on PATH."
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
};
}
if (Option.isNone(versionProbe.success)) {
return {
provider: CODEX_PROVIDER,
status: "error" as const,
available: false,
authStatus: "unknown" as const,
checkedAt,
message: "Codex CLI is installed but failed to run. Timed out while running command.",
};
}
const version = versionProbe.success.value;
if (version.code !== 0) {
const detail = detailFromResult(version);
return {
provider: CODEX_PROVIDER,
status: "error" as const,
available: false,
authStatus: "unknown" as const,
checkedAt,
message: detail
? `Codex CLI is installed but failed to run. ${detail}`
: "Codex CLI is installed but failed to run.",
};
}
// Probe 2: `codex login status` — is the user authenticated?
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return {
provider: CODEX_PROVIDER,
status: "warning" as const,
available: true,
authStatus: "unknown" as const,
checkedAt,
message:
error instanceof Error
? `Could not verify Codex authentication status: ${error.message}.`
: "Could not verify Codex authentication status.",
};
}
if (Option.isNone(authProbe.success)) {
return {
provider: CODEX_PROVIDER,
status: "warning" as const,
available: true,
authStatus: "unknown" as const,
checkedAt,
message: "Could not verify Codex authentication status. Timed out while running command.",
};
}
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
return {
provider: CODEX_PROVIDER,
status: parsed.status,
available: true,
authStatus: parsed.authStatus,
checkedAt,
...(parsed.message ? { message: parsed.message } : {}),
} satisfies ServerProviderStatus;
});
// ── 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",
) {}
+8 -23
View File
@@ -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";
@@ -42,27 +41,17 @@ export function makeServerProviderLayer(): Layer.Layer<
> {
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(
+1 -31
View File
@@ -25,7 +25,6 @@ import {
WS_METHODS,
type WebSocketResponse,
type ProviderRuntimeEvent,
type ServerProviderStatus,
type KeybindingsConfig,
type ResolvedKeybindingsConfig,
type WsPush,
@@ -44,7 +43,6 @@ 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";
@@ -71,20 +69,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),
};
class MockTerminalManager implements TerminalManagerShape {
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
private readonly listeners = new Set<(event: TerminalEvent) => void>();
@@ -393,7 +377,6 @@ describe("WebSocket Server", () => {
stateDir?: string;
staticDir?: string;
providerLayer?: Layer.Layer<ProviderService, never>;
providerHealth?: ProviderHealthShape;
open?: OpenShape;
gitManager?: GitManagerShape;
gitCore?: Pick<
@@ -411,10 +394,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",
@@ -449,7 +428,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),
@@ -758,7 +736,6 @@ describe("WebSocket Server", () => {
keybindingsConfigPath: keybindingsPath,
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
issues: [],
providers: defaultProviderStatuses,
availableEditors: expect.any(Array),
});
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
@@ -784,7 +761,6 @@ describe("WebSocket Server", () => {
keybindingsConfigPath: keybindingsPath,
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
issues: [],
providers: defaultProviderStatuses,
availableEditors: expect.any(Array),
});
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
@@ -820,7 +796,6 @@ describe("WebSocket Server", () => {
message: expect.stringContaining("expected JSON array"),
},
],
providers: defaultProviderStatuses,
availableEditors: expect.any(Array),
});
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
@@ -855,7 +830,6 @@ describe("WebSocket Server", () => {
keybindingsConfigPath: string;
keybindings: ResolvedKeybindingsConfig;
issues: Array<{ kind: string; index?: number; message: string }>;
providers: ReadonlyArray<ServerProviderStatus>;
availableEditors: unknown;
};
expect(result.cwd).toBe("/my/workspace");
@@ -875,7 +849,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);
});
@@ -904,7 +877,6 @@ describe("WebSocket Server", () => {
);
expect(malformedPush.data).toEqual({
issues: [{ kind: "keybindings.malformed-config", message: expect.any(String) }],
providers: defaultProviderStatuses,
});
fs.writeFileSync(keybindingsPath, "[]", "utf8");
@@ -915,7 +887,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 () => {
@@ -975,7 +947,6 @@ describe("WebSocket Server", () => {
keybindingsConfigPath: keybindingsPath,
keybindings: compileKeybindings(persistedConfig),
issues: [],
providers: defaultProviderStatuses,
availableEditors: expect.any(Array),
});
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
@@ -1023,7 +994,6 @@ describe("WebSocket Server", () => {
keybindingsConfigPath: keybindingsPath,
keybindings: compileKeybindings(persistedConfig),
issues: [],
providers: defaultProviderStatuses,
availableEditors: expect.any(Array),
});
expectAvailableEditors(
+2 -11
View File
@@ -52,7 +52,6 @@ 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";
@@ -155,8 +154,7 @@ export type ServerCoreRuntimeServices =
| ProjectionSnapshotQuery
| CheckpointDiffQuery
| OrchestrationReactor
| ProviderService
| ProviderHealth;
| ProviderService;
export type ServerRuntimeServices =
| ServerCoreRuntimeServices
@@ -200,7 +198,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
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;
@@ -215,8 +212,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");
@@ -542,10 +537,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));
@@ -743,7 +735,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
keybindingsConfigPath,
keybindings: keybindingsConfig.keybindings,
issues: keybindingsConfig.issues,
providers: providerStatuses,
availableEditors,
};
+1 -1
View File
@@ -21,5 +21,5 @@
}
]
},
"include": ["src", "tsdown.config.ts", "scripts", "integration", "../../scripts/lib"]
"include": ["src", "tsdown.config.ts", "scripts", "integration"]
}
+1 -4
View File
@@ -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",
+3 -6
View File
@@ -1,12 +1,11 @@
{
"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"
@@ -16,7 +15,6 @@
"@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,8 +41,7 @@
"@vitejs/plugin-react": "^5.1.4",
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
"tailwindcss": "^4.0.0",
"typescript": "catalog:",
"vite": "^8.0.0-beta.12",
"vitest": "catalog:"
"typescript": "^5.7.3",
"vite": "^8.0.0-beta.12"
}
}
+1 -15
View File
@@ -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"]);
});
});
-18
View File
@@ -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();
@@ -3,77 +3,8 @@ import { describe, expect, it } from "vitest";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
resolveDraftEnvModeAfterBranchChange,
resolveBranchToolbarValue,
} from "./BranchToolbar.logic";
describe("resolveDraftEnvModeAfterBranchChange", () => {
it("switches to local mode when returning from an existing worktree to the main worktree", () => {
expect(
resolveDraftEnvModeAfterBranchChange({
nextWorktreePath: null,
currentWorktreePath: "/repo/.t3/worktrees/feature-a",
effectiveEnvMode: "worktree",
}),
).toBe("local");
});
it("keeps new-worktree mode when selecting a base branch before worktree creation", () => {
expect(
resolveDraftEnvModeAfterBranchChange({
nextWorktreePath: null,
currentWorktreePath: null,
effectiveEnvMode: "worktree",
}),
).toBe("worktree");
});
it("uses worktree mode when selecting a branch already attached to a worktree", () => {
expect(
resolveDraftEnvModeAfterBranchChange({
nextWorktreePath: "/repo/.t3/worktrees/feature-a",
currentWorktreePath: null,
effectiveEnvMode: "local",
}),
).toBe("worktree");
});
});
describe("resolveBranchToolbarValue", () => {
it("defaults new-worktree mode to current git branch when no explicit base branch is set", () => {
expect(
resolveBranchToolbarValue({
envMode: "worktree",
activeWorktreePath: null,
activeThreadBranch: null,
currentGitBranch: "main",
}),
).toBe("main");
});
it("keeps an explicitly selected worktree base branch", () => {
expect(
resolveBranchToolbarValue({
envMode: "worktree",
activeWorktreePath: null,
activeThreadBranch: "feature/base",
currentGitBranch: "main",
}),
).toBe("feature/base");
});
it("shows the actual checked-out branch when not selecting a new worktree base", () => {
expect(
resolveBranchToolbarValue({
envMode: "local",
activeWorktreePath: null,
activeThreadBranch: "feature/base",
currentGitBranch: "main",
}),
).toBe("main");
});
});
describe("deriveLocalBranchNameFromRemoteRef", () => {
it("strips the remote prefix from a remote ref", () => {
expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo");
@@ -1,46 +1,5 @@
import type { GitBranch } from "@t3tools/contracts";
export type EnvMode = "local" | "worktree";
export function resolveEffectiveEnvMode(input: {
activeWorktreePath: string | null;
hasServerThread: boolean;
draftThreadEnvMode: EnvMode | undefined;
}): EnvMode {
const { activeWorktreePath, hasServerThread, draftThreadEnvMode } = input;
return activeWorktreePath || (!hasServerThread && draftThreadEnvMode === "worktree")
? "worktree"
: "local";
}
export function resolveDraftEnvModeAfterBranchChange(input: {
nextWorktreePath: string | null;
currentWorktreePath: string | null;
effectiveEnvMode: EnvMode;
}): EnvMode {
const { nextWorktreePath, currentWorktreePath, effectiveEnvMode } = input;
if (nextWorktreePath) {
return "worktree";
}
if (effectiveEnvMode === "worktree" && !currentWorktreePath) {
return "worktree";
}
return "local";
}
export function resolveBranchToolbarValue(input: {
envMode: EnvMode;
activeWorktreePath: string | null;
activeThreadBranch: string | null;
currentGitBranch: string | null;
}): string | null {
const { envMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
if (envMode === "worktree" && !activeWorktreePath) {
return activeThreadBranch ?? currentGitBranch;
}
return currentGitBranch ?? activeThreadBranch;
}
export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
const firstSeparatorIndex = branchName.indexOf("/");
if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
+287 -69
View File
@@ -1,27 +1,40 @@
import type { ThreadId } from "@t3tools/contracts";
import { useCallback } from "react";
import type { GitBranch, ThreadId } from "@t3tools/contracts";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useOptimistic, useState, useTransition } from "react";
import { newCommandId } from "../lib/utils";
import { gitBranchesQueryOptions, invalidateGitQueries } from "../lib/gitReactQuery";
import { readNativeApi } from "../nativeApi";
import { useComposerDraftStore } from "../composerDraftStore";
import { useStore } from "../store";
import {
EnvMode,
resolveDraftEnvModeAfterBranchChange,
resolveEffectiveEnvMode,
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
} from "./BranchToolbar.logic";
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
import { Button } from "./ui/button";
import {
Combobox,
ComboboxEmpty,
ComboboxInput,
ComboboxItem,
ComboboxList,
ComboboxPopup,
ComboboxTrigger,
} from "./ui/combobox";
import { ChevronDownIcon } from "lucide-react";
import { toastManager } from "./ui/toast";
interface BranchToolbarProps {
threadId: ThreadId;
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 +42,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 +58,184 @@ 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 currentGitBranch = branches.find((branch) => branch.current)?.name ?? null;
const canonicalActiveBranch =
effectiveEnvMode === "worktree" && !activeWorktreePath
? activeThreadBranch
: (currentGitBranch ?? activeThreadBranch);
const branchNames = branches.map((branch) => branch.name);
const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
const trimmedBranchQuery = branchQuery.trim();
const canCreateBranch = effectiveEnvMode === "local" && trimmedBranchQuery.length > 0;
const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
const createBranchItemValue = canCreateBranch
? `__create_new_branch__:${trimmedBranchQuery}`
: null;
const branchPickerItems =
createBranchItemValue && !hasExactBranchMatch
? [...branchNames, createBranchItemValue]
: branchNames;
// ── Helpers ───────────────────────────────────────────────────────────
const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
canonicalActiveBranch,
(_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
);
const [isBranchActionPending, startBranchActionTransition] = useTransition();
const runBranchAction = (action: () => Promise<void>) => {
startBranchActionTransition(async () => {
await action().catch(() => undefined);
await invalidateGitQueries(queryClient).catch(() => undefined);
});
};
const setThreadError = (error: string | null) => {
if (!activeThreadId) return;
setThreadErrorAction(activeThreadId, error);
};
const setThreadBranch = (branch: string | null, worktreePath: string | null) => {
if (!activeThreadId) return;
const api = readNativeApi();
// If the effective cwd is about to change, stop the running session so the
// next message creates a new one with the correct cwd.
const sessionId = serverThread?.session?.sessionId;
if (sessionId && worktreePath !== activeWorktreePath && api) {
void api.orchestration
.dispatchCommand({
type: "thread.session.stop",
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 || isBranchActionPending) return;
// For new worktree mode, selecting a branch picks the base branch.
if (effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath) {
setThreadBranch(branch.name, null);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
return;
}
// If the branch already lives in a worktree, redirect there instead of
// trying to checkout (which git would reject with "already used by worktree").
if (branch.worktreePath) {
const isMainWorktree = branch.worktreePath === activeProject?.cwd;
// Main worktree → switch back to local (project cwd, worktreePath=null).
// Secondary worktree → point the thread at that worktree path.
setThreadBranch(branch.name, isMainWorktree ? null : branch.worktreePath);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
return;
}
const selectedBranchName = branch.isRemote
? deriveLocalBranchNameFromRemoteRef(branch.name)
: branch.name;
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
runBranchAction(async () => {
setOptimisticBranch(selectedBranchName);
try {
await api.git.checkout({ cwd: branchCwd, branch: branch.name });
await invalidateGitQueries(queryClient);
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to checkout branch.",
description: error instanceof Error ? error.message : "An error occurred.",
});
return;
}
let nextBranchName = selectedBranchName;
if (branch.isRemote) {
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
if (status?.branch) {
nextBranchName = status.branch;
}
}
setOptimisticBranch(nextBranchName);
setThreadBranch(nextBranchName, activeWorktreePath);
});
};
const createBranch = (rawName: string) => {
const name = rawName.trim();
const api = readNativeApi();
if (!api || !activeThreadId || !branchCwd || !name || isBranchActionPending) return;
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
runBranchAction(async () => {
setOptimisticBranch(name);
try {
await api.git.createBranch({ cwd: branchCwd, branch: name });
try {
await api.git.checkout({ cwd: branchCwd, branch: name });
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to checkout branch.",
description: error instanceof Error ? error.message : "An error occurred.",
});
return;
}
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to create branch.",
description: error instanceof Error ? error.message : "An error occurred.",
});
return;
}
setOptimisticBranch(name);
setThreadBranch(name, activeWorktreePath);
setBranchQuery("");
});
};
if (!activeThreadId || !activeProject) return null;
@@ -121,16 +259,96 @@ export default function BranchToolbar({
)}
</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("");
else void invalidateGitQueries(queryClient);
}}
open={isBranchMenuOpen}
value={resolvedActiveBranch}
>
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
className="text-muted-foreground/70 hover:text-foreground/80"
disabled={branchesQuery.isLoading || isBranchActionPending}
>
<span className="max-w-[240px] truncate">
{resolvedActiveBranch
? effectiveEnvMode === "worktree" && !activeWorktreePath
? `From ${resolvedActiveBranch}`
: resolvedActiveBranch
: "Select branch"}
</span>
<ChevronDownIcon />
</ComboboxTrigger>
<ComboboxPopup align="end" side="top" className="w-64">
<div className="border-b p-1">
<ComboboxInput
className="[&_input]:font-sans rounded-md"
inputClassName="ring-0"
placeholder="Search branches..."
showTrigger={false}
size="sm"
value={branchQuery}
onChange={(event) => setBranchQuery(event.target.value)}
/>
</div>
<ComboboxEmpty>No branches found.</ComboboxEmpty>
<ComboboxList className="max-h-56">
{(itemValue) => {
if (createBranchItemValue && itemValue === createBranchItemValue) {
return (
<ComboboxItem
hideIndicator
key={itemValue}
value={itemValue}
onClick={() => createBranch(trimmedBranchQuery)}
>
<span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
</ComboboxItem>
);
}
const branch = branchByName.get(itemValue);
if (!branch) return null;
const hasSecondaryWorktree =
branch.worktreePath && branch.worktreePath !== activeProject.cwd;
const badge = branch.current
? "current"
: hasSecondaryWorktree
? "worktree"
: branch.isRemote
? "remote"
: branch.isDefault
? "default"
: null;
return (
<ComboboxItem
hideIndicator
key={itemValue}
value={itemValue}
className={
itemValue === resolvedActiveBranch ? "bg-accent text-foreground" : undefined
}
onClick={() => selectBranch(branch)}
>
<div className="flex w-full items-center justify-between gap-2">
<span className="truncate">{itemValue}</span>
{badge && (
<span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>
)}
</div>
</ComboboxItem>
);
}}
</ComboboxList>
</ComboboxPopup>
</Combobox>
</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>
);
}
+106 -285
View File
@@ -15,7 +15,6 @@ import {
type ReasoningEffort,
type ResolvedKeybindingsConfig,
type ProviderApprovalDecision,
type ServerProviderStatus,
type ThreadId,
type TurnId,
normalizeModelSlug,
@@ -63,18 +62,11 @@ import {
MAX_THREAD_TERMINAL_COUNT,
type ChatMessage,
type Thread,
type TurnDiffFileChange,
type TurnDiffSummary,
} from "../types";
import { basenameOfPath, getVscodeIconUrlForEntry } from "../vscode-icons";
import { useTheme } from "../hooks/useTheme";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import {
buildTurnDiffTree,
normalizeFilePath,
summarizeTurnDiffStats,
type TurnDiffTreeNode,
} from "../lib/turnDiffTree";
import BranchToolbar from "./BranchToolbar";
import GitActionsControl from "./GitActionsControl";
import {
@@ -126,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,
@@ -156,7 +148,6 @@ 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;
@@ -340,7 +331,6 @@ const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
pathValue: string;
kind: "file" | "directory";
theme: "light" | "dark";
className?: string;
}) {
const [failedIconUrl, setFailedIconUrl] = useState<string | null>(null);
const iconUrl = useMemo(
@@ -351,9 +341,9 @@ const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
if (failed) {
return props.kind === "directory" ? (
<FolderIcon className={cn("size-4 text-muted-foreground/80", props.className)} />
<FolderIcon className="size-4 text-muted-foreground/80" />
) : (
<FileIcon className={cn("size-4 text-muted-foreground/80", props.className)} />
<FileIcon className="size-4 text-muted-foreground/80" />
);
}
@@ -362,7 +352,7 @@ const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
src={iconUrl}
alt=""
aria-hidden="true"
className={cn("size-4 shrink-0", props.className)}
className="size-4 shrink-0"
loading="lazy"
onError={() => setFailedIconUrl(iconUrl)}
/>
@@ -534,6 +524,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const pendingUserScrollUpIntentRef = useRef(false);
const pendingAutoScrollFrameRef = useRef<number | null>(null);
const composerEditorRef = useRef<ComposerPromptEditorHandle>(null);
const composerCommandInputRef = useRef<HTMLInputElement>(null);
const composerFormRef = useRef<HTMLFormElement>(null);
const composerFormHeightRef = useRef(0);
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
@@ -641,11 +632,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";
@@ -921,14 +907,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(
() =>
@@ -946,12 +944,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
const keybindings = serverConfigQuery.data?.keybindings ?? EMPTY_KEYBINDINGS;
const availableEditors = serverConfigQuery.data?.availableEditors ?? EMPTY_AVAILABLE_EDITORS;
const providerStatuses = serverConfigQuery.data?.providers ?? EMPTY_PROVIDER_STATUSES;
const activeProvider = activeThread?.session?.provider ?? "codex";
const activeProviderStatus = useMemo(
() => providerStatuses.find((status) => status.provider === activeProvider) ?? null,
[activeProvider, providerStatuses],
);
const activeProjectCwd = activeProject?.cwd ?? null;
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
const threadTerminalRuntimeEnv = useMemo(() => {
@@ -2328,9 +2320,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);
}
@@ -2373,27 +2368,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;
@@ -2513,7 +2499,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
</header>
{/* Error banner */}
<ProviderHealthBanner status={activeProviderStatus} />
<ThreadErrorBanner error={activeThread.error} />
<PendingApprovalsPanel
pendingApprovals={pendingApprovals}
@@ -2555,7 +2540,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
isRevertingCheckpoint={isRevertingCheckpoint}
onImageExpand={onExpandTimelineImage}
markdownCwd={gitCwd ?? undefined}
resolvedTheme={resolvedTheme}
/>
</div>
@@ -2802,6 +2786,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
{isGitRepo && (
<BranchToolbar
threadId={activeThread.id}
envMode={envMode}
onEnvModeChange={onEnvModeChange}
envLocked={envLocked}
onComposerFocusRequest={scheduleComposerFocus}
@@ -3015,35 +3000,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[];
@@ -3135,153 +3091,6 @@ const MessageCopyButton = memo(function MessageCopyButton({ text }: { text: stri
);
});
function hasNonZeroStat(stat: { additions: number; deletions: number }): boolean {
return stat.additions > 0 || stat.deletions > 0;
}
const DiffStatLabel = memo(function DiffStatLabel(props: {
additions: number;
deletions: number;
}) {
const { additions, deletions } = props;
return (
<>
<span className="text-success">+{additions}</span>
<span className="mx-0.5 text-muted-foreground/70">/</span>
<span className="text-destructive">-{deletions}</span>
</>
);
});
function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[] {
const paths: string[] = [];
for (const node of nodes) {
if (node.kind !== "directory") continue;
paths.push(node.path);
paths.push(...collectDirectoryPaths(node.children));
}
return paths;
}
function buildDirectoryExpansionState(
directoryPaths: ReadonlyArray<string>,
expanded: boolean,
): Record<string, boolean> {
const expandedState: Record<string, boolean> = {};
for (const directoryPath of directoryPaths) {
expandedState[directoryPath] = expanded;
}
return expandedState;
}
const ChangedFilesTree = memo(function ChangedFilesTree(props: {
turnId: TurnId;
files: ReadonlyArray<TurnDiffFileChange>;
allDirectoriesExpanded: boolean;
resolvedTheme: "light" | "dark";
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
}) {
const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, turnId } = props;
const treeNodes = useMemo(() => buildTurnDiffTree(files), [files]);
const directoryPathsKey = useMemo(() => collectDirectoryPaths(treeNodes).join("\u0000"), [treeNodes]);
const allDirectoryExpansionState = useMemo(
() =>
buildDirectoryExpansionState(
directoryPathsKey ? directoryPathsKey.split("\u0000") : [],
allDirectoriesExpanded,
),
[allDirectoriesExpanded, directoryPathsKey],
);
const [expandedDirectories, setExpandedDirectories] = useState<Record<string, boolean>>(
() => buildDirectoryExpansionState((directoryPathsKey ? directoryPathsKey.split("\u0000") : []), true),
);
useEffect(() => {
setExpandedDirectories(allDirectoryExpansionState);
}, [allDirectoryExpansionState]);
const toggleDirectory = useCallback((pathValue: string, fallbackExpanded: boolean) => {
setExpandedDirectories((current) => ({
...current,
[pathValue]: !(current[pathValue] ?? fallbackExpanded),
}));
}, []);
const renderTreeNode = (node: TurnDiffTreeNode, depth: number) => {
const leftPadding = 8 + depth * 14;
if (node.kind === "directory") {
const isExpanded = expandedDirectories[node.path] ?? depth === 0;
return (
<div key={`dir:${node.path}`}>
<button
type="button"
className="group flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left hover:bg-background/80"
style={{ paddingLeft: `${leftPadding}px` }}
onClick={() => toggleDirectory(node.path, depth === 0)}
>
<ChevronRightIcon
aria-hidden="true"
className={cn(
"size-3.5 shrink-0 text-muted-foreground/70 transition-transform group-hover:text-foreground/80",
isExpanded && "rotate-90",
)}
/>
{isExpanded ? (
<FolderIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
) : (
<FolderClosedIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
)}
<span className="truncate font-mono text-[11px] text-muted-foreground/90 group-hover:text-foreground/90">
{node.name}
</span>
{hasNonZeroStat(node.stat) && (
<span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
<DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
</span>
)}
</button>
{isExpanded && (
<div className="space-y-0.5">
{node.children.map((childNode) => renderTreeNode(childNode, depth + 1))}
</div>
)}
</div>
);
}
return (
<button
key={`file:${node.path}`}
type="button"
className="group flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left hover:bg-background/80"
style={{ paddingLeft: `${leftPadding}px` }}
onClick={() => onOpenTurnDiff(turnId, node.path)}
>
<span aria-hidden="true" className="size-3.5 shrink-0" />
<VscodeEntryIcon
pathValue={node.path}
kind="file"
theme={resolvedTheme}
className="size-3.5 text-muted-foreground/70"
/>
<span className="truncate font-mono text-[11px] text-muted-foreground/80 group-hover:text-foreground/90">
{node.name}
</span>
{node.stat && (
<span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
<DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
</span>
)}
</button>
);
};
return (
<div className="space-y-0.5">
{treeNodes.map((node) => renderTreeNode(node, 0))}
</div>
);
});
interface MessagesTimelineProps {
hasMessages: boolean;
isWorking: boolean;
@@ -3301,7 +3110,6 @@ interface MessagesTimelineProps {
isRevertingCheckpoint: boolean;
onImageExpand: (preview: ExpandedImagePreview) => void;
markdownCwd: string | undefined;
resolvedTheme: "light" | "dark";
}
type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
@@ -3356,7 +3164,6 @@ const MessagesTimeline = memo(function MessagesTimeline({
isRevertingCheckpoint,
onImageExpand,
markdownCwd,
resolvedTheme,
}: MessagesTimelineProps) {
const rows = useMemo<TimelineRow[]>(() => {
const nextRows: TimelineRow[] = [];
@@ -3497,15 +3304,6 @@ const MessagesTimeline = memo(function MessagesTimeline({
const virtualRows = rowVirtualizer.getVirtualItems();
const nonVirtualizedRows = rows.slice(virtualizedRowCount);
const [allDirectoriesExpandedByTurnId, setAllDirectoriesExpandedByTurnId] = useState<
Record<string, boolean>
>({});
const onToggleAllDirectories = useCallback((turnId: TurnId) => {
setAllDirectoriesExpandedByTurnId((current) => ({
...current,
[turnId]: !(current[turnId] ?? true),
}));
}, []);
const renderRowContent = (row: TimelineRow) => (
<div className="pb-4">
@@ -3674,58 +3472,81 @@ const MessagesTimeline = memo(function MessagesTimeline({
if (!turnSummary) return null;
const checkpointFiles = turnSummary.files;
if (checkpointFiles.length === 0) return null;
const summaryStat = summarizeTurnDiffStats(checkpointFiles);
const summaryStat = checkpointFiles.reduce(
(acc, file) => {
if (
typeof file.additions !== "number" ||
typeof file.deletions !== "number"
) {
return acc;
}
return {
additions: acc.additions + file.additions,
deletions: acc.deletions + file.deletions,
};
},
{ additions: 0, deletions: 0 },
);
const changedFileCountLabel = String(checkpointFiles.length);
const allDirectoriesExpanded =
allDirectoriesExpandedByTurnId[turnSummary.turnId] ?? true;
return (
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
<div className="mb-1.5 flex items-center justify-between gap-2">
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
<span>Changed files ({changedFileCountLabel})</span>
{hasNonZeroStat(summaryStat) && (
{(summaryStat.additions > 0 || summaryStat.deletions > 0) && (
<>
<span className="mx-1">•</span>
<DiffStatLabel
additions={summaryStat.additions}
deletions={summaryStat.deletions}
/>
<span className="text-success">+{summaryStat.additions}</span>
<span className="mx-0.5 text-muted-foreground/70">/</span>
<span className="text-destructive">-{summaryStat.deletions}</span>
</>
)}
</p>
<div className="flex items-center gap-1.5">
<Button
type="button"
size="xs"
variant="outline"
onClick={() => onToggleAllDirectories(turnSummary.turnId)}
>
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
</Button>
<Button
type="button"
size="xs"
variant="outline"
onClick={() => {
const rawPath = checkpointFiles[0]?.path;
onOpenTurnDiff(
turnSummary.turnId,
rawPath ? normalizeFilePath(rawPath) : undefined,
);
}}
>
View diff
</Button>
</div>
<Button
type="button"
size="xs"
variant="outline"
onClick={() =>
onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)
}
>
View diff
</Button>
</div>
<div className="flex flex-wrap gap-1.5">
{checkpointFiles.map((file) => (
<button
key={`${turnSummary.turnId}:${file.path}`}
type="button"
className="rounded-md border border-border/70 bg-background/70 px-2 py-1 font-mono text-[11px] text-muted-foreground/80 transition-colors hover:border-border hover:text-foreground/90"
onClick={() => onOpenTurnDiff(turnSummary.turnId, file.path)}
>
{(() => {
const stat =
typeof file.additions === "number" &&
typeof file.deletions === "number"
? {
additions: file.additions,
deletions: file.deletions,
}
: null;
if (!stat) {
return file.path;
}
return (
<>
<span>{file.path}</span>
<span className="ml-1 text-muted-foreground/70">(</span>
<span className="text-success">+{stat.additions}</span>
<span className="mx-0.5 text-muted-foreground/70">/</span>
<span className="text-destructive">-{stat.deletions}</span>
<span className="text-muted-foreground/70">)</span>
</>
);
})()}
</button>
))}
</div>
<ChangedFilesTree
key={`changed-files-tree:${turnSummary.turnId}`}
turnId={turnSummary.turnId}
files={checkpointFiles}
allDirectoriesExpanded={allDirectoriesExpanded}
resolvedTheme={resolvedTheme}
onOpenTurnDiff={onOpenTurnDiff}
/>
</div>
);
})()}
@@ -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}`;
}
+59 -17
View File
@@ -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(() => {
+3 -151
View File
@@ -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";
}
+20 -3
View File
@@ -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 () => {
-165
View File
@@ -1,165 +0,0 @@
import { describe, expect, it } from "vitest";
import { buildTurnDiffTree, summarizeTurnDiffStats } from "./turnDiffTree";
describe("summarizeTurnDiffStats", () => {
it("sums only files with numeric additions/deletions", () => {
const stat = summarizeTurnDiffStats([
{ path: "README.md", additions: 3, deletions: 1 },
{ path: "docs/notes.md" },
{ path: "src/index.ts", additions: 5, deletions: 2 },
]);
expect(stat).toEqual({ additions: 8, deletions: 3 });
});
});
describe("buildTurnDiffTree", () => {
it("builds nested directory nodes with aggregated stats", () => {
const tree = buildTurnDiffTree([
{ path: "src/index.ts", additions: 2, deletions: 1 },
{ path: "src/components/Button.tsx", additions: 4, deletions: 2 },
{ path: "README.md", additions: 1, deletions: 0 },
]);
expect(tree).toEqual([
{
kind: "directory",
name: "src",
path: "src",
stat: { additions: 6, deletions: 3 },
children: [
{
kind: "directory",
name: "components",
path: "src/components",
stat: { additions: 4, deletions: 2 },
children: [
{
kind: "file",
name: "Button.tsx",
path: "src/components/Button.tsx",
stat: { additions: 4, deletions: 2 },
},
],
},
{
kind: "file",
name: "index.ts",
path: "src/index.ts",
stat: { additions: 2, deletions: 1 },
},
],
},
{
kind: "file",
name: "README.md",
path: "README.md",
stat: { additions: 1, deletions: 0 },
},
]);
});
it("keeps files without stat values and excludes them from directory totals", () => {
const tree = buildTurnDiffTree([
{ path: "docs/notes.md" },
{ path: "docs/todo.md", additions: 1, deletions: 1 },
]);
expect(tree).toEqual([
{
kind: "directory",
name: "docs",
path: "docs",
stat: { additions: 1, deletions: 1 },
children: [
{
kind: "file",
name: "notes.md",
path: "docs/notes.md",
stat: null,
},
{
kind: "file",
name: "todo.md",
path: "docs/todo.md",
stat: { additions: 1, deletions: 1 },
},
],
},
]);
});
it("normalizes file paths with windows separators", () => {
const tree = buildTurnDiffTree([{ path: "apps\\web\\src\\index.ts", additions: 2, deletions: 1 }]);
expect(tree).toEqual([
{
kind: "directory",
name: "apps/web/src",
path: "apps/web/src",
stat: { additions: 2, deletions: 1 },
children: [
{
kind: "file",
name: "index.ts",
path: "apps/web/src/index.ts",
stat: { additions: 2, deletions: 1 },
},
],
},
]);
});
it("compacts only single-directory chains and stops at branch points", () => {
const tree = buildTurnDiffTree([
{ path: "apps/server/src/index.ts", additions: 2, deletions: 1 },
{ path: "apps/server/main.ts", additions: 4, deletions: 0 },
]);
expect(tree).toEqual([
{
kind: "directory",
name: "apps/server",
path: "apps/server",
stat: { additions: 6, deletions: 1 },
children: [
{
kind: "directory",
name: "src",
path: "apps/server/src",
stat: { additions: 2, deletions: 1 },
children: [
{
kind: "file",
name: "index.ts",
path: "apps/server/src/index.ts",
stat: { additions: 2, deletions: 1 },
},
],
},
{
kind: "file",
name: "main.ts",
path: "apps/server/main.ts",
stat: { additions: 4, deletions: 0 },
},
],
},
]);
});
it("preserves leading/trailing whitespace in path segments", () => {
const tree = buildTurnDiffTree([
{ path: "a/file.ts", additions: 1, deletions: 0 },
{ path: " a/file.ts", additions: 2, deletions: 0 },
]);
expect(tree).toHaveLength(2);
const directoryNodes = tree.filter(
(node): node is Extract<(typeof tree)[number], { kind: "directory" }> => node.kind === "directory",
);
expect(directoryNodes.map((node) => node.name).toSorted()).toEqual([" a", "a"]);
expect(directoryNodes.map((node) => node.path).toSorted()).toEqual([" a", "a"]);
});
});
-176
View File
@@ -1,176 +0,0 @@
import type { TurnDiffFileChange } from "../types";
export interface TurnDiffStat {
additions: number;
deletions: number;
}
export interface TurnDiffTreeDirectoryNode {
kind: "directory";
name: string;
path: string;
stat: TurnDiffStat;
children: TurnDiffTreeNode[];
}
export interface TurnDiffTreeFileNode {
kind: "file";
name: string;
path: string;
stat: TurnDiffStat | null;
}
export type TurnDiffTreeNode = TurnDiffTreeDirectoryNode | TurnDiffTreeFileNode;
interface MutableDirectoryNode {
name: string;
path: string;
stat: TurnDiffStat;
directories: Map<string, MutableDirectoryNode>;
files: TurnDiffTreeFileNode[];
}
const SORT_LOCALE_OPTIONS: Intl.CollatorOptions = { numeric: true, sensitivity: "base" };
function normalizePathSegments(pathValue: string): string[] {
return pathValue
.replaceAll("\\", "/")
.split("/")
.filter((segment) => segment.length > 0);
}
export function normalizeFilePath(pathValue: string): string {
return normalizePathSegments(pathValue).join("/");
}
function compareByName(a: { name: string }, b: { name: string }): number {
return a.name.localeCompare(b.name, undefined, SORT_LOCALE_OPTIONS);
}
function readStat(file: TurnDiffFileChange): TurnDiffStat | null {
if (typeof file.additions !== "number" || typeof file.deletions !== "number") {
return null;
}
return {
additions: file.additions,
deletions: file.deletions,
};
}
function compactDirectoryNode(node: TurnDiffTreeDirectoryNode): TurnDiffTreeDirectoryNode {
const compactedChildren = node.children.map((child) =>
child.kind === "directory" ? compactDirectoryNode(child) : child,
);
let compactedNode: TurnDiffTreeDirectoryNode = {
...node,
children: compactedChildren,
};
while (compactedNode.children.length === 1 && compactedNode.children[0]?.kind === "directory") {
const onlyChild = compactedNode.children[0];
compactedNode = {
kind: "directory",
name: `${compactedNode.name}/${onlyChild.name}`,
path: onlyChild.path,
stat: onlyChild.stat,
children: onlyChild.children,
};
}
return compactedNode;
}
function toTreeNodes(directory: MutableDirectoryNode): TurnDiffTreeNode[] {
const subdirectories: TurnDiffTreeDirectoryNode[] = Array.from(directory.directories.values())
.toSorted(compareByName)
.map<TurnDiffTreeDirectoryNode>((subdirectory) => ({
kind: "directory",
name: subdirectory.name,
path: subdirectory.path,
stat: {
additions: subdirectory.stat.additions,
deletions: subdirectory.stat.deletions,
},
children: toTreeNodes(subdirectory),
}))
.map((subdirectory) => compactDirectoryNode(subdirectory));
const files = directory.files.toSorted(compareByName);
return [...subdirectories, ...files];
}
export function summarizeTurnDiffStats(files: ReadonlyArray<TurnDiffFileChange>): TurnDiffStat {
return files.reduce(
(acc, file) => {
const stat = readStat(file);
if (!stat) return acc;
return {
additions: acc.additions + stat.additions,
deletions: acc.deletions + stat.deletions,
};
},
{ additions: 0, deletions: 0 },
);
}
export function buildTurnDiffTree(files: ReadonlyArray<TurnDiffFileChange>): TurnDiffTreeNode[] {
const root: MutableDirectoryNode = {
name: "",
path: "",
stat: { additions: 0, deletions: 0 },
directories: new Map(),
files: [],
};
for (const file of files) {
const segments = normalizePathSegments(file.path);
if (segments.length === 0) {
continue;
}
const filePath = segments.join("/");
const fileName = segments.at(-1);
if (!fileName) {
continue;
}
const stat = readStat(file);
const ancestors: MutableDirectoryNode[] = [root];
let currentDirectory = root;
for (const segment of segments.slice(0, -1)) {
const nextPath = currentDirectory.path ? `${currentDirectory.path}/${segment}` : segment;
const existing = currentDirectory.directories.get(segment);
if (existing) {
currentDirectory = existing;
} else {
const created: MutableDirectoryNode = {
name: segment,
path: nextPath,
stat: { additions: 0, deletions: 0 },
directories: new Map(),
files: [],
};
currentDirectory.directories.set(segment, created);
currentDirectory = created;
}
ancestors.push(currentDirectory);
}
currentDirectory.files.push({
kind: "file",
name: fileName,
path: filePath,
stat,
});
if (stat) {
for (const ancestor of ancestors) {
ancestor.stat.additions += stat.additions;
ancestor.stat.deletions += stat.deletions;
}
}
}
return toTreeNodes(root);
}
+1 -15
View File
@@ -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 },
);
});
});
+55 -91
View File
@@ -5,34 +5,35 @@
"": {
"name": "@t3tools/monorepo",
"devDependencies": {
"@types/node": "catalog:",
"@effect/platform-node": "catalog:",
"@types/node": "^24.10.13",
"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": "^24.10.13",
"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 +47,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": "^24.10.13",
"@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",
@@ -94,53 +93,21 @@
"@vitejs/plugin-react": "^5.1.4",
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
"tailwindcss": "^4.0.0",
"typescript": "catalog:",
"typescript": "^5.7.3",
"vite": "^8.0.0-beta.12",
"vitest": "catalog:",
},
},
"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",
},
},
},
@@ -149,12 +116,7 @@
"@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b",
"@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@8881a9b",
"@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@8881a9b",
"@types/bun": "^1.3.9",
"@types/node": "^24.10.13",
"effect": "https://pkg.pr.new/Effect-TS/effect-smol/effect@8881a9b",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
"vitest": "^4.0.0",
},
"packages": {
"@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.28.5", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw=="],
@@ -575,10 +537,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=="],
@@ -727,8 +685,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=="],
@@ -759,8 +715,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=="],
@@ -779,6 +733,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=="],
@@ -861,7 +817,7 @@
"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=="],
@@ -917,7 +873,7 @@
"form-data": ["[email protected]", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.2", "mime-types": "^2.1.12" } }, "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w=="],
"fs-extra": ["fs-extra@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]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
@@ -949,6 +905,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=="],
@@ -975,6 +933,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=="],
@@ -1021,8 +981,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=="],
@@ -1031,14 +989,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=="],
@@ -1071,12 +1027,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=="],
@@ -1181,6 +1135,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=="],
@@ -1249,6 +1205,8 @@
"picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],
"pify": ["[email protected]", "", {}, "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g=="],
"postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg=="],
"prettier": ["[email protected]", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg=="],
@@ -1301,12 +1259,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=="],
@@ -1323,9 +1285,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=="],
@@ -1375,6 +1337,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=="],
@@ -1389,8 +1353,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=="],
@@ -1461,7 +1423,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=="],
@@ -1485,6 +1449,8 @@
"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=="],
@@ -1543,8 +1509,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=="],
@@ -1593,6 +1557,8 @@
"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=="],
@@ -1603,16 +1569,14 @@
"serialize-error/type-fest": ["[email protected]", "", {}, "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg=="],
"unixify/normalize-path": ["[email protected]", "", { "dependencies": { "remove-trailing-separator": "^1.0.1" } }, "sha512-3pKJwH184Xo/lnH6oyP1q2pMd7HcypqqmRs91/6/i2CGtWwIKGCkOOMTm/zXbgTEWHw1uNpNi/igc3ePOYHb6w=="],
"vitest/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA=="],
"@babel/generator/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
"@babel/parser/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
"@electron/get/fs-extra/jsonfile": ["[email protected]", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="],
"@electron/get/fs-extra/universalify": ["[email protected]", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="],
"@tailwindcss/node/lightningcss/lightningcss-android-arm64": ["[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-BH9sEdOCahSgmkVhBLeU7Hc9DWeZ1Eb6wNS6Da8igvUwAe0sqROHddIlvU06q3WyXVEOYDZ6ykBZQnjTbmo4+A=="],
"@tailwindcss/node/lightningcss/lightningcss-darwin-arm64": ["[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-ylTcDJBN3Hp21TdhRT5zBOIi73P6/W0qwvlFEk22fkdXchtNTOU4Qc37SkzV+EKYxLouZ6M4LG9NfZ1qkhhBWA=="],
-20
View File
@@ -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
+11 -14
View File
@@ -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/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,11 +40,14 @@
"sync:vscode-icons": "node scripts/sync-vscode-icons.mjs"
},
"devDependencies": {
"@types/node": "catalog:",
"@effect/platform-node": "catalog:",
"@types/node": "^24.10.13",
"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",
+4 -5
View File
@@ -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"
}
}
-6
View File
@@ -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),
-33
View File
@@ -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 -27
View File
@@ -1,8 +1,7 @@
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,35 +25,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 ServerConfig = Schema.Struct({
cwd: TrimmedNonEmptyString,
keybindingsConfigPath: TrimmedNonEmptyString,
keybindings: ResolvedKeybindingsConfig,
issues: ServerConfigIssues,
providers: ServerProviderStatuses,
availableEditors: Schema.Array(EditorId),
});
export type ServerConfig = typeof ServerConfig.Type;
@@ -70,6 +45,5 @@ export type ServerUpsertKeybindingResult = typeof ServerUpsertKeybindingResult.T
export const ServerConfigUpdatedPayload = Schema.Struct({
issues: ServerConfigIssues,
providers: ServerProviderStatuses,
});
export type ServerConfigUpdatedPayload = typeof ServerConfigUpdatedPayload.Type;
-35
View File
@@ -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:"
}
}
-98
View File
@@ -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,
),
);
});
});
-180
View File
@@ -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;
});
}
-61
View File
@@ -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}`;
}
-115
View File
@@ -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}`;
}
}
-4
View File
@@ -1,4 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"include": ["src"]
}
+53 -95
View File
@@ -6,13 +6,11 @@ import rootPackageJson from "../package.json" with { type: "json" };
import desktopPackageJson from "../apps/desktop/package.json" with { type: "json" };
import serverPackageJson from "../apps/server/package.json" with { type: "json" };
import { resolveCatalogDependencies } from "./lib/resolve-catalog.ts";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Config, Data, Effect, FileSystem, Layer, Logger, Option, Path, Schema } from "effect";
import { Config, Data, Effect, FileSystem, Logger, Option, Path, Schema } from "effect";
import { Command, Flag } from "effect/unstable/cli";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { ChildProcess } from "effect/unstable/process";
const BuildPlatform = Schema.Literals(["mac", "linux", "win"]);
const BuildArch = Schema.Literals(["arm64", "x64", "universal"]);
@@ -23,7 +21,6 @@ const RepoRoot = Effect.service(Path.Path).pipe(
const IconSource = Effect.zipWith(RepoRoot, Effect.service(Path.Path), (repoRoot, path) =>
path.join(repoRoot, "assets/macos-icon-1024.png"),
);
const encodeJsonString = Schema.encodeEffect(Schema.UnknownFromJsonString);
interface PlatformConfig {
readonly cliFlag: "--mac" | "--linux" | "--win";
@@ -137,12 +134,14 @@ const AzureTrustedSigningOptionsConfig = Config.all({
endpoint: Config.string("AZURE_TRUSTED_SIGNING_ENDPOINT"),
certificateProfileName: Config.string("AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME"),
codeSigningAccountName: Config.string("AZURE_TRUSTED_SIGNING_ACCOUNT_NAME"),
fileDigest: Config.string("AZURE_TRUSTED_SIGNING_FILE_DIGEST").pipe(Config.withDefault("SHA256")),
fileDigest: Config.string("AZURE_TRUSTED_SIGNING_FILE_DIGEST").pipe(
Config.withDefault(() => "SHA256"),
),
timestampDigest: Config.string("AZURE_TRUSTED_SIGNING_TIMESTAMP_DIGEST").pipe(
Config.withDefault("SHA256"),
Config.withDefault(() => "SHA256"),
),
timestampRfc3161: Config.string("AZURE_TRUSTED_SIGNING_TIMESTAMP_RFC3161").pipe(
Config.withDefault("http://timestamp.acs.microsoft.com"),
Config.withDefault(() => "http://timestamp.acs.microsoft.com"),
),
});
@@ -152,10 +151,10 @@ const BuildEnvConfig = Config.all({
arch: Config.schema(BuildArch, "T3CODE_DESKTOP_ARCH").pipe(Config.option),
version: Config.string("T3CODE_DESKTOP_VERSION").pipe(Config.option),
outputDir: Config.string("T3CODE_DESKTOP_OUTPUT_DIR").pipe(Config.option),
skipBuild: Config.boolean("T3CODE_DESKTOP_SKIP_BUILD").pipe(Config.withDefault(false)),
keepStage: Config.boolean("T3CODE_DESKTOP_KEEP_STAGE").pipe(Config.withDefault(false)),
signed: Config.boolean("T3CODE_DESKTOP_SIGNED").pipe(Config.withDefault(false)),
verbose: Config.boolean("T3CODE_DESKTOP_VERBOSE").pipe(Config.withDefault(false)),
skipBuild: Config.boolean("T3CODE_DESKTOP_SKIP_BUILD").pipe(Config.withDefault(() => false)),
keepStage: Config.boolean("T3CODE_DESKTOP_KEEP_STAGE").pipe(Config.withDefault(() => false)),
signed: Config.boolean("T3CODE_DESKTOP_SIGNED").pipe(Config.withDefault(() => false)),
verbose: Config.boolean("T3CODE_DESKTOP_VERBOSE").pipe(Config.withDefault(() => false)),
});
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
@@ -163,7 +162,7 @@ const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
const mergeOptions = <A>(a: Option.Option<A>, b: Option.Option<A>, defaultValue: A) =>
Option.getOrElse(a, () => Option.getOrElse(b, () => defaultValue));
const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (input: BuildCliInput) {
const resolveBuildOptions = Effect.fn(function* (input: BuildCliInput) {
const path = yield* Path.Path;
const repoRoot = yield* RepoRoot;
const env = yield* BuildEnvConfig.asEffect();
@@ -209,14 +208,12 @@ const commandOutputOptions = (verbose: boolean) =>
stderr: "inherit",
}) as const;
const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const child = yield* commandSpawner.spawn(command);
const exitCode = yield* child.exitCode;
const runCommand = Effect.fn(function* (command: ChildProcess.Command) {
const exitCode = yield* ChildProcess.exitCode(command);
if (exitCode !== 0) {
return yield* new BuildScriptError({
message: `Command exited with non-zero exit code (${exitCode})`,
message: "Command exited with non-zero exit code",
});
}
});
@@ -291,9 +288,9 @@ function validateBundledClientAssets(clientDir: string) {
const path = yield* Path.Path;
const indexPath = path.join(clientDir, "index.html");
const indexHtml = yield* fs.readFileString(indexPath);
const refs = [...indexHtml.matchAll(/\b(?:src|href)=["']([^"']+)["']/g)]
.map((match) => match[1])
.filter((value): value is string => value !== undefined);
const refs = [...indexHtml.matchAll(/\b(?:src|href)=["']([^"']+)["']/g)].map(
(match) => match[1],
);
const missing: string[] = [];
for (const ref of refs) {
@@ -322,47 +319,32 @@ function validateBundledClientAssets(clientDir: string) {
});
}
function resolveDesktopRuntimeDependencies(
dependencies: Record<string, unknown> | undefined,
function resolveCatalogDependencies(
dependencies: Record<string, unknown>,
catalog: Record<string, unknown>,
dependencySourceLabel: string,
): Record<string, unknown> {
if (!dependencies || Object.keys(dependencies).length === 0) {
return {};
}
return Object.fromEntries(
Object.entries(dependencies).map(([dependencyName, spec]) => {
if (typeof spec !== "string" || !spec.startsWith("catalog:")) {
return [dependencyName, spec];
}
const runtimeDependencies = Object.fromEntries(
Object.entries(dependencies).filter(([dependencyName]) => dependencyName !== "electron"),
const catalogKey = spec.slice("catalog:".length).trim();
const lookupKey = catalogKey.length > 0 ? catalogKey : dependencyName;
const resolvedSpec = catalog[lookupKey];
if (typeof resolvedSpec !== "string" || resolvedSpec.length === 0) {
throw new BuildScriptError({
message: `Unable to resolve '${spec}' for ${dependencySourceLabel} dependency '${dependencyName}'. Expected key '${lookupKey}' in root workspace catalog.`,
});
}
return [dependencyName, resolvedSpec];
}),
);
return resolveCatalogDependencies(runtimeDependencies, catalog, "apps/desktop");
}
function resolveGitHubPublishConfig():
| {
readonly provider: "github";
readonly owner: string;
readonly repo: string;
readonly releaseType: "release";
}
| undefined {
const rawRepo =
process.env.T3CODE_DESKTOP_UPDATE_REPOSITORY?.trim() ||
process.env.GITHUB_REPOSITORY?.trim() ||
"";
if (!rawRepo) return undefined;
const [owner, repo, ...rest] = rawRepo.split("/");
if (!owner || !repo || rest.length > 0) return undefined;
return {
provider: "github",
owner,
repo,
releaseType: "release",
};
}
const createBuildConfig = Effect.fn("createBuildConfig")(function* (
const createBuildConfig = Effect.fn(function* (
platform: typeof BuildPlatform.Type,
target: string,
productName: string,
@@ -376,14 +358,10 @@ const createBuildConfig = Effect.fn("createBuildConfig")(function* (
buildResources: "apps/desktop/resources",
},
};
const publishConfig = resolveGitHubPublishConfig();
if (publishConfig) {
buildConfig.publish = [publishConfig];
}
if (platform === "mac") {
buildConfig.mac = {
target: target === "dmg" ? [target, "zip"] : [target],
target: [target],
icon: "icon.icns",
category: "public.app-category.developer-tools",
};
@@ -411,7 +389,7 @@ const createBuildConfig = Effect.fn("createBuildConfig")(function* (
return buildConfig;
});
const assertPlatformBuildResources = Effect.fn("assertPlatformBuildResources")(function* (
const assertPlatformBuildResources = Effect.fn(function* (
platform: typeof BuildPlatform.Type,
stageResourcesDir: string,
verbose: boolean,
@@ -444,9 +422,7 @@ const assertPlatformBuildResources = Effect.fn("assertPlatformBuildResources")(f
}
});
const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
options: ResolvedBuildOptions,
) {
const buildDesktopArtifact = Effect.fn(function* (options: ResolvedBuildOptions) {
const repoRoot = yield* RepoRoot;
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
@@ -460,38 +436,22 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
const electronVersion = desktopPackageJson.dependencies.electron;
const serverDependencies = serverPackageJson.dependencies;
if (!serverDependencies || Object.keys(serverDependencies).length === 0) {
const dependencies = serverPackageJson.dependencies;
if (!dependencies || Object.keys(dependencies).length === 0) {
return yield* new BuildScriptError({
message: "Could not resolve production dependencies from apps/server/package.json.",
});
}
const resolvedServerDependencies = yield* Effect.try({
const resolvedDependencies = yield* Effect.try({
try: () =>
resolveCatalogDependencies(
serverDependencies,
rootPackageJson.workspaces.catalog,
"apps/server",
),
resolveCatalogDependencies(dependencies, rootPackageJson.workspaces.catalog, "apps/server"),
catch: (cause) =>
new BuildScriptError({
message: "Could not resolve production dependencies from apps/server/package.json.",
cause,
}),
});
const resolvedDesktopRuntimeDependencies = yield* Effect.try({
try: () =>
resolveDesktopRuntimeDependencies(
desktopPackageJson.dependencies,
rootPackageJson.workspaces.catalog,
),
catch: (cause) =>
new BuildScriptError({
message: "Could not resolve desktop runtime dependencies from apps/desktop/package.json.",
cause,
}),
});
const appVersion = options.version ?? serverPackageJson.version;
const commitHash = resolveGitCommitHash(repoRoot);
@@ -560,17 +520,16 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
desktopPackageJson.productName ?? "T3 Code",
options.signed,
),
dependencies: {
...resolvedServerDependencies,
...resolvedDesktopRuntimeDependencies,
},
dependencies: resolvedDependencies,
devDependencies: {
electron: electronVersion,
},
};
const stagePackageJsonString = yield* encodeJsonString(stagePackageJson);
yield* fs.writeFileString(path.join(stageAppDir, "package.json"), `${stagePackageJsonString}\n`);
yield* fs.writeFileString(
path.join(stageAppDir, "package.json"),
`${JSON.stringify(stagePackageJson, null, 2)}\n`,
);
yield* Effect.log("[desktop-artifact] Installing staged production dependencies...");
yield* runCommand(
@@ -605,7 +564,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
cwd: stageAppDir,
env: buildEnv,
...commandOutputOptions(options.verbose),
})`bunx electron-builder ${platformConfig.cliFlag} --${options.arch} --publish never`,
})`bunx electron-builder ${platformConfig.cliFlag} ${options.target} --${options.arch} --publish never`,
);
const stageDistDir = path.join(stageAppDir, "dist");
@@ -688,10 +647,9 @@ const buildDesktopArtifactCli = Command.make("build-desktop-artifact", {
Command.withHandler((input) => Effect.flatMap(resolveBuildOptions(input), buildDesktopArtifact)),
);
const cliRuntimeLayer = Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer);
Command.run(buildDesktopArtifactCli, { version: "0.0.0" }).pipe(
Effect.scoped,
Effect.provide(cliRuntimeLayer),
Effect.provide(Logger.layer([Logger.consolePretty()])),
Effect.provide(NodeServices.layer),
NodeRuntime.runMain,
);
+425
View File
@@ -0,0 +1,425 @@
import { spawn } from "node:child_process";
import net from "node:net";
import { homedir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
const BASE_SERVER_PORT = 3773;
const BASE_WEB_PORT = 5733;
const MAX_HASH_OFFSET = 3000;
const MAX_PORT = 65535;
export const DEFAULT_DEV_STATE_DIR = path.join(homedir(), ".t3", "dev");
const MODE_ARGS = {
dev: [
"run",
"dev",
"--ui=tui",
"--filter=@t3tools/contracts",
"--filter=@t3tools/web",
"--filter=t3",
"--parallel",
],
"dev:server": ["run", "dev", "--filter=t3"],
"dev:web": ["run", "dev", "--filter=@t3tools/web"],
"dev:desktop": ["run", "dev", "--filter=@t3tools/desktop", "--filter=@t3tools/web", "--parallel"],
};
const FORWARDED_ENV_FLAGS = {
"state-dir": { envName: "T3CODE_STATE_DIR", expectsValue: true },
"auth-token": { envName: "T3CODE_AUTH_TOKEN", expectsValue: true },
token: { envName: "T3CODE_AUTH_TOKEN", expectsValue: true },
"no-browser": { envName: "T3CODE_NO_BROWSER", expectsValue: false },
"auto-bootstrap-project-from-cwd": {
envName: "T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD",
expectsValue: false,
},
"log-websocket-events": { envName: "T3CODE_LOG_WS_EVENTS", expectsValue: false },
"log-ws-events": { envName: "T3CODE_LOG_WS_EVENTS", expectsValue: false },
host: { envName: "T3CODE_HOST", expectsValue: true },
port: { envName: "T3CODE_PORT", expectsValue: true },
"dev-url": { envName: "VITE_DEV_SERVER_URL", expectsValue: true },
};
function parseInteger(value, envName) {
const parsed = Number(value);
if (!Number.isInteger(parsed)) {
throw new Error(`Invalid ${envName}: ${value}`);
}
return parsed;
}
function hashSeed(seed) {
let hash = 0x811c9dc5;
for (let i = 0; i < seed.length; i += 1) {
hash ^= seed.charCodeAt(i);
hash = Math.imul(hash, 0x01000193);
}
return hash >>> 0;
}
export function resolveOffset(env = process.env) {
const explicitOffset = env.T3CODE_PORT_OFFSET?.trim();
if (explicitOffset) {
const parsed = parseInteger(explicitOffset, "T3CODE_PORT_OFFSET");
if (parsed < 0) {
throw new Error(`Invalid T3CODE_PORT_OFFSET: ${explicitOffset}`);
}
return { offset: parsed, source: `T3CODE_PORT_OFFSET=${explicitOffset}` };
}
const seed = env.T3CODE_DEV_INSTANCE?.trim();
if (!seed) {
return { offset: 0, source: "default ports" };
}
if (/^\d+$/.test(seed)) {
return { offset: Number(seed), source: `numeric T3CODE_DEV_INSTANCE=${seed}` };
}
const offset = (hashSeed(seed) % MAX_HASH_OFFSET) + 1;
return { offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` };
}
function parseLongFlag(raw) {
if (!raw.startsWith("--")) return null;
const normalized = raw.slice(2);
const equalsIndex = normalized.indexOf("=");
if (equalsIndex === -1) {
return { name: normalized, value: undefined };
}
return {
name: normalized.slice(0, equalsIndex),
value: normalized.slice(equalsIndex + 1),
};
}
function toBooleanEnvValue(value) {
if (value === undefined) return "1";
const normalized = value.trim().toLowerCase();
if (normalized === "false" || normalized === "0" || normalized === "no") return "0";
return "1";
}
export function parseDevRunnerArgs(rawArgs) {
const args = rawArgs[0] === "--" ? rawArgs.slice(1) : rawArgs.slice();
const envOverrides = {};
const turboArgs = [];
let isDryRun = false;
for (let index = 0; index < args.length; index += 1) {
const arg = args[index];
if (arg === "--dry-run") {
isDryRun = true;
continue;
}
if (arg === "--") {
turboArgs.push(...args.slice(index + 1));
break;
}
const parsedFlag = parseLongFlag(arg);
if (!parsedFlag) {
turboArgs.push(arg);
continue;
}
const definition = FORWARDED_ENV_FLAGS[parsedFlag.name];
if (!definition) {
turboArgs.push(arg);
continue;
}
if (definition.expectsValue) {
let value = parsedFlag.value;
if (value === undefined) {
const next = args[index + 1];
if (next === undefined || next === "--" || next.startsWith("-")) {
throw new Error(`Missing value for --${parsedFlag.name}`);
}
value = next;
index += 1;
}
envOverrides[definition.envName] = value;
continue;
}
envOverrides[definition.envName] = toBooleanEnvValue(parsedFlag.value);
}
return {
isDryRun,
envOverrides,
turboArgs,
};
}
function resolveStateDir(env, envOverrides) {
const overrideValue = envOverrides?.T3CODE_STATE_DIR?.trim();
if (overrideValue) {
// Resolve relative paths against cwd (monorepo root) before turbo changes directories
return path.resolve(overrideValue);
}
const envValue = env?.T3CODE_STATE_DIR?.trim();
if (envValue) {
return path.resolve(envValue);
}
return DEFAULT_DEV_STATE_DIR;
}
export function createDevRunnerEnv({ mode, env, offset, envOverrides }) {
const serverPort = BASE_SERVER_PORT + offset;
const webPort = BASE_WEB_PORT + offset;
const output = {
...env,
T3CODE_PORT: String(serverPort),
PORT: String(webPort),
ELECTRON_RENDERER_PORT: String(webPort),
VITE_WS_URL: `ws://localhost:${serverPort}`,
VITE_DEV_SERVER_URL: `http://localhost:${webPort}`,
...envOverrides,
};
output.T3CODE_STATE_DIR = resolveStateDir(env, envOverrides);
const parsedServerPort = Number(output.T3CODE_PORT);
if (!Number.isInteger(parsedServerPort) || parsedServerPort < 1 || parsedServerPort > 65535) {
throw new Error(
`Invalid T3CODE_PORT override: '${String(output.T3CODE_PORT)}'. Expected an integer between 1 and 65535.`,
);
}
output.VITE_WS_URL = `ws://localhost:${parsedServerPort}`;
if (mode === "dev" || mode === "dev:server" || mode === "dev:web") {
// Running server/web in browser mode should not inherit desktop launcher state.
output.T3CODE_MODE = "web";
if (!("T3CODE_NO_BROWSER" in envOverrides)) {
delete output.T3CODE_NO_BROWSER;
}
if (!("T3CODE_AUTH_TOKEN" in envOverrides)) {
delete output.T3CODE_AUTH_TOKEN;
}
delete output.T3CODE_DESKTOP_WS_URL;
}
if (mode === "dev" && !output.T3CODE_LOG_WS_EVENTS) {
output.T3CODE_LOG_WS_EVENTS = "1";
}
return output;
}
function portPairForOffset(offset) {
return {
serverPort: BASE_SERVER_PORT + offset,
webPort: BASE_WEB_PORT + offset,
};
}
async function canListenOnHost(port, host) {
return await new Promise((resolve) => {
const server = net.createServer();
server.unref();
server.once("error", (error) => {
const code = error?.code;
if (code === "EADDRNOTAVAIL") {
// Host family unavailable on this machine (for example, no IPv6 loopback).
resolve(true);
return;
}
resolve(false);
});
server.once("listening", () => {
server.close(() => {
resolve(true);
});
});
server.listen({ host, port });
});
}
async function isPortAvailable(port) {
// Vite/dev traffic uses localhost loopback. Verify both IPv4 and IPv6 loopback
// so we don't pick a port that fails later on one address family.
const [ipv4, ipv6] = await Promise.all([
canListenOnHost(port, "127.0.0.1"),
canListenOnHost(port, "::1"),
]);
return ipv4 && ipv6;
}
const defaultCheckPortAvailability = isPortAvailable;
export async function findFirstAvailableOffset({
startOffset,
requireServerPort,
requireWebPort,
checkPortAvailability = defaultCheckPortAvailability,
}) {
for (let candidate = startOffset; ; candidate += 1) {
const { serverPort, webPort } = portPairForOffset(candidate);
const serverPortOutOfRange = serverPort > MAX_PORT;
const webPortOutOfRange = webPort > MAX_PORT;
if (
(requireServerPort && serverPortOutOfRange) ||
(requireWebPort && webPortOutOfRange) ||
(!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
) {
break;
}
const checks = [];
if (requireServerPort) {
checks.push(checkPortAvailability(serverPort));
}
if (requireWebPort) {
checks.push(checkPortAvailability(webPort));
}
if (checks.length === 0) {
return candidate;
}
const availability = await Promise.all(checks);
if (availability.every(Boolean)) {
return candidate;
}
}
throw new Error(
`No available dev ports found from offset ${startOffset}. Tried server=${BASE_SERVER_PORT}+n web=${BASE_WEB_PORT}+n up to port ${MAX_PORT}.`,
);
}
export async function resolveModePortOffsets({
mode,
startOffset,
envOverrides,
checkPortAvailability,
}) {
const hasExplicitServerPort = typeof envOverrides.T3CODE_PORT === "string";
const hasExplicitDevUrl = typeof envOverrides.VITE_DEV_SERVER_URL === "string";
if (mode === "dev:web") {
if (hasExplicitDevUrl) {
return { serverOffset: startOffset, webOffset: startOffset };
}
const webOffset = await findFirstAvailableOffset({
startOffset,
requireServerPort: false,
requireWebPort: true,
checkPortAvailability,
});
return { serverOffset: startOffset, webOffset };
}
if (mode === "dev:server") {
if (hasExplicitServerPort) {
return { serverOffset: startOffset, webOffset: startOffset };
}
const serverOffset = await findFirstAvailableOffset({
startOffset,
requireServerPort: true,
requireWebPort: false,
checkPortAvailability,
});
return { serverOffset, webOffset: serverOffset };
}
const sharedOffset = await findFirstAvailableOffset({
startOffset,
requireServerPort: !hasExplicitServerPort,
requireWebPort: !hasExplicitDevUrl,
checkPortAvailability,
});
return { serverOffset: sharedOffset, webOffset: sharedOffset };
}
export async function runDevRunner(argv = process.argv) {
const mode = argv[2];
const parsedArgs = parseDevRunnerArgs(argv.slice(3));
if (!mode || !(mode in MODE_ARGS)) {
const supportedModes = Object.keys(MODE_ARGS).join(", ");
throw new Error(`Usage: bun scripts/dev-runner.mjs <mode>. Supported modes: ${supportedModes}`);
}
const { offset, source } = resolveOffset();
const { serverOffset, webOffset } = await resolveModePortOffsets({
mode,
startOffset: offset,
envOverrides: parsedArgs.envOverrides,
});
const mergedEnvOverrides = { ...parsedArgs.envOverrides };
if (!("VITE_DEV_SERVER_URL" in mergedEnvOverrides)) {
const { webPort } = portPairForOffset(webOffset);
mergedEnvOverrides.PORT = String(webPort);
mergedEnvOverrides.ELECTRON_RENDERER_PORT = String(webPort);
mergedEnvOverrides.VITE_DEV_SERVER_URL = `http://localhost:${webPort}`;
}
const env = createDevRunnerEnv({
mode,
env: process.env,
offset: serverOffset,
envOverrides: mergedEnvOverrides,
});
const parsedServerPort = Number(env.T3CODE_PORT);
const parsedWebPort = Number(env.PORT);
if (
!Number.isInteger(parsedServerPort) ||
parsedServerPort < 1 ||
parsedServerPort > MAX_PORT ||
!Number.isInteger(parsedWebPort) ||
parsedWebPort < 1 ||
parsedWebPort > MAX_PORT
) {
throw new Error(
`Invalid computed dev ports: server='${String(env.T3CODE_PORT)}' web='${String(env.PORT)}'.`,
);
}
const selectionSuffix =
serverOffset !== offset || webOffset !== offset
? ` selectedOffset(server=${serverOffset},web=${webOffset})`
: "";
console.info(
`[dev-runner] mode=${mode} source=${source}${selectionSuffix} serverPort=${parsedServerPort} webPort=${parsedWebPort} stateDir=${env.T3CODE_STATE_DIR}`,
);
if (parsedArgs.isDryRun) {
return;
}
const command = process.platform === "win32" ? "turbo.cmd" : "turbo";
const child = spawn(command, [...MODE_ARGS[mode], ...parsedArgs.turboArgs], {
stdio: "inherit",
env,
});
child.on("exit", (code, signal) => {
if (signal) {
process.kill(process.pid, signal);
return;
}
process.exit(code ?? 0);
});
child.on("error", (error) => {
console.error("[dev-runner] failed to start turbo", error);
process.exit(1);
});
}
const entrypointPath = process.argv[1] ? pathToFileURL(process.argv[1]).href : "";
if (import.meta.url === entrypointPath) {
runDevRunner().catch((error) => {
console.error("[dev-runner]", error);
process.exit(1);
});
}
+208 -203
View File
@@ -1,218 +1,223 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { resolve } from "node:path";
import { assert, describe, it } from "@effect/vitest";
import { Effect } from "effect";
import { describe, expect, it } from "vitest";
import {
DEFAULT_DEV_STATE_DIR,
createDevRunnerEnv,
findFirstAvailableOffset,
parseDevRunnerArgs,
resolveModePortOffsets,
resolveOffset,
} from "./dev-runner.ts";
} from "./dev-runner.mjs";
it.layer(NodeServices.layer)("dev-runner", (it) => {
describe("resolveOffset", () => {
it.effect("uses explicit T3CODE_PORT_OFFSET when provided", () =>
Effect.sync(() => {
const result = resolveOffset({ portOffset: 12, devInstance: undefined });
assert.deepStrictEqual(result, {
offset: 12,
source: "T3CODE_PORT_OFFSET=12",
});
}),
);
describe("parseDevRunnerArgs", () => {
it("maps supported server flags to env overrides and keeps other flags for turbo", () => {
const parsed = parseDevRunnerArgs([
"--",
"--state-dir",
"~/alt-state",
"--token=abc123",
"--no-browser=false",
"--dry-run",
"--continue",
]);
it.effect("hashes non-numeric instance values", () =>
Effect.sync(() => {
const result = resolveOffset({ portOffset: undefined, devInstance: "feature-branch" });
assert.ok(result.offset >= 1);
assert.ok(result.offset <= 3000);
}),
);
it.effect("throws for negative port offset", () =>
Effect.gen(function* () {
const error = yield* Effect.flip(
Effect.try({
try: () => resolveOffset({ portOffset: -1, devInstance: undefined }),
catch: (cause) => String(cause),
}),
);
assert.ok(error.includes("Invalid T3CODE_PORT_OFFSET"));
}),
);
expect(parsed.isDryRun).toBe(true);
expect(parsed.envOverrides).toEqual({
T3CODE_STATE_DIR: "~/alt-state",
T3CODE_AUTH_TOKEN: "abc123",
T3CODE_NO_BROWSER: "0",
});
expect(parsed.turboArgs).toEqual(["--continue"]);
});
describe("createDevRunnerEnv", () => {
it.effect("defaults state dir to ~/.t3/dev when not provided", () =>
Effect.gen(function* () {
const [env, defaultStateDir] = yield* Effect.all([
createDevRunnerEnv({
mode: "dev",
baseEnv: {},
serverOffset: 0,
webOffset: 0,
stateDir: undefined,
authToken: undefined,
noBrowser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: undefined,
port: undefined,
devUrl: undefined,
}),
DEFAULT_DEV_STATE_DIR,
]);
assert.equal(env.T3CODE_STATE_DIR, defaultStateDir);
}),
);
it.effect("supports explicit typed overrides", () =>
Effect.gen(function* () {
const env = yield* createDevRunnerEnv({
mode: "dev:server",
baseEnv: {},
serverOffset: 0,
webOffset: 0,
stateDir: "/tmp/override-state",
authToken: "secret",
noBrowser: true,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
host: "0.0.0.0",
port: 4222,
devUrl: new URL("http://localhost:7331"),
});
assert.equal(env.T3CODE_STATE_DIR, resolve("/tmp/override-state"));
assert.equal(env.T3CODE_PORT, "4222");
assert.equal(env.VITE_WS_URL, "ws://localhost:4222");
assert.equal(env.T3CODE_NO_BROWSER, "1");
assert.equal(env.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD, "0");
assert.equal(env.T3CODE_LOG_WS_EVENTS, "1");
assert.equal(env.T3CODE_HOST, "0.0.0.0");
assert.equal(env.VITE_DEV_SERVER_URL, "http://localhost:7331/");
}),
);
it("throws when a value flag is missing its value", () => {
expect(() => parseDevRunnerArgs(["--state-dir"])).toThrow("Missing value for --state-dir");
});
describe("findFirstAvailableOffset", () => {
it.effect("returns the starting offset when required ports are available", () =>
Effect.gen(function* () {
const offset = yield* findFirstAvailableOffset({
startOffset: 0,
requireServerPort: true,
requireWebPort: true,
checkPortAvailability: () => Effect.succeed(true),
});
assert.equal(offset, 0);
}),
);
it.effect("advances until all required ports are available", () =>
Effect.gen(function* () {
const taken = new Set([3773, 5733, 3774, 5734]);
const offset = yield* findFirstAvailableOffset({
startOffset: 0,
requireServerPort: true,
requireWebPort: true,
checkPortAvailability: (port) => Effect.succeed(!taken.has(port)),
});
assert.equal(offset, 2);
}),
);
it.effect("allows offsets where only non-required ports exceed max", () =>
Effect.gen(function* () {
const offset = yield* findFirstAvailableOffset({
startOffset: 59_803,
requireServerPort: true,
requireWebPort: false,
checkPortAvailability: () => Effect.succeed(true),
});
assert.equal(offset, 59_803);
}),
);
});
describe("resolveModePortOffsets", () => {
it.effect("uses a shared fallback offset for dev mode", () =>
Effect.gen(function* () {
const taken = new Set([3773, 5733]);
const offsets = yield* resolveModePortOffsets({
mode: "dev",
startOffset: 0,
hasExplicitServerPort: false,
hasExplicitDevUrl: false,
checkPortAvailability: (port) => Effect.succeed(!taken.has(port)),
});
assert.deepStrictEqual(offsets, { serverOffset: 1, webOffset: 1 });
}),
);
it.effect("keeps server offset stable for dev:web and only shifts web offset", () =>
Effect.gen(function* () {
const taken = new Set([5733]);
const offsets = yield* resolveModePortOffsets({
mode: "dev:web",
startOffset: 0,
hasExplicitServerPort: false,
hasExplicitDevUrl: false,
checkPortAvailability: (port) => Effect.succeed(!taken.has(port)),
});
assert.deepStrictEqual(offsets, { serverOffset: 0, webOffset: 1 });
}),
);
it.effect("shifts only server offset for dev:server", () =>
Effect.gen(function* () {
const taken = new Set([3773]);
const offsets = yield* resolveModePortOffsets({
mode: "dev:server",
startOffset: 0,
hasExplicitServerPort: false,
hasExplicitDevUrl: false,
checkPortAvailability: (port) => Effect.succeed(!taken.has(port)),
});
assert.deepStrictEqual(offsets, { serverOffset: 1, webOffset: 1 });
}),
);
it.effect("respects explicit dev-url override for dev:web", () =>
Effect.gen(function* () {
const offsets = yield* resolveModePortOffsets({
mode: "dev:web",
startOffset: 0,
hasExplicitServerPort: false,
hasExplicitDevUrl: true,
checkPortAvailability: () => Effect.succeed(false),
});
assert.deepStrictEqual(offsets, { serverOffset: 0, webOffset: 0 });
}),
);
it.effect("respects explicit server port override for dev:server", () =>
Effect.gen(function* () {
const offsets = yield* resolveModePortOffsets({
mode: "dev:server",
startOffset: 0,
hasExplicitServerPort: true,
hasExplicitDevUrl: false,
checkPortAvailability: () => Effect.succeed(false),
});
assert.deepStrictEqual(offsets, { serverOffset: 0, webOffset: 0 });
}),
it("throws when a value flag is followed by another flag token", () => {
expect(() => parseDevRunnerArgs(["--state-dir", "--continue"])).toThrow(
"Missing value for --state-dir",
);
});
});
describe("createDevRunnerEnv", () => {
it("defaults state dir to ~/.t3/dev when not provided", () => {
const env = createDevRunnerEnv({
mode: "dev",
env: {},
offset: 0,
envOverrides: {},
});
expect(env.T3CODE_STATE_DIR).toBe(DEFAULT_DEV_STATE_DIR);
});
it("uses existing env state dir when --state-dir is not provided", () => {
const env = createDevRunnerEnv({
mode: "dev:server",
env: { T3CODE_STATE_DIR: "/tmp/existing-state" },
offset: 0,
envOverrides: {},
});
expect(env.T3CODE_STATE_DIR).toBe("/tmp/existing-state");
});
it("lets --state-dir override existing env state dir", () => {
const env = createDevRunnerEnv({
mode: "dev:server",
env: { T3CODE_STATE_DIR: "/tmp/existing-state" },
offset: 0,
envOverrides: { T3CODE_STATE_DIR: "/tmp/override-state" },
});
expect(env.T3CODE_STATE_DIR).toBe("/tmp/override-state");
});
it("treats whitespace-only --state-dir as missing and falls back to env/default", () => {
const env = createDevRunnerEnv({
mode: "dev:server",
env: { T3CODE_STATE_DIR: "/tmp/existing-state" },
offset: 0,
envOverrides: { T3CODE_STATE_DIR: " " },
});
expect(env.T3CODE_STATE_DIR).toBe("/tmp/existing-state");
});
it("recomputes websocket url when port is overridden", () => {
const env = createDevRunnerEnv({
mode: "dev",
env: {},
offset: 0,
envOverrides: { T3CODE_PORT: "4222" },
});
expect(env.T3CODE_PORT).toBe("4222");
expect(env.VITE_WS_URL).toBe("ws://localhost:4222");
});
it("keeps explicitly forwarded web-mode flags", () => {
const env = createDevRunnerEnv({
mode: "dev",
env: {
T3CODE_AUTH_TOKEN: "desktop-token",
},
offset: 0,
envOverrides: {
T3CODE_NO_BROWSER: "1",
T3CODE_AUTH_TOKEN: "cli-token",
},
});
expect(env.T3CODE_NO_BROWSER).toBe("1");
expect(env.T3CODE_AUTH_TOKEN).toBe("cli-token");
});
it("fails fast for invalid port overrides", () => {
expect(() =>
createDevRunnerEnv({
mode: "dev",
env: {},
offset: 0,
envOverrides: { T3CODE_PORT: "not-a-port" },
}),
).toThrow("Invalid T3CODE_PORT override");
});
});
describe("findFirstAvailableOffset", () => {
it("returns the starting offset when required ports are available", async () => {
const offset = await findFirstAvailableOffset({
startOffset: 0,
requireServerPort: true,
requireWebPort: true,
checkPortAvailability: async () => true,
});
expect(offset).toBe(0);
});
it("advances until all required ports are available", async () => {
const taken = new Set([3773, 5733, 3774, 5734]);
const offset = await findFirstAvailableOffset({
startOffset: 0,
requireServerPort: true,
requireWebPort: true,
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offset).toBe(2);
});
it("allows offsets where only non-required ports exceed max", async () => {
const offset = await findFirstAvailableOffset({
startOffset: 59_803,
requireServerPort: true,
requireWebPort: false,
checkPortAvailability: async () => true,
});
expect(offset).toBe(59_803);
});
});
describe("resolveModePortOffsets", () => {
it("uses a shared fallback offset for dev mode", async () => {
const taken = new Set([3773, 5733]);
const offsets = await resolveModePortOffsets({
mode: "dev",
startOffset: 0,
envOverrides: {},
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offsets).toEqual({ serverOffset: 1, webOffset: 1 });
});
it("keeps server offset stable for dev:web and only shifts web offset", async () => {
const taken = new Set([5733]);
const offsets = await resolveModePortOffsets({
mode: "dev:web",
startOffset: 0,
envOverrides: {},
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offsets).toEqual({ serverOffset: 0, webOffset: 1 });
});
it("shifts only server offset for dev:server", async () => {
const taken = new Set([3773]);
const offsets = await resolveModePortOffsets({
mode: "dev:server",
startOffset: 0,
envOverrides: {},
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offsets).toEqual({ serverOffset: 1, webOffset: 1 });
});
it("respects explicit dev-url override for dev:web", async () => {
const offsets = await resolveModePortOffsets({
mode: "dev:web",
startOffset: 0,
envOverrides: { VITE_DEV_SERVER_URL: "http://localhost:9999" },
checkPortAvailability: async () => false,
});
expect(offsets).toEqual({ serverOffset: 0, webOffset: 0 });
});
it("respects explicit server port override for dev:server", async () => {
const offsets = await resolveModePortOffsets({
mode: "dev:server",
startOffset: 0,
envOverrides: { T3CODE_PORT: "4888" },
checkPortAvailability: async () => false,
});
expect(offsets).toEqual({ serverOffset: 0, webOffset: 0 });
});
});
-507
View File
@@ -1,507 +0,0 @@
#!/usr/bin/env node
import { homedir } from "node:os";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NetService } from "@t3tools/shared/Net";
import { Config, Data, Effect, Hash, Layer, Logger, Option, Path, Schema } from "effect";
import { Argument, Command, Flag } from "effect/unstable/cli";
import { ChildProcess } from "effect/unstable/process";
const BASE_SERVER_PORT = 3773;
const BASE_WEB_PORT = 5733;
const MAX_HASH_OFFSET = 3000;
const MAX_PORT = 65535;
export const DEFAULT_DEV_STATE_DIR = Effect.map(Effect.service(Path.Path), (path) =>
path.join(homedir(), ".t3", "dev"),
);
const MODE_ARGS = {
dev: [
"run",
"dev",
"--ui=tui",
"--filter=@t3tools/contracts",
"--filter=@t3tools/web",
"--filter=t3",
"--parallel",
],
"dev:server": ["run", "dev", "--filter=t3"],
"dev:web": ["run", "dev", "--filter=@t3tools/web"],
"dev:desktop": ["run", "dev", "--filter=@t3tools/desktop", "--filter=@t3tools/web", "--parallel"],
} as const satisfies Record<string, ReadonlyArray<string>>;
type DevMode = keyof typeof MODE_ARGS;
type PortAvailabilityCheck<R = never> = (port: number) => Effect.Effect<boolean, never, R>;
const DEV_RUNNER_MODES = Object.keys(MODE_ARGS) as Array<DevMode>;
class DevRunnerError extends Data.TaggedError("DevRunnerError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
const optionalStringConfig = (name: string): Config.Config<string | undefined> =>
Config.string(name).pipe(
Config.option,
Config.map((value) => Option.getOrUndefined(value)),
);
const optionalBooleanConfig = (name: string): Config.Config<boolean | undefined> =>
Config.boolean(name).pipe(
Config.option,
Config.map((value) => Option.getOrUndefined(value)),
);
const optionalPortConfig = (name: string): Config.Config<number | undefined> =>
Config.port(name).pipe(
Config.option,
Config.map((value) => Option.getOrUndefined(value)),
);
const optionalIntegerConfig = (name: string): Config.Config<number | undefined> =>
Config.int(name).pipe(
Config.option,
Config.map((value) => Option.getOrUndefined(value)),
);
const optionalUrlConfig = (name: string): Config.Config<URL | undefined> =>
Config.url(name).pipe(
Config.option,
Config.map((value) => Option.getOrUndefined(value)),
);
const OffsetConfig = Config.all({
portOffset: optionalIntegerConfig("T3CODE_PORT_OFFSET"),
devInstance: optionalStringConfig("T3CODE_DEV_INSTANCE"),
});
export function resolveOffset(config: {
readonly portOffset: number | undefined;
readonly devInstance: string | undefined;
}): { readonly offset: number; readonly source: string } {
if (config.portOffset !== undefined) {
if (config.portOffset < 0) {
throw new Error(`Invalid T3CODE_PORT_OFFSET: ${config.portOffset}`);
}
return {
offset: config.portOffset,
source: `T3CODE_PORT_OFFSET=${config.portOffset}`,
};
}
const seed = config.devInstance?.trim();
if (!seed) {
return { offset: 0, source: "default ports" };
}
if (/^\d+$/.test(seed)) {
return { offset: Number(seed), source: `numeric T3CODE_DEV_INSTANCE=${seed}` };
}
const offset = ((Hash.string(seed) >>> 0) % MAX_HASH_OFFSET) + 1;
return { offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` };
}
function resolveStateDir(stateDir: string | undefined): Effect.Effect<string, never, Path.Path> {
return Effect.gen(function* () {
const path = yield* Path.Path;
const configured = stateDir?.trim();
if (configured) {
// Resolve relative paths against cwd (monorepo root) before turbo changes directories.
return path.resolve(configured);
}
return yield* DEFAULT_DEV_STATE_DIR;
});
}
interface CreateDevRunnerEnvInput {
readonly mode: DevMode;
readonly baseEnv: NodeJS.ProcessEnv;
readonly serverOffset: number;
readonly webOffset: number;
readonly stateDir: string | undefined;
readonly authToken: string | undefined;
readonly noBrowser: boolean | undefined;
readonly autoBootstrapProjectFromCwd: boolean | undefined;
readonly logWebSocketEvents: boolean | undefined;
readonly host: string | undefined;
readonly port: number | undefined;
readonly devUrl: URL | undefined;
}
export function createDevRunnerEnv({
mode,
baseEnv,
serverOffset,
webOffset,
stateDir,
authToken,
noBrowser,
autoBootstrapProjectFromCwd,
logWebSocketEvents,
host,
port,
devUrl,
}: CreateDevRunnerEnvInput): Effect.Effect<NodeJS.ProcessEnv, never, Path.Path> {
return Effect.gen(function* () {
const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
const webPort = BASE_WEB_PORT + webOffset;
const resolvedStateDir = yield* resolveStateDir(stateDir);
const output: NodeJS.ProcessEnv = {
...baseEnv,
T3CODE_PORT: String(serverPort),
PORT: String(webPort),
ELECTRON_RENDERER_PORT: String(webPort),
VITE_WS_URL: `ws://localhost:${serverPort}`,
VITE_DEV_SERVER_URL: devUrl?.toString() ?? `http://localhost:${webPort}`,
T3CODE_STATE_DIR: resolvedStateDir,
};
if (host !== undefined) {
output.T3CODE_HOST = host;
}
if (authToken !== undefined) {
output.T3CODE_AUTH_TOKEN = authToken;
} else {
delete output.T3CODE_AUTH_TOKEN;
}
if (noBrowser !== undefined) {
output.T3CODE_NO_BROWSER = noBrowser ? "1" : "0";
} else {
delete output.T3CODE_NO_BROWSER;
}
if (autoBootstrapProjectFromCwd !== undefined) {
output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD = autoBootstrapProjectFromCwd ? "1" : "0";
} else {
delete output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD;
}
if (logWebSocketEvents !== undefined) {
output.T3CODE_LOG_WS_EVENTS = logWebSocketEvents ? "1" : "0";
} else {
delete output.T3CODE_LOG_WS_EVENTS;
}
if (mode === "dev") {
output.T3CODE_MODE = "web";
if (logWebSocketEvents === undefined) {
output.T3CODE_LOG_WS_EVENTS = "1";
}
delete output.T3CODE_DESKTOP_WS_URL;
}
if (mode === "dev:server" || mode === "dev:web") {
output.T3CODE_MODE = "web";
delete output.T3CODE_DESKTOP_WS_URL;
}
return output;
});
}
function portPairForOffset(offset: number): {
readonly serverPort: number;
readonly webPort: number;
} {
return {
serverPort: BASE_SERVER_PORT + offset,
webPort: BASE_WEB_PORT + offset,
};
}
const defaultCheckPortAvailability: PortAvailabilityCheck<NetService> = (port) =>
Effect.gen(function* () {
const net = yield* NetService;
return yield* net.isPortAvailableOnLoopback(port);
});
interface FindFirstAvailableOffsetInput<R = NetService> {
readonly startOffset: number;
readonly requireServerPort: boolean;
readonly requireWebPort: boolean;
readonly checkPortAvailability?: PortAvailabilityCheck<R>;
}
export function findFirstAvailableOffset<R = NetService>({
startOffset,
requireServerPort,
requireWebPort,
checkPortAvailability,
}: FindFirstAvailableOffsetInput<R>): Effect.Effect<number, DevRunnerError, R> {
return Effect.gen(function* () {
const checkPort = (checkPortAvailability ??
defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
for (let candidate = startOffset; ; candidate += 1) {
const { serverPort, webPort } = portPairForOffset(candidate);
const serverPortOutOfRange = serverPort > MAX_PORT;
const webPortOutOfRange = webPort > MAX_PORT;
if (
(requireServerPort && serverPortOutOfRange) ||
(requireWebPort && webPortOutOfRange) ||
(!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
) {
break;
}
const checks: Array<Effect.Effect<boolean, never, R>> = [];
if (requireServerPort) {
checks.push(checkPort(serverPort));
}
if (requireWebPort) {
checks.push(checkPort(webPort));
}
if (checks.length === 0) {
return candidate;
}
const availability = yield* Effect.all(checks);
if (availability.every(Boolean)) {
return candidate;
}
}
return yield* new DevRunnerError({
message: `No available dev ports found from offset ${startOffset}. Tried server=${BASE_SERVER_PORT}+n web=${BASE_WEB_PORT}+n up to port ${MAX_PORT}.`,
});
});
}
interface ResolveModePortOffsetsInput<R = NetService> {
readonly mode: DevMode;
readonly startOffset: number;
readonly hasExplicitServerPort: boolean;
readonly hasExplicitDevUrl: boolean;
readonly checkPortAvailability?: PortAvailabilityCheck<R>;
}
export function resolveModePortOffsets<R = NetService>({
mode,
startOffset,
hasExplicitServerPort,
hasExplicitDevUrl,
checkPortAvailability,
}: ResolveModePortOffsetsInput<R>): Effect.Effect<
{ readonly serverOffset: number; readonly webOffset: number },
DevRunnerError,
R
> {
return Effect.gen(function* () {
const checkPort = (checkPortAvailability ??
defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
if (mode === "dev:web") {
if (hasExplicitDevUrl) {
return { serverOffset: startOffset, webOffset: startOffset };
}
const webOffset = yield* findFirstAvailableOffset({
startOffset,
requireServerPort: false,
requireWebPort: true,
checkPortAvailability: checkPort,
});
return { serverOffset: startOffset, webOffset };
}
if (mode === "dev:server") {
if (hasExplicitServerPort) {
return { serverOffset: startOffset, webOffset: startOffset };
}
const serverOffset = yield* findFirstAvailableOffset({
startOffset,
requireServerPort: true,
requireWebPort: false,
checkPortAvailability: checkPort,
});
return { serverOffset, webOffset: serverOffset };
}
const sharedOffset = yield* findFirstAvailableOffset({
startOffset,
requireServerPort: !hasExplicitServerPort,
requireWebPort: !hasExplicitDevUrl,
checkPortAvailability: checkPort,
});
return { serverOffset: sharedOffset, webOffset: sharedOffset };
});
}
interface DevRunnerCliInput {
readonly mode: DevMode;
readonly stateDir: string | undefined;
readonly authToken: string | undefined;
readonly noBrowser: boolean | undefined;
readonly autoBootstrapProjectFromCwd: boolean | undefined;
readonly logWebSocketEvents: boolean | undefined;
readonly host: string | undefined;
readonly port: number | undefined;
readonly devUrl: URL | undefined;
readonly dryRun: boolean;
readonly turboArgs: ReadonlyArray<string>;
}
export function runDevRunnerWithInput(input: DevRunnerCliInput) {
return Effect.gen(function* () {
const { portOffset, devInstance } = yield* OffsetConfig.asEffect().pipe(
Effect.mapError(
(cause) =>
new DevRunnerError({
message: "Failed to read T3CODE_PORT_OFFSET/T3CODE_DEV_INSTANCE configuration.",
cause,
}),
),
);
const { offset, source } = yield* Effect.try({
try: () => resolveOffset({ portOffset, devInstance }),
catch: (cause) =>
new DevRunnerError({
message: cause instanceof Error ? cause.message : String(cause),
cause,
}),
});
const { serverOffset, webOffset } = yield* resolveModePortOffsets({
mode: input.mode,
startOffset: offset,
hasExplicitServerPort: input.port !== undefined,
hasExplicitDevUrl: input.devUrl !== undefined,
});
const env = yield* createDevRunnerEnv({
mode: input.mode,
baseEnv: process.env,
serverOffset,
webOffset,
stateDir: input.stateDir,
authToken: input.authToken,
noBrowser: input.noBrowser,
autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
logWebSocketEvents: input.logWebSocketEvents,
host: input.host,
port: input.port,
devUrl: input.devUrl,
});
const selectionSuffix =
serverOffset !== offset || webOffset !== offset
? ` selectedOffset(server=${serverOffset},web=${webOffset})`
: "";
yield* Effect.logInfo(
`[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} stateDir=${String(env.T3CODE_STATE_DIR)}`,
);
if (input.dryRun) {
return;
}
const child = yield* ChildProcess.make(
"turbo",
[...MODE_ARGS[input.mode], ...input.turboArgs],
{
stdin: "inherit",
stdout: "inherit",
stderr: "inherit",
env,
extendEnv: false,
},
);
const exitCode = yield* child.exitCode;
if (exitCode !== 0) {
return yield* new DevRunnerError({
message: `turbo exited with code ${exitCode}`,
});
}
}).pipe(
Effect.mapError((cause) =>
cause instanceof DevRunnerError
? cause
: new DevRunnerError({
message: cause instanceof Error ? cause.message : "dev-runner failed",
cause,
}),
),
);
}
const devRunnerCli = Command.make("dev-runner", {
mode: Argument.choice("mode", DEV_RUNNER_MODES).pipe(
Argument.withDescription("Development mode to run."),
),
stateDir: Flag.string("state-dir").pipe(
Flag.withDescription("State directory path (forwards to T3CODE_STATE_DIR)."),
Flag.withFallbackConfig(optionalStringConfig("T3CODE_STATE_DIR")),
),
authToken: Flag.string("auth-token").pipe(
Flag.withDescription("Auth token (forwards to T3CODE_AUTH_TOKEN)."),
Flag.withAlias("token"),
Flag.withFallbackConfig(optionalStringConfig("T3CODE_AUTH_TOKEN")),
),
noBrowser: Flag.boolean("no-browser").pipe(
Flag.withDescription("Browser auto-open toggle (equivalent to T3CODE_NO_BROWSER)."),
Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_NO_BROWSER")),
),
autoBootstrapProjectFromCwd: Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
Flag.withDescription(
"Auto-bootstrap toggle (equivalent to T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).",
),
Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD")),
),
logWebSocketEvents: Flag.boolean("log-websocket-events").pipe(
Flag.withDescription("WebSocket event logging toggle (equivalent to T3CODE_LOG_WS_EVENTS)."),
Flag.withAlias("log-ws-events"),
Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_LOG_WS_EVENTS")),
),
host: Flag.string("host").pipe(
Flag.withDescription("Server host/interface override (forwards to T3CODE_HOST)."),
Flag.withFallbackConfig(optionalStringConfig("T3CODE_HOST")),
),
port: Flag.integer("port").pipe(
Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
Flag.withDescription("Server port override (forwards to T3CODE_PORT)."),
Flag.withFallbackConfig(optionalPortConfig("T3CODE_PORT")),
),
devUrl: Flag.string("dev-url").pipe(
Flag.withSchema(Schema.URLFromString),
Flag.withDescription("Web dev URL override (forwards to VITE_DEV_SERVER_URL)."),
Flag.withFallbackConfig(optionalUrlConfig("VITE_DEV_SERVER_URL")),
),
dryRun: Flag.boolean("dry-run").pipe(
Flag.withDescription("Resolve mode/ports/env and print, but do not spawn turbo."),
Flag.withDefault(false),
),
turboArgs: Argument.string("turbo-arg").pipe(
Argument.withDescription("Additional turbo args (pass after `--`)."),
Argument.variadic(),
),
}).pipe(
Command.withDescription("Run monorepo development modes with deterministic port/env wiring."),
Command.withHandler((input) => runDevRunnerWithInput(input)),
);
const cliRuntimeLayer = Layer.mergeAll(
Logger.layer([Logger.consolePretty()]),
NodeServices.layer,
NetService.layer,
);
const runtimeProgram = Command.run(devRunnerCli, { version: "0.0.0" }).pipe(
Effect.scoped,
Effect.provide(cliRuntimeLayer),
);
if (import.meta.main) {
NodeRuntime.runMain(runtimeProgram);
}
-31
View File
@@ -1,31 +0,0 @@
/**
* Resolve `catalog:` dependency specs using the workspace catalog.
*
* Pure function: returns a new record with every `catalog:…` value replaced by
* the concrete version string found in `catalog`. Throws on missing entries.
*/
export function resolveCatalogDependencies(
dependencies: Record<string, unknown>,
catalog: Record<string, unknown>,
label: string,
): Record<string, unknown> {
return Object.fromEntries(
Object.entries(dependencies).map(([name, spec]) => {
if (typeof spec !== "string" || !spec.startsWith("catalog:")) {
return [name, spec];
}
const catalogKey = spec.slice("catalog:".length).trim();
const lookupKey = catalogKey.length > 0 ? catalogKey : name;
const resolved = catalog[lookupKey];
if (typeof resolved !== "string" || resolved.length === 0) {
throw new Error(
`Unable to resolve '${spec}' for ${label} dependency '${name}'. Expected key '${lookupKey}' in root workspace catalog.`,
);
}
return [name, resolved];
}),
);
}
-23
View File
@@ -1,23 +0,0 @@
{
"name": "@t3tools/scripts",
"private": true,
"type": "module",
"scripts": {
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"@effect/platform-node": "catalog:",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"effect": "catalog:"
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"@types/bun": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
}
}
-16
View File
@@ -1,16 +0,0 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"types": ["node", "bun"],
"lib": ["ES2023", "esnext.disposable"],
"noEmit": true,
"allowImportingTsExtensions": true,
"plugins": [
{
"name": "@effect/language-service"
}
]
},
"include": ["**/*.ts"]
}