Compare commits
No files matched your search
@@ -6,6 +6,10 @@ on:
|
||||
branches:
|
||||
- main
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
name: Lint, Typecheck, Test, Build
|
||||
@@ -46,5 +50,84 @@ jobs:
|
||||
|
||||
- name: Verify preload bundle output
|
||||
run: |
|
||||
test -f apps/desktop/dist-electron/preload.js
|
||||
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
|
||||
test -f apps/desktop/dist-electron/preload.cjs
|
||||
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
|
||||
|
||||
- name: Install desktop runtime deps (Linux)
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
xvfb \
|
||||
xauth \
|
||||
libgtk-3-0 \
|
||||
libnotify4 \
|
||||
libnss3 \
|
||||
libxss1 \
|
||||
libxtst6 \
|
||||
libatspi2.0-0 \
|
||||
libdrm2 \
|
||||
libgbm1 \
|
||||
libxrandr2 \
|
||||
libxshmfence1 \
|
||||
libxi6 \
|
||||
xdg-utils
|
||||
sudo apt-get install -y libasound2t64 || sudo apt-get install -y libasound2
|
||||
|
||||
- name: Desktop perf trace test
|
||||
if: github.event_name != 'pull_request'
|
||||
env:
|
||||
ELECTRON_DISABLE_SANDBOX: "1"
|
||||
T3CODE_PERF_TIMEOUT_MS: "420000"
|
||||
T3CODE_PERF_MAX_KEYPRESS_AVG_MS: "12"
|
||||
T3CODE_PERF_MAX_KEYPRESS_MAX_MS: "24"
|
||||
T3CODE_PERF_MAX_LONG_DISPATCH_COUNT: "5"
|
||||
# Terminal PTY scripting is flaky in CI VMs; renderer perf checks remain enforced.
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "0"
|
||||
# Keep only core renderer interactions in CI perf runs for lower variance.
|
||||
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: "0"
|
||||
# Skip benchmark sweep loops in CI to reduce EventDispatch variance.
|
||||
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "0"
|
||||
# Keep benchmark follow-up passes disabled in CI by default.
|
||||
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "0"
|
||||
T3CODE_ELECTRON_STARTUP_TIMEOUT_MS: "180000"
|
||||
run: xvfb-run -a bun run test:desktop-perf
|
||||
|
||||
- name: Desktop perf trace test (fork PR)
|
||||
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository
|
||||
env:
|
||||
ELECTRON_DISABLE_SANDBOX: "1"
|
||||
T3CODE_PERF_TIMEOUT_MS: "420000"
|
||||
T3CODE_PERF_MAX_KEYPRESS_AVG_MS: "12"
|
||||
T3CODE_PERF_MAX_KEYPRESS_MAX_MS: "24"
|
||||
T3CODE_PERF_MAX_LONG_DISPATCH_COUNT: "5"
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "0"
|
||||
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: "0"
|
||||
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "0"
|
||||
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "0"
|
||||
T3CODE_ELECTRON_STARTUP_TIMEOUT_MS: "180000"
|
||||
run: xvfb-run -a bun run test:desktop-perf
|
||||
|
||||
- name: Desktop perf trace test and PR summary
|
||||
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
ELECTRON_DISABLE_SANDBOX: "1"
|
||||
T3CODE_PERF_TIMEOUT_MS: "420000"
|
||||
T3CODE_PERF_MAX_KEYPRESS_AVG_MS: "12"
|
||||
T3CODE_PERF_MAX_KEYPRESS_MAX_MS: "24"
|
||||
T3CODE_PERF_MAX_LONG_DISPATCH_COUNT: "5"
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "0"
|
||||
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: "0"
|
||||
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "0"
|
||||
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "0"
|
||||
T3CODE_ELECTRON_STARTUP_TIMEOUT_MS: "180000"
|
||||
run: xvfb-run -a bun run test:desktop-perf:post
|
||||
|
||||
- name: Upload desktop perf artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: desktop-perf-artifacts
|
||||
path: /tmp/t3code-perf-artifacts
|
||||
if-no-files-found: ignore
|
||||
@@ -53,7 +53,6 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
|
||||
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
|
||||
- `chat.newLocal`: create a new local chat thread for the active project (no worktree context)
|
||||
- `editor.openFavorite`: open current project/worktree in the last-used editor
|
||||
- `script.{id}.run`: run a project script by id (for example `script.test.run`)
|
||||
|
||||
### Key Syntax
|
||||
|
||||
|
||||
@@ -2,13 +2,14 @@
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.mjs",
|
||||
"scripts": {
|
||||
"dev": "bun run --parallel dev:bundle dev:electron",
|
||||
"dev:bundle": "tsdown --watch",
|
||||
"dev:bundle": "tsdown --watch --no-clean",
|
||||
"dev:electron": "bun run scripts/dev-electron.mjs",
|
||||
"build": "tsdown",
|
||||
"start": "electron dist-electron/main.js",
|
||||
"start": "electron dist-electron/main.mjs",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
|
||||
@@ -1,24 +1,184 @@
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
import waitOn from "wait-on";
|
||||
import fs from "node:fs";
|
||||
import net from "node:net";
|
||||
import path from "node:path";
|
||||
|
||||
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5173);
|
||||
const devServerUrl = `http://localhost:${port}`;
|
||||
const STARTUP_TIMEOUT_MS = Number(process.env.T3CODE_ELECTRON_STARTUP_TIMEOUT_MS ?? 120_000);
|
||||
|
||||
await waitOn({
|
||||
resources: [
|
||||
`tcp:${port}`,
|
||||
"file:dist-electron/main.js",
|
||||
"file:dist-electron/preload.js",
|
||||
"file:../server/dist/index.mjs",
|
||||
],
|
||||
});
|
||||
async function canConnect(host, probePort, timeoutMs = 1_000) {
|
||||
return new Promise((resolve) => {
|
||||
const socket = new net.Socket();
|
||||
let settled = false;
|
||||
|
||||
const finish = (value) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
socket.destroy();
|
||||
resolve(value);
|
||||
};
|
||||
|
||||
socket.setTimeout(timeoutMs);
|
||||
socket.once("connect", () => finish(true));
|
||||
socket.once("timeout", () => finish(false));
|
||||
socket.once("error", () => finish(false));
|
||||
socket.connect(probePort, host);
|
||||
});
|
||||
}
|
||||
|
||||
const f = (p) => path.join(import.meta.dirname, "..", p);
|
||||
|
||||
function inspectBundleFile(bundleFile) {
|
||||
let stat = null;
|
||||
try {
|
||||
stat = fs.statSync(bundleFile.path);
|
||||
} catch {
|
||||
return {
|
||||
...bundleFile,
|
||||
status: "missing",
|
||||
mtimeMs: null,
|
||||
reason: "not found",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...bundleFile,
|
||||
status: "ready",
|
||||
mtimeMs: stat.mtimeMs,
|
||||
reason: "ok",
|
||||
};
|
||||
}
|
||||
|
||||
function describeBundleStates(states) {
|
||||
return states
|
||||
.map((state) => {
|
||||
const mtime =
|
||||
typeof state.mtimeMs === "number" ? new Date(state.mtimeMs).toISOString() : "n/a";
|
||||
return `${state.label}=${state.status} (mtime=${mtime}; reason=${state.reason})`;
|
||||
})
|
||||
.join("; ");
|
||||
}
|
||||
|
||||
function waitForDesktopBundles(timeoutMs) {
|
||||
const startedAt = Date.now();
|
||||
const bundleFiles = [
|
||||
{
|
||||
path: f("dist-electron/main.mjs"),
|
||||
label: "desktop/main.mjs",
|
||||
},
|
||||
{
|
||||
path: f("dist-electron/preload.cjs"),
|
||||
label: "desktop/preload.cjs",
|
||||
},
|
||||
{
|
||||
path: f("../server/dist/index.mjs"),
|
||||
label: "server/index.mjs",
|
||||
},
|
||||
];
|
||||
let lastProgressLogAt = 0;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const tick = () => {
|
||||
const states = bundleFiles.map(inspectBundleFile);
|
||||
const missing = states.filter((state) => state.status === "missing");
|
||||
|
||||
if (missing.length === 0) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
const elapsedMs = Date.now() - startedAt;
|
||||
if (elapsedMs >= timeoutMs) {
|
||||
const parts = [];
|
||||
if (missing.length > 0) {
|
||||
parts.push(`missing: ${missing.map((state) => state.label).join(", ")}`);
|
||||
}
|
||||
reject(
|
||||
new Error(
|
||||
`[dev-electron] timed out after ${timeoutMs}ms waiting for bundles (${parts.join("; ")})\n[dev-electron] bundle state: ${describeBundleStates(states)}`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Date.now() - lastProgressLogAt >= 5_000) {
|
||||
lastProgressLogAt = Date.now();
|
||||
const waitParts = [];
|
||||
if (missing.length > 0) {
|
||||
waitParts.push(`missing=${missing.map((state) => state.label).join(",")}`);
|
||||
}
|
||||
console.log(
|
||||
`[dev-electron] still waiting for bundles after ${elapsedMs}ms (${waitParts.join("; ")})`,
|
||||
);
|
||||
}
|
||||
|
||||
setTimeout(tick, 250);
|
||||
};
|
||||
|
||||
tick();
|
||||
});
|
||||
}
|
||||
|
||||
function waitForDevServer(probePort, timeoutMs) {
|
||||
const startedAt = Date.now();
|
||||
const candidates = [
|
||||
{ host: "127.0.0.1", url: `http://127.0.0.1:${probePort}` },
|
||||
{ host: "::1", url: `http://[::1]:${probePort}` },
|
||||
{ host: "localhost", url: `http://localhost:${probePort}` },
|
||||
];
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const tick = () => {
|
||||
void Promise.all(
|
||||
candidates.map(async (candidate) => ({
|
||||
candidate,
|
||||
connected: await canConnect(candidate.host, probePort),
|
||||
})),
|
||||
)
|
||||
.then((results) => {
|
||||
const ready = results.find((entry) => entry.connected);
|
||||
if (ready) {
|
||||
resolve(ready.candidate.url);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Date.now() - startedAt >= timeoutMs) {
|
||||
reject(
|
||||
new Error(
|
||||
`[dev-electron] timed out after ${timeoutMs}ms waiting for renderer dev server on port ${probePort}`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
setTimeout(tick, 250);
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(error);
|
||||
});
|
||||
};
|
||||
|
||||
tick();
|
||||
});
|
||||
}
|
||||
|
||||
console.log("[dev-electron] waiting for desktop/server bundles");
|
||||
await waitForDesktopBundles(STARTUP_TIMEOUT_MS);
|
||||
|
||||
console.log(`[dev-electron] waiting for renderer dev server on port ${port}`);
|
||||
const devServerUrl = await waitForDevServer(port, STARTUP_TIMEOUT_MS);
|
||||
console.log(`[dev-electron] launching electron with renderer url ${devServerUrl}`);
|
||||
|
||||
const command = process.platform === "win32" ? "electronmon.cmd" : "electronmon";
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const child = spawn(command, ["dist-electron/main.js"], {
|
||||
if (process.platform === "linux" && !childEnv.ELECTRON_DISABLE_SANDBOX) {
|
||||
childEnv.ELECTRON_DISABLE_SANDBOX = "1";
|
||||
console.log("[dev-electron] enabling ELECTRON_DISABLE_SANDBOX=1 on Linux");
|
||||
}
|
||||
|
||||
const child = spawn(command, ["dist-electron/main.mjs"], {
|
||||
stdio: "inherit",
|
||||
env: {
|
||||
...childEnv,
|
||||
@@ -29,3 +189,8 @@ const child = spawn(command, ["dist-electron/main.js"], {
|
||||
child.on("exit", (code) => {
|
||||
process.exit(code ?? 0);
|
||||
});
|
||||
|
||||
child.on("error", (error) => {
|
||||
console.error("[dev-electron] failed to launch electronmon:", error.message);
|
||||
process.exit(1);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,11 +1,9 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const desktopDir = resolve(__dirname, "..");
|
||||
const desktopDir = resolve(import.meta.dirname, "..");
|
||||
const electronBin = resolve(desktopDir, "node_modules/.bin/electron");
|
||||
const mainJs = resolve(desktopDir, "dist-electron/main.js");
|
||||
const mainJs = resolve(desktopDir, "dist-electron/main.mjs");
|
||||
|
||||
console.log("\nLaunching Electron smoke test...");
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -16,11 +16,13 @@ const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const ROOT_DIR = path.resolve(__dirname, "../../..");
|
||||
const ROOT_DIR = path.resolve(import.meta.dirname, "../../..");
|
||||
const BACKEND_ENTRY = path.join(ROOT_DIR, "apps/server/dist/index.mjs");
|
||||
const WEB_ENTRY = path.join(ROOT_DIR, "apps/web/dist/index.html");
|
||||
const STATE_DIR = path.join(os.homedir(), ".t3", "userdata");
|
||||
const STATE_DIR =
|
||||
process.env.T3CODE_STATE_DIR?.trim() || path.join(os.homedir(), ".t3", "userdata");
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const PERF_AUTOMATION_ENABLED = process.env.T3CODE_DESKTOP_PERF_AUTOMATION === "1";
|
||||
|
||||
let mainWindow: BrowserWindow | null = null;
|
||||
let backendProcess: ChildProcess | null = null;
|
||||
@@ -31,6 +33,32 @@ let restartAttempt = 0;
|
||||
let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let isQuitting = false;
|
||||
|
||||
async function runPerfAutomationIfEnabled(window: BrowserWindow): Promise<void> {
|
||||
if (!PERF_AUTOMATION_ENABLED) return;
|
||||
try {
|
||||
const { runDesktopPerfAutomation } = await import("./desktopPerfAutomation");
|
||||
await runDesktopPerfAutomation(window);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.error("[desktop-perf] failed to load automation module:", message);
|
||||
const doneOutPath = process.env.T3CODE_DESKTOP_PERF_DONE_OUT?.trim() ?? "";
|
||||
if (doneOutPath.length > 0) {
|
||||
fs.mkdirSync(path.dirname(doneOutPath), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
doneOutPath,
|
||||
JSON.stringify(
|
||||
{
|
||||
status: "error",
|
||||
error: `Failed to load desktop perf automation module: ${message}`,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function reserveLoopbackPort(): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const probe = net.createServer();
|
||||
@@ -215,7 +243,7 @@ function createWindow(): BrowserWindow {
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, "preload.js"),
|
||||
preload: path.join(import.meta.dirname, "preload.cjs"),
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: true,
|
||||
@@ -228,13 +256,25 @@ function createWindow(): BrowserWindow {
|
||||
});
|
||||
|
||||
if (isDevelopment) {
|
||||
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
const devUrl = new URL(process.env.VITE_DEV_SERVER_URL as string);
|
||||
if (PERF_AUTOMATION_ENABLED) {
|
||||
devUrl.searchParams.set("t3code_perf_automation", "1");
|
||||
}
|
||||
void window.loadURL(devUrl.toString());
|
||||
if (!PERF_AUTOMATION_ENABLED) {
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
}
|
||||
} else {
|
||||
if (!fs.existsSync(WEB_ENTRY)) {
|
||||
throw new Error(`Web bundle missing at ${WEB_ENTRY}`);
|
||||
}
|
||||
void window.loadFile(WEB_ENTRY);
|
||||
if (PERF_AUTOMATION_ENABLED) {
|
||||
void window.loadFile(WEB_ENTRY, {
|
||||
query: { t3code_perf_automation: "1" },
|
||||
});
|
||||
} else {
|
||||
void window.loadFile(WEB_ENTRY);
|
||||
}
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
@@ -255,6 +295,9 @@ async function bootstrap(): Promise<void> {
|
||||
registerIpcHandlers();
|
||||
startBackend();
|
||||
mainWindow = createWindow();
|
||||
if (mainWindow && PERF_AUTOMATION_ENABLED) {
|
||||
void runPerfAutomationIfEnabled(mainWindow);
|
||||
}
|
||||
}
|
||||
|
||||
app.on("before-quit", () => {
|
||||
|
||||
@@ -0,0 +1,407 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
resolveBenchmarkFollowUpPassCount,
|
||||
shouldRunBenchmarkThreadSweep,
|
||||
shouldRunOptionalRendererPerfInteractions,
|
||||
shouldRunTerminalPerfInteractions,
|
||||
} from "./perfConfig";
|
||||
|
||||
describe("shouldRunTerminalPerfInteractions", () => {
|
||||
it("defaults to enabled outside CI when env is unset", () => {
|
||||
expect(shouldRunTerminalPerfInteractions({ CI: "false" })).toBe(true);
|
||||
expect(shouldRunTerminalPerfInteractions({ CI: "0" })).toBe(true);
|
||||
expect(shouldRunTerminalPerfInteractions({ CI: "off" })).toBe(true);
|
||||
expect(shouldRunTerminalPerfInteractions({ CI: "no" })).toBe(true);
|
||||
expect(shouldRunTerminalPerfInteractions({ CI: undefined })).toBe(true);
|
||||
});
|
||||
|
||||
it("defaults to disabled in CI when env is unset", () => {
|
||||
expect(shouldRunTerminalPerfInteractions({ CI: "true" })).toBe(false);
|
||||
expect(shouldRunTerminalPerfInteractions({ CI: "TRUE" })).toBe(false);
|
||||
expect(shouldRunTerminalPerfInteractions({ CI: "1" })).toBe(false);
|
||||
expect(shouldRunTerminalPerfInteractions({ CI: " yes " })).toBe(false);
|
||||
expect(shouldRunTerminalPerfInteractions({ CI: "on" })).toBe(false);
|
||||
});
|
||||
|
||||
it("supports explicit true values", () => {
|
||||
expect(
|
||||
shouldRunTerminalPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "1",
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldRunTerminalPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: " true ",
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldRunTerminalPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "TRUE",
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldRunTerminalPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: " yes ",
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldRunTerminalPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "ON",
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("supports explicit false values", () => {
|
||||
expect(
|
||||
shouldRunTerminalPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "0",
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldRunTerminalPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: " false ",
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldRunTerminalPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "FALSE",
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldRunTerminalPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: " no ",
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldRunTerminalPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "OFF",
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldRunTerminalPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "0",
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("falls back to CI-based default for unknown values", () => {
|
||||
expect(
|
||||
shouldRunTerminalPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "maybe",
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldRunTerminalPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "maybe",
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldRunTerminalPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "maybe",
|
||||
CI: "ON",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldRunTerminalPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: " ",
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldRunTerminalPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: " ",
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldRunTerminalPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "unknown",
|
||||
CI: "maybe",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveBenchmarkFollowUpPassCount", () => {
|
||||
it("defaults to 1 outside CI", () => {
|
||||
expect(resolveBenchmarkFollowUpPassCount({ CI: "false" })).toBe(1);
|
||||
expect(resolveBenchmarkFollowUpPassCount({ CI: "0" })).toBe(1);
|
||||
expect(resolveBenchmarkFollowUpPassCount({ CI: "maybe" })).toBe(1);
|
||||
expect(resolveBenchmarkFollowUpPassCount({})).toBe(1);
|
||||
});
|
||||
|
||||
it("defaults to 0 in CI", () => {
|
||||
expect(resolveBenchmarkFollowUpPassCount({ CI: "true" })).toBe(0);
|
||||
expect(resolveBenchmarkFollowUpPassCount({ CI: "on" })).toBe(0);
|
||||
expect(resolveBenchmarkFollowUpPassCount({ CI: " yes " })).toBe(0);
|
||||
});
|
||||
|
||||
it("accepts explicit non-negative integer overrides", () => {
|
||||
expect(
|
||||
resolveBenchmarkFollowUpPassCount({
|
||||
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "2",
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(2);
|
||||
expect(
|
||||
resolveBenchmarkFollowUpPassCount({
|
||||
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: " 0 ",
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(0);
|
||||
expect(
|
||||
resolveBenchmarkFollowUpPassCount({
|
||||
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "3",
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(3);
|
||||
});
|
||||
|
||||
it("caps explicit overrides to avoid runaway workload", () => {
|
||||
expect(
|
||||
resolveBenchmarkFollowUpPassCount({
|
||||
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "5",
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(5);
|
||||
expect(
|
||||
resolveBenchmarkFollowUpPassCount({
|
||||
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "6",
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(5);
|
||||
expect(
|
||||
resolveBenchmarkFollowUpPassCount({
|
||||
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "99",
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(5);
|
||||
expect(
|
||||
resolveBenchmarkFollowUpPassCount({
|
||||
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "99",
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(5);
|
||||
});
|
||||
|
||||
it("ignores malformed overrides and falls back to CI default", () => {
|
||||
expect(
|
||||
resolveBenchmarkFollowUpPassCount({
|
||||
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "1abc",
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(0);
|
||||
expect(
|
||||
resolveBenchmarkFollowUpPassCount({
|
||||
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "-1",
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(1);
|
||||
expect(
|
||||
resolveBenchmarkFollowUpPassCount({
|
||||
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "",
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldRunOptionalRendererPerfInteractions", () => {
|
||||
it("defaults to enabled outside CI and disabled in CI", () => {
|
||||
expect(shouldRunOptionalRendererPerfInteractions({ CI: "false" })).toBe(true);
|
||||
expect(shouldRunOptionalRendererPerfInteractions({ CI: "true" })).toBe(false);
|
||||
expect(shouldRunOptionalRendererPerfInteractions({ CI: "ON" })).toBe(false);
|
||||
});
|
||||
|
||||
it("supports explicit env overrides", () => {
|
||||
expect(
|
||||
shouldRunOptionalRendererPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: "1",
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldRunOptionalRendererPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: "off",
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldRunOptionalRendererPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: " FALSE ",
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("falls back to CI default for unknown values", () => {
|
||||
expect(
|
||||
shouldRunOptionalRendererPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: "maybe",
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldRunOptionalRendererPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: "maybe",
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldRunOptionalRendererPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: " ",
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldRunBenchmarkThreadSweep", () => {
|
||||
it("defaults to enabled outside CI and disabled in CI", () => {
|
||||
expect(shouldRunBenchmarkThreadSweep({ CI: "false" })).toBe(true);
|
||||
expect(shouldRunBenchmarkThreadSweep({ CI: "true" })).toBe(false);
|
||||
expect(shouldRunBenchmarkThreadSweep({ CI: "ON" })).toBe(false);
|
||||
});
|
||||
|
||||
it("supports explicit env overrides", () => {
|
||||
expect(
|
||||
shouldRunBenchmarkThreadSweep({
|
||||
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "1",
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldRunBenchmarkThreadSweep({
|
||||
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "off",
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldRunBenchmarkThreadSweep({
|
||||
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "TRUE",
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("falls back to CI default for unknown values", () => {
|
||||
expect(
|
||||
shouldRunBenchmarkThreadSweep({
|
||||
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "maybe",
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldRunBenchmarkThreadSweep({
|
||||
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "maybe",
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("toggle fallback consistency", () => {
|
||||
it("applies the same CI-aware fallback to all perf toggles", () => {
|
||||
const unknownValue = { value: "maybe" };
|
||||
|
||||
expect(
|
||||
shouldRunTerminalPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: unknownValue.value,
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldRunOptionalRendererPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: unknownValue.value,
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldRunBenchmarkThreadSweep({
|
||||
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: unknownValue.value,
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
shouldRunTerminalPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: unknownValue.value,
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldRunOptionalRendererPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: unknownValue.value,
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldRunBenchmarkThreadSweep({
|
||||
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: unknownValue.value,
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts the same explicit truthy aliases for all perf toggles", () => {
|
||||
const truthyAliases = ["1", "true", "TRUE", " yes ", "ON"];
|
||||
for (const value of truthyAliases) {
|
||||
expect(
|
||||
shouldRunTerminalPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: value,
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldRunOptionalRendererPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: value,
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldRunBenchmarkThreadSweep({
|
||||
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: value,
|
||||
CI: "true",
|
||||
}),
|
||||
).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts the same explicit falsy aliases for all perf toggles", () => {
|
||||
const falsyAliases = ["0", "false", "FALSE", " no ", "OFF"];
|
||||
for (const value of falsyAliases) {
|
||||
expect(
|
||||
shouldRunTerminalPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL: value,
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldRunOptionalRendererPerfInteractions({
|
||||
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: value,
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldRunBenchmarkThreadSweep({
|
||||
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: value,
|
||||
CI: "false",
|
||||
}),
|
||||
).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
type PerfToggleEnv = {
|
||||
T3CODE_DESKTOP_PERF_RUN_TERMINAL?: string | undefined;
|
||||
CI?: string | undefined;
|
||||
};
|
||||
|
||||
type OptionalRendererToggleEnv = {
|
||||
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER?: string | undefined;
|
||||
CI?: string | undefined;
|
||||
};
|
||||
|
||||
type PerfBenchmarkEnv = {
|
||||
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES?: string | undefined;
|
||||
CI?: string | undefined;
|
||||
};
|
||||
|
||||
type BenchmarkSweepToggleEnv = {
|
||||
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP?: string | undefined;
|
||||
CI?: string | undefined;
|
||||
};
|
||||
|
||||
const TRUE_VALUES = new Set(["1", "true", "yes", "on"]);
|
||||
const FALSE_VALUES = new Set(["0", "false", "no", "off"]);
|
||||
// Avoid pathological workload from misconfigured env overrides in CI.
|
||||
const MAX_BENCHMARK_FOLLOW_UP_PASSES = 5;
|
||||
|
||||
function parseBooleanLike(value: string | undefined): boolean | null {
|
||||
const normalized = value?.trim().toLowerCase();
|
||||
if (!normalized) return null;
|
||||
if (TRUE_VALUES.has(normalized)) return true;
|
||||
if (FALSE_VALUES.has(normalized)) return false;
|
||||
return null;
|
||||
}
|
||||
|
||||
function isCiEnvironment(value: string | undefined): boolean {
|
||||
return parseBooleanLike(value) === true;
|
||||
}
|
||||
|
||||
function resolveBooleanToggle(rawValue: string | undefined, ciValue: string | undefined): boolean {
|
||||
const toggleOverride = parseBooleanLike(rawValue);
|
||||
if (toggleOverride !== null) return toggleOverride;
|
||||
return !isCiEnvironment(ciValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Controls whether desktop perf automation should include terminal shortcuts.
|
||||
*
|
||||
* Accepted explicit env values:
|
||||
* - truthy: "1", "true", "yes", "on"
|
||||
* - falsy: "0", "false", "no", "off"
|
||||
*
|
||||
* Defaults to "on" for local/dev runs, but "off" in CI unless explicitly enabled.
|
||||
* This keeps CI perf checks focused on renderer responsiveness while avoiding
|
||||
* flaky PTY-dependent interactions in ephemeral Linux runners.
|
||||
*/
|
||||
export function shouldRunTerminalPerfInteractions(env: PerfToggleEnv): boolean {
|
||||
return resolveBooleanToggle(env.T3CODE_DESKTOP_PERF_RUN_TERMINAL, env.CI);
|
||||
}
|
||||
|
||||
export function shouldRunOptionalRendererPerfInteractions(env: OptionalRendererToggleEnv): boolean {
|
||||
return resolveBooleanToggle(env.T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER, env.CI);
|
||||
}
|
||||
|
||||
/**
|
||||
* Controls high-variance benchmark thread switching loops.
|
||||
* Defaults off in CI, on locally, with explicit env override support.
|
||||
*/
|
||||
export function shouldRunBenchmarkThreadSweep(env: BenchmarkSweepToggleEnv): boolean {
|
||||
return resolveBooleanToggle(env.T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP, env.CI);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves number of follow-up benchmark passes.
|
||||
* - explicit non-negative integer env override wins
|
||||
* - value is capped for safety
|
||||
* - otherwise defaults to 0 in CI and 1 locally
|
||||
*/
|
||||
export function resolveBenchmarkFollowUpPassCount(env: PerfBenchmarkEnv): number {
|
||||
const raw = env.T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES?.trim();
|
||||
if (raw && /^\d+$/.test(raw)) {
|
||||
const parsed = Number.parseInt(raw, 10);
|
||||
return Math.min(parsed, MAX_BENCHMARK_FOLLOW_UP_PASSES);
|
||||
}
|
||||
return isCiEnvironment(env.CI) ? 0 : 1;
|
||||
}
|
||||
@@ -1,21 +1,20 @@
|
||||
import { defineConfig } from "tsdown";
|
||||
|
||||
const shared = {
|
||||
format: "cjs" as const,
|
||||
outDir: "dist-electron",
|
||||
sourcemap: true,
|
||||
outExtensions: () => ({ js: ".js" }),
|
||||
};
|
||||
|
||||
export default defineConfig([
|
||||
{
|
||||
...shared,
|
||||
outDir: "dist-electron",
|
||||
sourcemap: true,
|
||||
entry: ["src/main.ts"],
|
||||
clean: true,
|
||||
noExternal: ["@t3tools/contracts"],
|
||||
format: "esm",
|
||||
},
|
||||
{
|
||||
...shared,
|
||||
outDir: "dist-electron",
|
||||
sourcemap: true,
|
||||
entry: ["src/preload.ts"],
|
||||
clean: true,
|
||||
noExternal: ["@t3tools/contracts"],
|
||||
format: "cjs",
|
||||
},
|
||||
]);
|
||||
@@ -17,12 +17,12 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/node": "^22.10.2",
|
||||
"@types/ws": "^8.5.13",
|
||||
|
||||
@@ -4,11 +4,9 @@
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webDist = path.resolve(__dirname, "../../web/dist");
|
||||
const target = path.resolve(__dirname, "../dist/client");
|
||||
const webDist = path.resolve(import.meta.dirname, "../../web/dist");
|
||||
const target = path.resolve(import.meta.dirname, "../dist/client");
|
||||
|
||||
if (!fs.existsSync(webDist)) {
|
||||
console.log(
|
||||
|
||||
@@ -760,35 +760,6 @@ describe("git integration", () => {
|
||||
expect(dirty.hasWorkingTreeChanges).toBe(true);
|
||||
});
|
||||
|
||||
it("refreshes upstream before statusDetails so behind count reflects remote updates", async () => {
|
||||
await using remote = await makeTmpDir();
|
||||
await using source = await makeTmpDir();
|
||||
await using clone = await makeTmpDir();
|
||||
await git(remote.path, "init --bare");
|
||||
|
||||
await initRepoWithCommit(source.path);
|
||||
const initialBranch = (await listGitBranches({ cwd: source.path })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
|
||||
await git(source.path, `push -u origin ${initialBranch}`);
|
||||
|
||||
await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
|
||||
await git(clone.path, "config user.email '[email protected]'");
|
||||
await git(clone.path, "config user.name 'Test'");
|
||||
await git(clone.path, `checkout -B ${initialBranch} --track origin/${initialBranch}`);
|
||||
await writeFile(path.join(clone.path, "CHANGELOG.md"), "remote change\n");
|
||||
await git(clone.path, "add CHANGELOG.md");
|
||||
await git(clone.path, "commit -m 'remote update'");
|
||||
await git(clone.path, `push origin ${initialBranch}`);
|
||||
|
||||
const core = new GitCoreService();
|
||||
const details = await core.statusDetails(source.path);
|
||||
expect(details.branch).toBe(initialBranch);
|
||||
expect(details.aheadCount).toBe(0);
|
||||
expect(details.behindCount).toBe(1);
|
||||
});
|
||||
|
||||
it("prepares commit context by auto-staging and creates commit", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
|
||||
+6
-62
@@ -65,8 +65,6 @@ interface ExecuteGitOptions {
|
||||
}
|
||||
|
||||
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
||||
const STATUS_UPSTREAM_REFRESH_INTERVAL_MS = 15_000;
|
||||
const STATUS_UPSTREAM_REFRESH_TIMEOUT_MS = 5_000;
|
||||
|
||||
/** Spawn git directly with an argv array — no shell, no quoting needed. */
|
||||
function runGit(
|
||||
@@ -218,8 +216,6 @@ async function executeGit(
|
||||
}
|
||||
|
||||
export class GitCoreService {
|
||||
private readonly lastUpstreamRefreshAt = new Map<string, number>();
|
||||
|
||||
async status(raw: GitStatusInput): Promise<GitStatusResult> {
|
||||
const input = gitStatusInputSchema.parse(raw);
|
||||
const details = await this.statusDetails(input.cwd);
|
||||
@@ -235,8 +231,6 @@ export class GitCoreService {
|
||||
}
|
||||
|
||||
async statusDetails(cwd: string): Promise<GitStatusDetails> {
|
||||
await this.refreshStatusUpstreamIfStale(cwd).catch(() => undefined);
|
||||
|
||||
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([
|
||||
this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),
|
||||
this.gitStdout(cwd, ["diff", "--numstat"]),
|
||||
@@ -559,9 +553,7 @@ export class GitCoreService {
|
||||
});
|
||||
}
|
||||
|
||||
private async resolveCurrentUpstream(
|
||||
cwd: string,
|
||||
): Promise<{ upstreamRef: string; remoteName: string; upstreamBranch: string } | null> {
|
||||
private async refreshCheckedOutBranchUpstream(cwd: string): Promise<void> {
|
||||
const upstreamRef = trimStdout(
|
||||
await this.gitStdout(
|
||||
cwd,
|
||||
@@ -570,72 +562,24 @@ export class GitCoreService {
|
||||
),
|
||||
);
|
||||
if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") {
|
||||
return null;
|
||||
return;
|
||||
}
|
||||
|
||||
const separatorIndex = upstreamRef.indexOf("/");
|
||||
if (separatorIndex <= 0) {
|
||||
return null;
|
||||
return;
|
||||
}
|
||||
const remoteName = upstreamRef.slice(0, separatorIndex);
|
||||
const upstreamBranch = upstreamRef.slice(separatorIndex + 1);
|
||||
if (remoteName.length === 0) {
|
||||
return null;
|
||||
return;
|
||||
}
|
||||
if (upstreamBranch.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
upstreamRef,
|
||||
remoteName,
|
||||
upstreamBranch,
|
||||
};
|
||||
}
|
||||
|
||||
private async fetchUpstreamRef(
|
||||
cwd: string,
|
||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
||||
): Promise<void> {
|
||||
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
|
||||
await this.git(cwd, ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], true);
|
||||
}
|
||||
|
||||
private async fetchUpstreamRefForStatus(
|
||||
cwd: string,
|
||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
||||
): Promise<void> {
|
||||
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
|
||||
await executeGit(cwd, ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], {
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: STATUS_UPSTREAM_REFRESH_TIMEOUT_MS,
|
||||
});
|
||||
}
|
||||
|
||||
private async refreshStatusUpstreamIfStale(cwd: string): Promise<void> {
|
||||
const upstream = await this.resolveCurrentUpstream(cwd);
|
||||
if (!upstream) {
|
||||
return;
|
||||
}
|
||||
|
||||
const cacheKey = `${cwd}\u0000${upstream.upstreamRef}`;
|
||||
const now = Date.now();
|
||||
const lastRefreshAt = this.lastUpstreamRefreshAt.get(cacheKey) ?? 0;
|
||||
if (now - lastRefreshAt < STATUS_UPSTREAM_REFRESH_INTERVAL_MS) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Record attempt time first to avoid repeated fetch spikes when status is polled often.
|
||||
this.lastUpstreamRefreshAt.set(cacheKey, now);
|
||||
await this.fetchUpstreamRefForStatus(cwd, upstream);
|
||||
}
|
||||
|
||||
private async refreshCheckedOutBranchUpstream(cwd: string): Promise<void> {
|
||||
const upstream = await this.resolveCurrentUpstream(cwd);
|
||||
if (!upstream) {
|
||||
return;
|
||||
}
|
||||
await this.fetchUpstreamRef(cwd, upstream);
|
||||
const refspec = `+refs/heads/${upstreamBranch}:refs/remotes/${upstreamRef}`;
|
||||
await this.git(cwd, ["fetch", "--quiet", "--no-tags", remoteName, refspec], true);
|
||||
}
|
||||
|
||||
async checkoutBranch(input: GitCheckoutInput): Promise<void> {
|
||||
|
||||
@@ -2,7 +2,6 @@ import fs from "node:fs";
|
||||
import net from "node:net";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { fixPath } from "./fixPath";
|
||||
import { createLogger } from "./logger";
|
||||
@@ -72,11 +71,9 @@ async function findAvailablePort(preferred: number): Promise<number> {
|
||||
}
|
||||
|
||||
function resolveStaticDir(): string | undefined {
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
// Check for bundled client (npm publish / npx scenario):
|
||||
// dist/client/ lives alongside dist/index.js
|
||||
const bundledClient = path.resolve(__dirname, "client");
|
||||
const bundledClient = path.resolve(import.meta.dirname, "client");
|
||||
try {
|
||||
const stat = fs.statSync(path.join(bundledClient, "index.html"));
|
||||
if (stat.isFile()) return bundledClient;
|
||||
@@ -85,7 +82,7 @@ function resolveStaticDir(): string | undefined {
|
||||
}
|
||||
|
||||
// Monorepo layout: apps/server/dist/index.js → apps/web/dist/
|
||||
const monorepoClient = path.resolve(__dirname, "../../web/dist");
|
||||
const monorepoClient = path.resolve(import.meta.dirname, "../../web/dist");
|
||||
try {
|
||||
const stat = fs.statSync(path.join(monorepoClient, "index.html"));
|
||||
if (stat.isFile()) return monorepoClient;
|
||||
|
||||
@@ -1,34 +1,8 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { assert, afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { assert, describe, it } from "vitest";
|
||||
|
||||
import {
|
||||
compileResolvedKeybindingRule,
|
||||
parseKeybindingShortcut,
|
||||
upsertKeybindingRule,
|
||||
} from "./keybindings";
|
||||
import { compileResolvedKeybindingRule, parseKeybindingShortcut } from "./keybindings";
|
||||
|
||||
describe("server keybindings", () => {
|
||||
const tempDirs: string[] = [];
|
||||
const logger = {
|
||||
warn: vi.fn(),
|
||||
};
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
logger.warn.mockReset();
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("parses shortcuts including plus key", () => {
|
||||
assert.deepEqual(parseKeybindingShortcut("mod+j"), {
|
||||
key: "j",
|
||||
@@ -92,101 +66,4 @@ describe("server keybindings", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("upserts custom keybindings to ~/.t3/keybindings.json", () => {
|
||||
const fakeHome = makeTempDir("t3code-keybindings-upsert-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
const configPath = path.join(configDir, "keybindings.json");
|
||||
fs.writeFileSync(
|
||||
configPath,
|
||||
JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
|
||||
"utf8",
|
||||
);
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
const resolved = upsertKeybindingRule(logger, {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
const persisted = JSON.parse(fs.readFileSync(configPath, "utf8")) as Array<{
|
||||
key: string;
|
||||
command: string;
|
||||
}>;
|
||||
|
||||
expect(persisted).toEqual([
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
]);
|
||||
expect(resolved.some((entry) => entry.command === "script.run-tests.run")).toBe(true);
|
||||
});
|
||||
|
||||
it("replaces existing custom keybinding for the same command", () => {
|
||||
const fakeHome = makeTempDir("t3code-keybindings-upsert-replace-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
const configPath = path.join(configDir, "keybindings.json");
|
||||
fs.writeFileSync(
|
||||
configPath,
|
||||
JSON.stringify([{ key: "mod+r", command: "script.run-tests.run" }]),
|
||||
"utf8",
|
||||
);
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
upsertKeybindingRule(logger, {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
|
||||
const persisted = JSON.parse(fs.readFileSync(configPath, "utf8")) as Array<{
|
||||
key: string;
|
||||
command: string;
|
||||
}>;
|
||||
expect(persisted).toEqual([{ key: "mod+shift+r", command: "script.run-tests.run" }]);
|
||||
});
|
||||
|
||||
it("refuses to overwrite malformed keybindings config", () => {
|
||||
const fakeHome = makeTempDir("t3code-keybindings-malformed-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
const configPath = path.join(configDir, "keybindings.json");
|
||||
fs.writeFileSync(configPath, "{ not-json", "utf8");
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
expect(() =>
|
||||
upsertKeybindingRule(logger, {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
}),
|
||||
).toThrow(/Unable to parse keybindings config/);
|
||||
|
||||
expect(fs.readFileSync(configPath, "utf8")).toBe("{ not-json");
|
||||
});
|
||||
|
||||
it("cleans up temp files when atomic keybinding write fails", () => {
|
||||
const fakeHome = makeTempDir("t3code-keybindings-atomic-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
const configPath = path.join(configDir, "keybindings.json");
|
||||
fs.writeFileSync(configPath, JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]), "utf8");
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
vi.spyOn(fs, "renameSync").mockImplementation(() => {
|
||||
throw new Error("rename failed");
|
||||
});
|
||||
|
||||
expect(() =>
|
||||
upsertKeybindingRule(logger, {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
}),
|
||||
).toThrow(/rename failed/);
|
||||
|
||||
expect(fs.readFileSync(configPath, "utf8")).toBe(
|
||||
JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
|
||||
);
|
||||
const tempFiles = fs
|
||||
.readdirSync(configDir)
|
||||
.filter((file) => file.includes("keybindings.json.") && file.endsWith(".tmp"));
|
||||
expect(tempFiles).toEqual([]);
|
||||
});
|
||||
});
|
||||
+53
-122
@@ -274,85 +274,6 @@ function compileDefaultKeybindings(): ResolvedKeybindingsConfig {
|
||||
}
|
||||
|
||||
const DEFAULT_RESOLVED_KEYBINDINGS = compileDefaultKeybindings();
|
||||
const KEYBINDINGS_CONFIG_PATH = path.join(".t3", "keybindings.json");
|
||||
const MAX_KEYBINDINGS = 256;
|
||||
|
||||
function resolveKeybindingsConfigPath(): string {
|
||||
return path.join(os.homedir(), KEYBINDINGS_CONFIG_PATH);
|
||||
}
|
||||
|
||||
function loadCustomKeybindingsConfig(
|
||||
logger: KeybindingsLogger,
|
||||
options?: {
|
||||
throwOnUnreadableConfig?: boolean;
|
||||
},
|
||||
): KeybindingsConfig {
|
||||
const configPath = resolveKeybindingsConfigPath();
|
||||
try {
|
||||
const raw = fs.readFileSync(configPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!Array.isArray(parsed)) {
|
||||
if (options?.throwOnUnreadableConfig) {
|
||||
throw new Error(`Unable to parse keybindings config at ${configPath}: expected JSON array`);
|
||||
}
|
||||
logger.warn("ignoring keybindings config with unsupported format; expected array", {
|
||||
path: configPath,
|
||||
});
|
||||
return [];
|
||||
}
|
||||
|
||||
const sanitized: KeybindingsConfig = [];
|
||||
let invalidEntries = 0;
|
||||
for (const entry of parsed) {
|
||||
const result = keybindingRuleSchema.safeParse(entry);
|
||||
if (result.success) {
|
||||
if (!compileResolvedKeybindingRule(result.data)) {
|
||||
invalidEntries += 1;
|
||||
continue;
|
||||
}
|
||||
sanitized.push(result.data);
|
||||
continue;
|
||||
}
|
||||
invalidEntries += 1;
|
||||
}
|
||||
if (invalidEntries > 0) {
|
||||
logger.warn("ignoring invalid keybinding entries", {
|
||||
path: configPath,
|
||||
invalidEntries,
|
||||
totalEntries: parsed.length,
|
||||
});
|
||||
}
|
||||
return sanitized;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
|
||||
return [];
|
||||
}
|
||||
if (options?.throwOnUnreadableConfig) {
|
||||
throw new Error(
|
||||
`Unable to parse keybindings config at ${configPath}: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
logger.warn("ignoring malformed keybindings config", {
|
||||
path: configPath,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function writeConfigAtomically(configPath: string, config: KeybindingsConfig): void {
|
||||
const tempPath = `${configPath}.${process.pid}.${Date.now()}.tmp`;
|
||||
try {
|
||||
fs.writeFileSync(tempPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
|
||||
fs.renameSync(tempPath, configPath);
|
||||
} catch (error) {
|
||||
fs.rmSync(tempPath, { force: true });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): ResolvedKeybindingsConfig {
|
||||
if (custom.length === 0) {
|
||||
@@ -365,60 +286,70 @@ function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): Resolve
|
||||
);
|
||||
const merged = [...retainedDefaults, ...custom];
|
||||
|
||||
if (merged.length <= MAX_KEYBINDINGS) {
|
||||
if (merged.length <= 256) {
|
||||
return merged;
|
||||
}
|
||||
|
||||
// Keep the latest rules when the config exceeds max size; later rules have higher precedence.
|
||||
return merged.slice(-MAX_KEYBINDINGS);
|
||||
return merged.slice(-256);
|
||||
}
|
||||
|
||||
export function loadResolvedKeybindingsConfig(
|
||||
logger: KeybindingsLogger,
|
||||
): ResolvedKeybindingsConfig {
|
||||
const customConfig = loadCustomKeybindingsConfig(logger);
|
||||
const compiledCustomConfig = compileResolvedKeybindingsConfig(customConfig);
|
||||
const overriddenCommands = new Set(compiledCustomConfig.map((entry) => entry.command));
|
||||
const mergedBeforeCapLength =
|
||||
DEFAULT_RESOLVED_KEYBINDINGS.filter((binding) => !overriddenCommands.has(binding.command))
|
||||
.length + compiledCustomConfig.length;
|
||||
const merged = mergeWithDefaultKeybindings(compiledCustomConfig);
|
||||
if (mergedBeforeCapLength > MAX_KEYBINDINGS) {
|
||||
logger.warn("truncating merged keybindings config to max entries", {
|
||||
path: resolveKeybindingsConfigPath(),
|
||||
maxEntries: MAX_KEYBINDINGS,
|
||||
});
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
const configPath = path.join(os.homedir(), ".t3", "keybindings.json");
|
||||
try {
|
||||
const raw = fs.readFileSync(configPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!Array.isArray(parsed)) {
|
||||
logger.warn("ignoring keybindings config with unsupported format; expected array", {
|
||||
path: configPath,
|
||||
});
|
||||
return [...DEFAULT_RESOLVED_KEYBINDINGS];
|
||||
}
|
||||
|
||||
export function upsertKeybindingRule(
|
||||
logger: KeybindingsLogger,
|
||||
rawRule: unknown,
|
||||
): ResolvedKeybindingsConfig {
|
||||
const rule = keybindingRuleSchema.parse(rawRule);
|
||||
if (!compileResolvedKeybindingRule(rule)) {
|
||||
throw new Error(`Invalid keybinding shortcut: "${rule.key}"`);
|
||||
}
|
||||
|
||||
const configPath = resolveKeybindingsConfigPath();
|
||||
const customConfig = loadCustomKeybindingsConfig(logger, {
|
||||
throwOnUnreadableConfig: true,
|
||||
});
|
||||
const nextConfig = [...customConfig.filter((entry) => entry.command !== rule.command), rule];
|
||||
const cappedConfig =
|
||||
nextConfig.length > MAX_KEYBINDINGS ? nextConfig.slice(-MAX_KEYBINDINGS) : nextConfig;
|
||||
|
||||
if (nextConfig.length > MAX_KEYBINDINGS) {
|
||||
logger.warn("truncating keybindings config to max entries", {
|
||||
const sanitized: ResolvedKeybindingsConfig = [];
|
||||
let invalidEntries = 0;
|
||||
for (const entry of parsed) {
|
||||
const result = keybindingRuleSchema.safeParse(entry);
|
||||
if (result.success) {
|
||||
const compiled = compileResolvedKeybindingRule(result.data);
|
||||
if (!compiled) {
|
||||
invalidEntries += 1;
|
||||
continue;
|
||||
}
|
||||
sanitized.push(compiled);
|
||||
continue;
|
||||
}
|
||||
invalidEntries += 1;
|
||||
}
|
||||
if (invalidEntries > 0) {
|
||||
logger.warn("ignoring invalid keybinding entries", {
|
||||
path: configPath,
|
||||
invalidEntries,
|
||||
totalEntries: parsed.length,
|
||||
});
|
||||
}
|
||||
const overriddenCommands = new Set(sanitized.map((entry) => entry.command));
|
||||
const mergedBeforeCapLength =
|
||||
DEFAULT_RESOLVED_KEYBINDINGS.filter((binding) => !overriddenCommands.has(binding.command))
|
||||
.length + sanitized.length;
|
||||
const merged = mergeWithDefaultKeybindings(sanitized);
|
||||
if (mergedBeforeCapLength > 256) {
|
||||
logger.warn("truncating merged keybindings config to max entries", {
|
||||
path: configPath,
|
||||
maxEntries: 256,
|
||||
});
|
||||
}
|
||||
return merged;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
|
||||
return [...DEFAULT_RESOLVED_KEYBINDINGS];
|
||||
}
|
||||
logger.warn("ignoring malformed keybindings config", {
|
||||
path: configPath,
|
||||
maxEntries: MAX_KEYBINDINGS,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(configPath), { recursive: true });
|
||||
writeConfigAtomically(configPath, cappedConfig);
|
||||
|
||||
const compiledCustomConfig = compileResolvedKeybindingsConfig(cappedConfig);
|
||||
return mergeWithDefaultKeybindings(compiledCustomConfig);
|
||||
return [...DEFAULT_RESOLVED_KEYBINDINGS];
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { ProjectRegistry } from "./projectRegistry";
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("ProjectRegistry scripts", () => {
|
||||
it("stores and reloads project scripts", () => {
|
||||
const stateDir = makeTempDir("t3code-project-registry-state-");
|
||||
const projectDir = makeTempDir("t3code-project-registry-project-");
|
||||
const registry = new ProjectRegistry(stateDir);
|
||||
|
||||
const created = registry.add({ cwd: projectDir }).project;
|
||||
const updated = registry.updateScripts({
|
||||
id: created.id,
|
||||
scripts: [
|
||||
{
|
||||
id: "run",
|
||||
name: "Run",
|
||||
command: "bun run dev",
|
||||
icon: "play",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
command: "bun install",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(updated.project.scripts).toHaveLength(2);
|
||||
expect(updated.project.scripts[1]?.id).toBe("setup");
|
||||
expect(updated.project.scripts[1]?.runOnWorktreeCreate).toBe(true);
|
||||
|
||||
const reloaded = new ProjectRegistry(stateDir);
|
||||
const listed = reloaded.list();
|
||||
expect(listed).toHaveLength(1);
|
||||
expect(listed[0]?.scripts).toHaveLength(2);
|
||||
expect(listed[0]?.scripts[0]?.id).toBe("run");
|
||||
expect(listed[0]?.scripts[1]?.id).toBe("setup");
|
||||
});
|
||||
|
||||
it("deduplicates script ids and allows only one setup script", () => {
|
||||
const stateDir = makeTempDir("t3code-project-registry-state-");
|
||||
const projectDir = makeTempDir("t3code-project-registry-project-");
|
||||
const registry = new ProjectRegistry(stateDir);
|
||||
const created = registry.add({ cwd: projectDir }).project;
|
||||
|
||||
const updated = registry.updateScripts({
|
||||
id: created.id,
|
||||
scripts: [
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
command: "echo setup",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup Duplicate",
|
||||
command: "echo duplicate",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
{
|
||||
id: "another",
|
||||
name: "Another Setup",
|
||||
command: "echo another",
|
||||
icon: "play",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(updated.project.scripts).toHaveLength(2);
|
||||
expect(updated.project.scripts[0]?.id).toBe("setup");
|
||||
expect(updated.project.scripts[0]?.runOnWorktreeCreate).toBe(true);
|
||||
expect(updated.project.scripts[1]?.id).toBe("another");
|
||||
expect(updated.project.scripts[1]?.runOnWorktreeCreate).toBe(false);
|
||||
});
|
||||
|
||||
it("throws when updating scripts for an unknown project id", () => {
|
||||
const stateDir = makeTempDir("t3code-project-registry-state-");
|
||||
const registry = new ProjectRegistry(stateDir);
|
||||
|
||||
expect(() =>
|
||||
registry.updateScripts({
|
||||
id: "missing-project",
|
||||
scripts: [],
|
||||
}),
|
||||
).toThrowError("Project not found");
|
||||
});
|
||||
});
|
||||
@@ -8,31 +8,11 @@ import {
|
||||
type ProjectListResult,
|
||||
type ProjectRecord,
|
||||
type ProjectRemoveInput,
|
||||
type ProjectScript,
|
||||
type ProjectUpdateScriptsInput,
|
||||
type ProjectUpdateScriptsResult,
|
||||
projectAddInputSchema,
|
||||
projectRecordSchema,
|
||||
projectRemoveInputSchema,
|
||||
projectScriptsSchema,
|
||||
projectUpdateScriptsInputSchema,
|
||||
normalizeProjectScripts,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
function cloneScripts(scripts: readonly ProjectScript[]): ProjectScript[] {
|
||||
const cloned: ProjectScript[] = [];
|
||||
for (const script of scripts) {
|
||||
cloned.push({
|
||||
id: script.id,
|
||||
name: script.name,
|
||||
command: script.command,
|
||||
icon: script.icon,
|
||||
runOnWorktreeCreate: script.runOnWorktreeCreate,
|
||||
});
|
||||
}
|
||||
return cloned;
|
||||
}
|
||||
|
||||
function normalizeCwd(rawCwd: string): string {
|
||||
const resolved = path.resolve(rawCwd.trim());
|
||||
const normalized = path.normalize(resolved);
|
||||
@@ -68,10 +48,7 @@ export class ProjectRegistry {
|
||||
}
|
||||
|
||||
list(): ProjectListResult {
|
||||
return this.projects.map((project) => ({
|
||||
...project,
|
||||
scripts: cloneScripts(project.scripts),
|
||||
}));
|
||||
return this.projects.map((project) => ({ ...project }));
|
||||
}
|
||||
|
||||
add(raw: ProjectAddInput): ProjectAddResult {
|
||||
@@ -83,13 +60,7 @@ export class ProjectRegistry {
|
||||
|
||||
const existing = this.projects.find((project) => normalizeCwd(project.cwd) === normalizedCwd);
|
||||
if (existing) {
|
||||
return {
|
||||
project: {
|
||||
...existing,
|
||||
scripts: cloneScripts(existing.scripts),
|
||||
},
|
||||
created: false,
|
||||
};
|
||||
return { project: { ...existing }, created: false };
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
@@ -97,20 +68,13 @@ export class ProjectRegistry {
|
||||
id: randomUUID(),
|
||||
cwd: normalizedCwd,
|
||||
name: inferProjectName(normalizedCwd),
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
this.projects = [project, ...this.projects];
|
||||
this.persist();
|
||||
return {
|
||||
project: {
|
||||
...project,
|
||||
scripts: cloneScripts(project.scripts),
|
||||
},
|
||||
created: true,
|
||||
};
|
||||
return { project: { ...project }, created: true };
|
||||
}
|
||||
|
||||
remove(raw: ProjectRemoveInput): void {
|
||||
@@ -124,31 +88,6 @@ export class ProjectRegistry {
|
||||
this.persist();
|
||||
}
|
||||
|
||||
updateScripts(raw: ProjectUpdateScriptsInput): ProjectUpdateScriptsResult {
|
||||
const input = projectUpdateScriptsInputSchema.parse(raw);
|
||||
const index = this.projects.findIndex((project) => project.id === input.id);
|
||||
if (index < 0) {
|
||||
throw new Error(`Project not found: ${input.id}`);
|
||||
}
|
||||
|
||||
const nextScripts = normalizeProjectScripts(projectScriptsSchema.parse(input.scripts));
|
||||
const nextUpdatedAt = new Date().toISOString();
|
||||
const nextProject: ProjectRecord = {
|
||||
...this.projects[index]!,
|
||||
scripts: nextScripts,
|
||||
updatedAt: nextUpdatedAt,
|
||||
};
|
||||
|
||||
const nextProjects = [...this.projects];
|
||||
nextProjects[index] = nextProject;
|
||||
this.projects = nextProjects;
|
||||
this.persist();
|
||||
|
||||
return {
|
||||
project: { ...nextProject, scripts: cloneScripts(nextProject.scripts) },
|
||||
};
|
||||
}
|
||||
|
||||
private loadFromDisk(): ProjectRecord[] {
|
||||
const loaded = this.readPersistedProjects();
|
||||
const deduped = new Map<string, ProjectRecord>();
|
||||
@@ -168,7 +107,6 @@ export class ProjectRegistry {
|
||||
cwd: normalizedCwd,
|
||||
name:
|
||||
project.name.trim().length > 0 ? project.name.trim() : inferProjectName(normalizedCwd),
|
||||
scripts: normalizeProjectScripts(project.scripts),
|
||||
};
|
||||
deduped.set(normalizedCwd, normalizedProject);
|
||||
normalizedProjects.push(normalizedProject);
|
||||
@@ -183,7 +121,6 @@ export class ProjectRegistry {
|
||||
source.id !== project.id ||
|
||||
source.cwd !== project.cwd ||
|
||||
source.name !== project.name ||
|
||||
JSON.stringify(source.scripts) !== JSON.stringify(project.scripts) ||
|
||||
source.createdAt !== project.createdAt ||
|
||||
source.updatedAt !== project.updatedAt
|
||||
);
|
||||
|
||||
@@ -763,6 +763,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
const pendingHistory = this.pendingPersistHistory.get(persistenceKey);
|
||||
if (pendingHistory !== undefined) {
|
||||
this.pendingPersistHistory.delete(persistenceKey);
|
||||
// oxlint-disable-next-line no-await-in-loop
|
||||
await this.enqueuePersistWrite(threadId, terminalId, pendingHistory);
|
||||
}
|
||||
|
||||
@@ -770,6 +771,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
if (!pending) {
|
||||
return;
|
||||
}
|
||||
// oxlint-disable-next-line no-await-in-loop
|
||||
await pending.catch(() => undefined);
|
||||
}
|
||||
}
|
||||
@@ -954,6 +956,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
|
||||
private async runWithThreadLock<T>(threadId: string, task: () => Promise<T>): Promise<T> {
|
||||
const previous = this.threadLocks.get(threadId) ?? Promise.resolve();
|
||||
// oxlint-disable-next-line unicorn/consistent-function-scoping
|
||||
let release: () => void = () => {};
|
||||
const current = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
import { assert, beforeEach, describe, it, vi } from "vitest";
|
||||
import type { ProcessRunOptions, ProcessRunResult } from "./processRunner";
|
||||
|
||||
const { runProcessMock } = vi.hoisted(() => ({
|
||||
runProcessMock: vi.fn<
|
||||
(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options?: ProcessRunOptions,
|
||||
) => Promise<ProcessRunResult>
|
||||
>(),
|
||||
}));
|
||||
|
||||
vi.mock("./processRunner", () => ({
|
||||
runProcess: runProcessMock,
|
||||
}));
|
||||
|
||||
function processResult(
|
||||
overrides: Partial<ProcessRunResult> & Pick<ProcessRunResult, "stdout" | "code">,
|
||||
): ProcessRunResult {
|
||||
return {
|
||||
stdout: overrides.stdout,
|
||||
code: overrides.code,
|
||||
stderr: overrides.stderr ?? "",
|
||||
signal: overrides.signal ?? null,
|
||||
timedOut: overrides.timedOut ?? false,
|
||||
stdoutTruncated: overrides.stdoutTruncated ?? false,
|
||||
stderrTruncated: overrides.stderrTruncated ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
describe("searchWorkspaceEntries git-ignore chunking", () => {
|
||||
beforeEach(() => {
|
||||
runProcessMock.mockReset();
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it("chunks git check-ignore stdin to avoid building giant strings", async () => {
|
||||
const ignoredPaths = Array.from(
|
||||
{ length: 5000 },
|
||||
(_, index) => `ignored/${index.toString().padStart(5, "0")}/${"x".repeat(80)}.ts`,
|
||||
);
|
||||
const keptPaths = ["src/keep.ts", "docs/readme.md"];
|
||||
const listedPaths = [...ignoredPaths, ...keptPaths];
|
||||
let checkIgnoreCalls = 0;
|
||||
|
||||
runProcessMock.mockImplementation(async (_command, args, options) => {
|
||||
if (args[0] === "rev-parse") {
|
||||
return processResult({ code: 0, stdout: "true\n" });
|
||||
}
|
||||
|
||||
if (args[0] === "ls-files") {
|
||||
return processResult({ code: 0, stdout: `${listedPaths.join("\0")}\0` });
|
||||
}
|
||||
|
||||
if (args[0] === "check-ignore") {
|
||||
checkIgnoreCalls += 1;
|
||||
const chunkPaths = (options?.stdin ?? "").split("\0").filter((value) => value.length > 0);
|
||||
const chunkIgnored = chunkPaths.filter((value) => value.startsWith("ignored/"));
|
||||
return processResult({
|
||||
code: chunkIgnored.length > 0 ? 0 : 1,
|
||||
stdout: chunkIgnored.length > 0 ? `${chunkIgnored.join("\0")}\0` : "",
|
||||
});
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected command: git ${args.join(" ")}`);
|
||||
});
|
||||
|
||||
const { searchWorkspaceEntries } = await import("./workspaceEntries");
|
||||
const result = await searchWorkspaceEntries({
|
||||
cwd: "/virtual/workspace",
|
||||
query: "",
|
||||
limit: 100,
|
||||
});
|
||||
|
||||
assert.isAbove(checkIgnoreCalls, 1);
|
||||
assert.isFalse(result.entries.some((entry) => entry.path.startsWith("ignored/")));
|
||||
assert.isTrue(result.entries.some((entry) => entry.path === "src/keep.ts"));
|
||||
});
|
||||
});
|
||||
@@ -1,176 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import fsPromises from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
import { afterEach, assert, describe, it, vi } from "vitest";
|
||||
|
||||
import { searchWorkspaceEntries } from "./workspaceEntries";
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
function writeFile(cwd: string, relativePath: string, contents = ""): void {
|
||||
const absolutePath = path.join(cwd, relativePath);
|
||||
fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
|
||||
fs.writeFileSync(absolutePath, contents, "utf8");
|
||||
}
|
||||
|
||||
function runGit(cwd: string, args: string[]): void {
|
||||
const result = spawnSync("git", args, { cwd, encoding: "utf8" });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(result.stderr || `git ${args.join(" ")} failed`);
|
||||
}
|
||||
}
|
||||
|
||||
describe("searchWorkspaceEntries", () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns files and directories relative to cwd", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-entries-");
|
||||
writeFile(cwd, "src/components/Composer.tsx");
|
||||
writeFile(cwd, "src/index.ts");
|
||||
writeFile(cwd, "README.md");
|
||||
writeFile(cwd, ".git/HEAD");
|
||||
writeFile(cwd, "node_modules/pkg/index.js");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.include(paths, "src");
|
||||
assert.include(paths, "src/components");
|
||||
assert.include(paths, "src/components/Composer.tsx");
|
||||
assert.include(paths, "README.md");
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".git")));
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith("node_modules")));
|
||||
assert.isFalse(result.truncated);
|
||||
});
|
||||
|
||||
it("filters and ranks entries by query", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-query-");
|
||||
writeFile(cwd, "src/components/Composer.tsx");
|
||||
writeFile(cwd, "src/components/composePrompt.ts");
|
||||
writeFile(cwd, "docs/composition.md");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "compo", limit: 5 });
|
||||
|
||||
assert.isAbove(result.entries.length, 0);
|
||||
assert.isTrue(result.entries.some((entry) => entry.path === "src/components"));
|
||||
assert.isTrue(result.entries.every((entry) => entry.path.toLowerCase().includes("compo")));
|
||||
});
|
||||
|
||||
it("excludes gitignored paths for git repositories", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-gitignore-");
|
||||
runGit(cwd, ["init"]);
|
||||
writeFile(cwd, ".gitignore", ".convex/\nconvex/\nignored.txt\n");
|
||||
writeFile(cwd, "src/keep.ts", "export {};");
|
||||
writeFile(cwd, "ignored.txt", "ignore me");
|
||||
writeFile(cwd, ".convex/local-storage/data.json", "{}");
|
||||
writeFile(cwd, "convex/UOoS-l/convex_local_storage/modules/data.json", "{}");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.include(paths, "src");
|
||||
assert.include(paths, "src/keep.ts");
|
||||
assert.notInclude(paths, "ignored.txt");
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/")));
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith("convex/")));
|
||||
});
|
||||
|
||||
it("excludes tracked paths that match ignore rules", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-tracked-gitignore-");
|
||||
runGit(cwd, ["init"]);
|
||||
writeFile(cwd, ".convex/local-storage/data.json", "{}");
|
||||
writeFile(cwd, "src/keep.ts", "export {};");
|
||||
runGit(cwd, ["add", ".convex/local-storage/data.json", "src/keep.ts"]);
|
||||
writeFile(cwd, ".gitignore", ".convex/\n");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.include(paths, "src");
|
||||
assert.include(paths, "src/keep.ts");
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/")));
|
||||
});
|
||||
|
||||
it("excludes .convex in non-git workspaces", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-non-git-convex-");
|
||||
writeFile(cwd, ".convex/local-storage/data.json", "{}");
|
||||
writeFile(cwd, "src/keep.ts", "export {};");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.include(paths, "src");
|
||||
assert.include(paths, "src/keep.ts");
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/")));
|
||||
});
|
||||
|
||||
it("deduplicates concurrent index builds for the same cwd", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-concurrent-build-");
|
||||
writeFile(cwd, "src/components/Composer.tsx");
|
||||
|
||||
let rootReadCount = 0;
|
||||
const originalReaddir = fsPromises.readdir.bind(fsPromises);
|
||||
vi.spyOn(fsPromises, "readdir").mockImplementation(
|
||||
(async (...args: Parameters<typeof fsPromises.readdir>) => {
|
||||
if (args[0] === cwd) {
|
||||
rootReadCount += 1;
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
}
|
||||
return originalReaddir(...args);
|
||||
}) as typeof fsPromises.readdir,
|
||||
);
|
||||
|
||||
await Promise.all([
|
||||
searchWorkspaceEntries({ cwd, query: "", limit: 100 }),
|
||||
searchWorkspaceEntries({ cwd, query: "comp", limit: 100 }),
|
||||
searchWorkspaceEntries({ cwd, query: "src", limit: 100 }),
|
||||
]);
|
||||
|
||||
assert.equal(rootReadCount, 1);
|
||||
});
|
||||
|
||||
it("limits concurrent directory reads while walking the filesystem", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-read-concurrency-");
|
||||
for (let index = 0; index < 80; index += 1) {
|
||||
writeFile(cwd, `group-${index}/entry-${index}.ts`, "export {};");
|
||||
}
|
||||
|
||||
let activeReads = 0;
|
||||
let peakReads = 0;
|
||||
const originalReaddir = fsPromises.readdir.bind(fsPromises);
|
||||
vi.spyOn(fsPromises, "readdir").mockImplementation(
|
||||
(async (...args: Parameters<typeof fsPromises.readdir>) => {
|
||||
const target = args[0];
|
||||
if (typeof target === "string" && target.startsWith(cwd)) {
|
||||
activeReads += 1;
|
||||
peakReads = Math.max(peakReads, activeReads);
|
||||
await new Promise((resolve) => setTimeout(resolve, 4));
|
||||
try {
|
||||
return await originalReaddir(...args);
|
||||
} finally {
|
||||
activeReads -= 1;
|
||||
}
|
||||
}
|
||||
return originalReaddir(...args);
|
||||
}) as typeof fsPromises.readdir,
|
||||
);
|
||||
|
||||
await searchWorkspaceEntries({ cwd, query: "", limit: 200 });
|
||||
|
||||
assert.isAtMost(peakReads, 32);
|
||||
});
|
||||
});
|
||||
@@ -1,433 +0,0 @@
|
||||
import fs from "node:fs/promises";
|
||||
import type { Dirent } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { runProcess } from "./processRunner";
|
||||
|
||||
import {
|
||||
projectSearchEntriesInputSchema,
|
||||
type ProjectEntry,
|
||||
type ProjectSearchEntriesInput,
|
||||
type ProjectSearchEntriesResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
const WORKSPACE_CACHE_TTL_MS = 15_000;
|
||||
const WORKSPACE_CACHE_MAX_KEYS = 4;
|
||||
const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
|
||||
const WORKSPACE_SCAN_READDIR_CONCURRENCY = 32;
|
||||
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
|
||||
const IGNORED_DIRECTORY_NAMES = new Set([
|
||||
".git",
|
||||
".convex",
|
||||
"node_modules",
|
||||
".next",
|
||||
".turbo",
|
||||
"dist",
|
||||
"build",
|
||||
"out",
|
||||
".cache",
|
||||
]);
|
||||
|
||||
interface WorkspaceIndex {
|
||||
scannedAt: number;
|
||||
entries: ProjectEntry[];
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
const workspaceIndexCache = new Map<string, WorkspaceIndex>();
|
||||
const inFlightWorkspaceIndexBuilds = new Map<string, Promise<WorkspaceIndex>>();
|
||||
|
||||
function toPosixPath(input: string): string {
|
||||
return input.split(path.sep).join("/");
|
||||
}
|
||||
|
||||
function parentPathOf(input: string): string | undefined {
|
||||
const separatorIndex = input.lastIndexOf("/");
|
||||
if (separatorIndex === -1) {
|
||||
return undefined;
|
||||
}
|
||||
return input.slice(0, separatorIndex);
|
||||
}
|
||||
|
||||
function basenameOf(input: string): string {
|
||||
const separatorIndex = input.lastIndexOf("/");
|
||||
if (separatorIndex === -1) {
|
||||
return input;
|
||||
}
|
||||
return input.slice(separatorIndex + 1);
|
||||
}
|
||||
|
||||
function normalizeQuery(input: string): string {
|
||||
return input
|
||||
.trim()
|
||||
.replace(/^[@./]+/, "")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function scoreEntry(entry: ProjectEntry, query: string): number {
|
||||
if (!query) {
|
||||
return entry.kind === "directory" ? 0 : 1;
|
||||
}
|
||||
|
||||
const normalizedPath = entry.path.toLowerCase();
|
||||
const normalizedName = basenameOf(normalizedPath);
|
||||
|
||||
if (normalizedName === query) return 0;
|
||||
if (normalizedPath === query) return 1;
|
||||
if (normalizedName.startsWith(query)) return 2;
|
||||
if (normalizedPath.startsWith(query)) return 3;
|
||||
if (normalizedPath.includes(`/${query}`)) return 4;
|
||||
return 5;
|
||||
}
|
||||
|
||||
function isPathInIgnoredDirectory(relativePath: string): boolean {
|
||||
const firstSegment = relativePath.split("/")[0];
|
||||
if (!firstSegment) return false;
|
||||
return IGNORED_DIRECTORY_NAMES.has(firstSegment);
|
||||
}
|
||||
|
||||
function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
|
||||
const parts = input.split("\0");
|
||||
if (parts.length === 0) return [];
|
||||
|
||||
// If output was truncated, the final token can be partial.
|
||||
if (truncated && parts[parts.length - 1]?.length) {
|
||||
parts.pop();
|
||||
}
|
||||
|
||||
return parts.filter((value) => value.length > 0);
|
||||
}
|
||||
|
||||
function directoryAncestorsOf(relativePath: string): string[] {
|
||||
const segments = relativePath.split("/").filter((segment) => segment.length > 0);
|
||||
if (segments.length <= 1) return [];
|
||||
const directories: string[] = [];
|
||||
for (let index = 1; index < segments.length; index += 1) {
|
||||
directories.push(segments.slice(0, index).join("/"));
|
||||
}
|
||||
return directories;
|
||||
}
|
||||
|
||||
async function mapWithConcurrency<TInput, TOutput>(
|
||||
items: readonly TInput[],
|
||||
concurrency: number,
|
||||
mapper: (item: TInput, index: number) => Promise<TOutput>,
|
||||
): Promise<TOutput[]> {
|
||||
if (items.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const boundedConcurrency = Math.max(1, Math.min(concurrency, items.length));
|
||||
const results = Array.from({ length: items.length }) as TOutput[];
|
||||
let nextIndex = 0;
|
||||
|
||||
const workers = Array.from({ length: boundedConcurrency }, async () => {
|
||||
while (nextIndex < items.length) {
|
||||
const currentIndex = nextIndex;
|
||||
nextIndex += 1;
|
||||
results[currentIndex] = await mapper(items[currentIndex] as TInput, currentIndex);
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(workers);
|
||||
return results;
|
||||
}
|
||||
|
||||
async function isInsideGitWorkTree(cwd: string): Promise<boolean> {
|
||||
const insideWorkTree = await runProcess("git", ["rev-parse", "--is-inside-work-tree"], {
|
||||
cwd,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxBufferBytes: 4_096,
|
||||
}).catch(() => null);
|
||||
return Boolean(
|
||||
insideWorkTree && insideWorkTree.code === 0 && insideWorkTree.stdout.trim() === "true",
|
||||
);
|
||||
}
|
||||
|
||||
async function filterGitIgnoredPaths(cwd: string, relativePaths: string[]): Promise<string[]> {
|
||||
if (relativePaths.length === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
const ignoredPaths = new Set<string>();
|
||||
let chunk: string[] = [];
|
||||
let chunkBytes = 0;
|
||||
|
||||
const flushChunk = async (): Promise<boolean> => {
|
||||
if (chunk.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const checkIgnore = await runProcess("git", ["check-ignore", "--no-index", "-z", "--stdin"], {
|
||||
cwd,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxBufferBytes: 16 * 1024 * 1024,
|
||||
outputMode: "truncate",
|
||||
stdin: `${chunk.join("\0")}\0`,
|
||||
}).catch(() => null);
|
||||
chunk = [];
|
||||
chunkBytes = 0;
|
||||
|
||||
if (!checkIgnore) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// git-check-ignore exits with 1 when no paths match.
|
||||
if (checkIgnore.code !== 0 && checkIgnore.code !== 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const matchedIgnoredPaths = splitNullSeparatedPaths(
|
||||
checkIgnore.stdout,
|
||||
Boolean(checkIgnore.stdoutTruncated),
|
||||
);
|
||||
for (const ignoredPath of matchedIgnoredPaths) {
|
||||
ignoredPaths.add(ignoredPath);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
for (const relativePath of relativePaths) {
|
||||
const relativePathBytes = Buffer.byteLength(relativePath) + 1;
|
||||
if (
|
||||
chunk.length > 0 &&
|
||||
chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES &&
|
||||
!(await flushChunk())
|
||||
) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
chunk.push(relativePath);
|
||||
chunkBytes += relativePathBytes;
|
||||
|
||||
if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES && !(await flushChunk())) {
|
||||
return relativePaths;
|
||||
}
|
||||
}
|
||||
|
||||
if (!(await flushChunk())) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
if (ignoredPaths.size === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
|
||||
}
|
||||
|
||||
async function buildWorkspaceIndexFromGit(cwd: string): Promise<WorkspaceIndex | null> {
|
||||
if (!(await isInsideGitWorkTree(cwd))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const listedFiles = await runProcess(
|
||||
"git",
|
||||
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
||||
{
|
||||
cwd,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxBufferBytes: 16 * 1024 * 1024,
|
||||
outputMode: "truncate",
|
||||
},
|
||||
).catch(() => null);
|
||||
if (!listedFiles || listedFiles.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const listedPaths = splitNullSeparatedPaths(
|
||||
listedFiles.stdout,
|
||||
Boolean(listedFiles.stdoutTruncated),
|
||||
)
|
||||
.map((entry) => toPosixPath(entry))
|
||||
.filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry));
|
||||
const filePaths = await filterGitIgnoredPaths(cwd, listedPaths);
|
||||
|
||||
const directorySet = new Set<string>();
|
||||
for (const filePath of filePaths) {
|
||||
for (const directoryPath of directoryAncestorsOf(filePath)) {
|
||||
if (!isPathInIgnoredDirectory(directoryPath)) {
|
||||
directorySet.add(directoryPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const directoryEntries: ProjectEntry[] = [...directorySet]
|
||||
.toSorted((left, right) => left.localeCompare(right))
|
||||
.map((directoryPath) => ({
|
||||
path: directoryPath,
|
||||
kind: "directory",
|
||||
parentPath: parentPathOf(directoryPath),
|
||||
}));
|
||||
const fileEntries: ProjectEntry[] = [...new Set(filePaths)]
|
||||
.toSorted((left, right) => left.localeCompare(right))
|
||||
.map((filePath) => ({
|
||||
path: filePath,
|
||||
kind: "file",
|
||||
parentPath: parentPathOf(filePath),
|
||||
}));
|
||||
|
||||
const entries = [...directoryEntries, ...fileEntries];
|
||||
return {
|
||||
scannedAt: Date.now(),
|
||||
entries: entries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES),
|
||||
truncated: Boolean(listedFiles.stdoutTruncated) || entries.length > WORKSPACE_INDEX_MAX_ENTRIES,
|
||||
};
|
||||
}
|
||||
|
||||
async function buildWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
|
||||
const gitIndexed = await buildWorkspaceIndexFromGit(cwd);
|
||||
if (gitIndexed) {
|
||||
return gitIndexed;
|
||||
}
|
||||
const shouldFilterWithGitIgnore = await isInsideGitWorkTree(cwd);
|
||||
|
||||
let pendingDirectories: string[] = [""];
|
||||
const entries: ProjectEntry[] = [];
|
||||
let truncated = false;
|
||||
|
||||
while (pendingDirectories.length > 0 && !truncated) {
|
||||
const currentDirectories = pendingDirectories;
|
||||
pendingDirectories = [];
|
||||
const directoryEntries = await mapWithConcurrency(
|
||||
currentDirectories,
|
||||
WORKSPACE_SCAN_READDIR_CONCURRENCY,
|
||||
async (relativeDir) => {
|
||||
const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd;
|
||||
try {
|
||||
const dirents = await fs.readdir(absoluteDir, { withFileTypes: true });
|
||||
return { relativeDir, dirents };
|
||||
} catch (error) {
|
||||
if (!relativeDir) {
|
||||
throw new Error(
|
||||
`Unable to scan workspace entries at '${cwd}': ${error instanceof Error ? error.message : "unknown error"}`,
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
return { relativeDir, dirents: null };
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => {
|
||||
const { relativeDir, dirents } = directoryEntry;
|
||||
if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>;
|
||||
|
||||
dirents.sort((left, right) => left.name.localeCompare(right.name));
|
||||
const candidates: Array<{ dirent: Dirent; relativePath: string }> = [];
|
||||
for (const dirent of dirents) {
|
||||
if (!dirent.name || dirent.name === "." || dirent.name === "..") {
|
||||
continue;
|
||||
}
|
||||
if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) {
|
||||
continue;
|
||||
}
|
||||
if (!dirent.isDirectory() && !dirent.isFile()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const relativePath = toPosixPath(
|
||||
relativeDir ? path.join(relativeDir, dirent.name) : dirent.name,
|
||||
);
|
||||
if (isPathInIgnoredDirectory(relativePath)) {
|
||||
continue;
|
||||
}
|
||||
candidates.push({ dirent, relativePath });
|
||||
}
|
||||
return candidates;
|
||||
});
|
||||
|
||||
const candidatePaths = candidateEntriesByDirectory.flatMap((candidateEntries) =>
|
||||
candidateEntries.map((entry) => entry.relativePath),
|
||||
);
|
||||
const allowedPathSet = shouldFilterWithGitIgnore
|
||||
? new Set(await filterGitIgnoredPaths(cwd, candidatePaths))
|
||||
: null;
|
||||
|
||||
for (const candidateEntries of candidateEntriesByDirectory) {
|
||||
for (const candidate of candidateEntries) {
|
||||
if (allowedPathSet && !allowedPathSet.has(candidate.relativePath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const entry: ProjectEntry = {
|
||||
path: candidate.relativePath,
|
||||
kind: candidate.dirent.isDirectory() ? "directory" : "file",
|
||||
parentPath: parentPathOf(candidate.relativePath),
|
||||
};
|
||||
entries.push(entry);
|
||||
|
||||
if (candidate.dirent.isDirectory()) {
|
||||
pendingDirectories.push(candidate.relativePath);
|
||||
}
|
||||
|
||||
if (entries.length >= WORKSPACE_INDEX_MAX_ENTRIES) {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (truncated) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
scannedAt: Date.now(),
|
||||
entries,
|
||||
truncated,
|
||||
};
|
||||
}
|
||||
|
||||
async function getWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
|
||||
const cached = workspaceIndexCache.get(cwd);
|
||||
if (cached && Date.now() - cached.scannedAt < WORKSPACE_CACHE_TTL_MS) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const inFlight = inFlightWorkspaceIndexBuilds.get(cwd);
|
||||
if (inFlight) {
|
||||
return inFlight;
|
||||
}
|
||||
|
||||
const nextPromise = buildWorkspaceIndex(cwd)
|
||||
.then((next) => {
|
||||
workspaceIndexCache.set(cwd, next);
|
||||
while (workspaceIndexCache.size > WORKSPACE_CACHE_MAX_KEYS) {
|
||||
const oldestKey = workspaceIndexCache.keys().next().value;
|
||||
if (!oldestKey) break;
|
||||
workspaceIndexCache.delete(oldestKey);
|
||||
}
|
||||
return next;
|
||||
})
|
||||
.finally(() => {
|
||||
inFlightWorkspaceIndexBuilds.delete(cwd);
|
||||
});
|
||||
inFlightWorkspaceIndexBuilds.set(cwd, nextPromise);
|
||||
return nextPromise;
|
||||
}
|
||||
|
||||
export async function searchWorkspaceEntries(
|
||||
input: ProjectSearchEntriesInput,
|
||||
): Promise<ProjectSearchEntriesResult> {
|
||||
const parsed = projectSearchEntriesInputSchema.parse(input);
|
||||
const index = await getWorkspaceIndex(parsed.cwd);
|
||||
const normalizedQuery = normalizeQuery(parsed.query);
|
||||
const candidates = normalizedQuery
|
||||
? index.entries.filter((entry) => entry.path.toLowerCase().includes(normalizedQuery))
|
||||
: index.entries;
|
||||
|
||||
const ranked = candidates.toSorted((left, right) => {
|
||||
const scoreDelta = scoreEntry(left, normalizedQuery) - scoreEntry(right, normalizedQuery);
|
||||
if (scoreDelta !== 0) return scoreDelta;
|
||||
return left.path.localeCompare(right.path);
|
||||
});
|
||||
|
||||
return {
|
||||
entries: ranked.slice(0, parsed.limit),
|
||||
truncated: index.truncated || ranked.length > parsed.limit,
|
||||
};
|
||||
}
|
||||
@@ -133,7 +133,7 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
|
||||
this.sessions.delete(this.key(input.threadId, input.terminalId));
|
||||
return;
|
||||
}
|
||||
for (const key of [...this.sessions.keys()]) {
|
||||
for (const key of this.sessions.keys()) {
|
||||
if (key.startsWith(`${input.threadId}\u0000`)) {
|
||||
this.sessions.delete(key);
|
||||
}
|
||||
@@ -188,6 +188,7 @@ async function sendRequest(ws: WebSocket, method: string, params?: unknown): Pro
|
||||
|
||||
// Wait for response with matching id
|
||||
while (true) {
|
||||
// oxlint-disable-next-line no-await-in-loop
|
||||
const parsed = (await waitForMessage(ws)) as Record<string, unknown>;
|
||||
if (parsed.id === id) {
|
||||
return parsed as WsResponse;
|
||||
@@ -491,59 +492,6 @@ describe("WebSocket Server", () => {
|
||||
expect(secondResponse.result).toEqual(firstResponse.result);
|
||||
});
|
||||
|
||||
it("upserts keybinding rules and updates cached server config", async () => {
|
||||
const fakeHome = makeTempDir("t3code-home-upsert-keybinding-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
const keybindingsPath = path.join(configDir, "keybindings.json");
|
||||
fs.writeFileSync(
|
||||
keybindingsPath,
|
||||
JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
|
||||
"utf8",
|
||||
);
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
server = createTestServer({ cwd: "/my/workspace" });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const upsertResponse = await sendRequest(ws, WS_METHODS.serverUpsertKeybinding, {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
expect(upsertResponse.error).toBeUndefined();
|
||||
expect(upsertResponse.result).toEqual({
|
||||
keybindings: mergeWithDefaultsForTest([
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
]),
|
||||
});
|
||||
|
||||
const persistedConfig = JSON.parse(fs.readFileSync(keybindingsPath, "utf8")) as Array<{
|
||||
key: string;
|
||||
command: string;
|
||||
}>;
|
||||
expect(persistedConfig).toEqual([
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
]);
|
||||
|
||||
const configResponse = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
||||
expect(configResponse.error).toBeUndefined();
|
||||
expect(configResponse.result).toEqual({
|
||||
cwd: "/my/workspace",
|
||||
keybindings: mergeWithDefaultsForTest([
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
]),
|
||||
});
|
||||
});
|
||||
|
||||
it("warns and ignores unsupported keybindings config format", async () => {
|
||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const fakeHome = makeTempDir("t3code-home-unsupported-format-");
|
||||
@@ -809,42 +757,6 @@ describe("WebSocket Server", () => {
|
||||
expect(projectId).toBeTruthy();
|
||||
if (!projectId) return;
|
||||
|
||||
const updatedScripts = await sendRequest(ws, WS_METHODS.projectsUpdateScripts, {
|
||||
id: projectId,
|
||||
scripts: [
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
command: "bun install",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(updatedScripts.error).toBeUndefined();
|
||||
const scriptPayload = (
|
||||
updatedScripts.result as {
|
||||
project: {
|
||||
scripts: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
command: string;
|
||||
icon: string;
|
||||
runOnWorktreeCreate: boolean;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
).project.scripts;
|
||||
expect(scriptPayload).toEqual([
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
command: "bun install",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
]);
|
||||
|
||||
const removed = await sendRequest(ws, WS_METHODS.projectsRemove, {
|
||||
id: projectId,
|
||||
});
|
||||
@@ -855,38 +767,6 @@ describe("WebSocket Server", () => {
|
||||
expect(afterRemove.result).toEqual([]);
|
||||
});
|
||||
|
||||
it("supports projects.searchEntries", async () => {
|
||||
const workspace = makeTempDir("t3code-ws-workspace-entries-");
|
||||
fs.mkdirSync(path.join(workspace, "src", "components"), { recursive: true });
|
||||
fs.writeFileSync(path.join(workspace, "src", "components", "Composer.tsx"), "export {};", "utf8");
|
||||
fs.writeFileSync(path.join(workspace, "README.md"), "# test", "utf8");
|
||||
fs.mkdirSync(path.join(workspace, ".git"), { recursive: true });
|
||||
fs.writeFileSync(path.join(workspace, ".git", "HEAD"), "ref: refs/heads/main\n", "utf8");
|
||||
|
||||
server = createTestServer({ cwd: "/test" });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const response = await sendRequest(ws, WS_METHODS.projectsSearchEntries, {
|
||||
cwd: workspace,
|
||||
query: "comp",
|
||||
limit: 10,
|
||||
});
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual({
|
||||
entries: expect.arrayContaining([
|
||||
expect.objectContaining({ path: "src/components", kind: "directory" }),
|
||||
expect.objectContaining({ path: "src/components/Composer.tsx", kind: "file" }),
|
||||
]),
|
||||
truncated: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("supports git methods over websocket", async () => {
|
||||
const repoCwd = makeTempDir("t3code-ws-git-project-");
|
||||
|
||||
|
||||
+22
-35
@@ -31,8 +31,7 @@ import {
|
||||
removeGitWorktree,
|
||||
} from "./git";
|
||||
import { TerminalManager } from "./terminalManager";
|
||||
import { loadResolvedKeybindingsConfig, upsertKeybindingRule } from "./keybindings";
|
||||
import { searchWorkspaceEntries } from "./workspaceEntries";
|
||||
import { loadResolvedKeybindingsConfig } from "./keybindings";
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
@@ -70,6 +69,26 @@ function parseBooleanEnv(value: string | undefined): boolean | undefined {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void {
|
||||
socket.write(
|
||||
`HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` +
|
||||
"Connection: close\r\n" +
|
||||
"Content-Type: text/plain\r\n" +
|
||||
`Content-Length: ${Buffer.byteLength(message)}\r\n` +
|
||||
"\r\n" +
|
||||
message,
|
||||
);
|
||||
socket.destroy();
|
||||
}
|
||||
|
||||
const isServerNotRunningError = (error: unknown): boolean => {
|
||||
if (!(error instanceof Error)) return false;
|
||||
const maybeCode = (error as NodeJS.ErrnoException).code;
|
||||
return (
|
||||
maybeCode === "ERR_SERVER_NOT_RUNNING" || error.message.toLowerCase().includes("not running")
|
||||
);
|
||||
};
|
||||
|
||||
export function createServer(options: ServerOptions) {
|
||||
const {
|
||||
port,
|
||||
@@ -92,7 +111,7 @@ export function createServer(options: ServerOptions) {
|
||||
const logger = createLogger("ws");
|
||||
const logWebSocketEvents =
|
||||
explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl);
|
||||
let keybindingsConfig = loadResolvedKeybindingsConfig(logger);
|
||||
const keybindingsConfig = loadResolvedKeybindingsConfig(logger);
|
||||
|
||||
function logOutgoingPush(push: WsPush, recipients: number) {
|
||||
if (!logWebSocketEvents) return;
|
||||
@@ -198,18 +217,6 @@ export function createServer(options: ServerOptions) {
|
||||
// WebSocket server — upgrades from the HTTP server
|
||||
const wss = new WebSocketServer({ noServer: true });
|
||||
|
||||
function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void {
|
||||
socket.write(
|
||||
`HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` +
|
||||
"Connection: close\r\n" +
|
||||
"Content-Type: text/plain\r\n" +
|
||||
`Content-Length: ${Buffer.byteLength(message)}\r\n` +
|
||||
"\r\n" +
|
||||
message,
|
||||
);
|
||||
socket.destroy();
|
||||
}
|
||||
|
||||
httpServer.on("upgrade", (request, socket, head) => {
|
||||
if (authToken) {
|
||||
let providedToken: string | null = null;
|
||||
@@ -320,11 +327,6 @@ export function createServer(options: ServerOptions) {
|
||||
projectRegistry.remove(request.params as never);
|
||||
return undefined;
|
||||
|
||||
case WS_METHODS.projectsSearchEntries:
|
||||
return searchWorkspaceEntries(request.params as never);
|
||||
case WS_METHODS.projectsUpdateScripts:
|
||||
return projectRegistry.updateScripts(request.params as never);
|
||||
|
||||
case WS_METHODS.shellOpenInEditor: {
|
||||
const params = request.params as {
|
||||
cwd: string;
|
||||
@@ -423,12 +425,6 @@ export function createServer(options: ServerOptions) {
|
||||
keybindings: keybindingsConfig,
|
||||
};
|
||||
|
||||
case WS_METHODS.serverUpsertKeybinding:
|
||||
keybindingsConfig = upsertKeybindingRule(logger, request.params);
|
||||
return {
|
||||
keybindings: keybindingsConfig,
|
||||
};
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown method: ${request.method}`);
|
||||
}
|
||||
@@ -464,15 +460,6 @@ export function createServer(options: ServerOptions) {
|
||||
}
|
||||
clients.clear();
|
||||
|
||||
const isServerNotRunningError = (error: unknown): boolean => {
|
||||
if (!(error instanceof Error)) return false;
|
||||
const maybeCode = (error as NodeJS.ErrnoException).code;
|
||||
return (
|
||||
maybeCode === "ERR_SERVER_NOT_RUNNING" ||
|
||||
error.message.toLowerCase().includes("not running")
|
||||
);
|
||||
};
|
||||
|
||||
const closeWebSocketServer = new Promise<void>((resolve, reject) => {
|
||||
wss.close((error) => {
|
||||
if (error && !isServerNotRunningError(error)) {
|
||||
|
||||
@@ -6,7 +6,6 @@ export default defineConfig({
|
||||
outDir: "dist",
|
||||
sourcemap: true,
|
||||
clean: true,
|
||||
noExternal: ["@t3tools/contracts", "zod"],
|
||||
inlineOnly: false,
|
||||
banner: {
|
||||
js: "#!/usr/bin/env node\n",
|
||||
|
||||
@@ -13,8 +13,8 @@
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
"@tanstack/react-virtual": "^3.13.18",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
|
||||
+19
-4
@@ -85,7 +85,6 @@ function AutoProjectBootstrap() {
|
||||
cwd: payload.cwd,
|
||||
model: DEFAULT_MODEL,
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
});
|
||||
dispatch({
|
||||
@@ -125,12 +124,19 @@ function AutoProjectBootstrap() {
|
||||
|
||||
function DesktopProjectBootstrap() {
|
||||
const api = useNativeApi();
|
||||
const { dispatch } = useStore();
|
||||
const { state, dispatch } = useStore();
|
||||
const bootstrappedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isElectron || !api || bootstrappedRef.current) return;
|
||||
|
||||
const perfAutomationSession =
|
||||
new URLSearchParams(window.location.search).get("t3code_perf_automation") === "1";
|
||||
if (perfAutomationSession) {
|
||||
bootstrappedRef.current = true;
|
||||
return;
|
||||
}
|
||||
|
||||
let disposed = false;
|
||||
let retryDelayMs = 500;
|
||||
let retryTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
@@ -139,6 +145,16 @@ function DesktopProjectBootstrap() {
|
||||
try {
|
||||
const projects = await api.projects.list();
|
||||
if (disposed) return;
|
||||
if (projects.length === 0 && (state.projects.length > 0 || state.threads.length > 0)) {
|
||||
// Avoid wiping hydrated renderer state if the initial projects.list races
|
||||
// backend startup and transiently returns no projects.
|
||||
retryTimer = setTimeout(() => {
|
||||
retryTimer = null;
|
||||
void attemptBootstrap();
|
||||
}, retryDelayMs);
|
||||
retryDelayMs = Math.min(retryDelayMs * 2, 5_000);
|
||||
return;
|
||||
}
|
||||
dispatch({
|
||||
type: "SYNC_PROJECTS",
|
||||
projects: projects.map((project) => ({
|
||||
@@ -147,7 +163,6 @@ function DesktopProjectBootstrap() {
|
||||
cwd: project.cwd,
|
||||
model: DEFAULT_MODEL,
|
||||
expanded: true,
|
||||
scripts: project.scripts,
|
||||
})),
|
||||
});
|
||||
bootstrappedRef.current = true;
|
||||
@@ -169,7 +184,7 @@ function DesktopProjectBootstrap() {
|
||||
clearTimeout(retryTimer);
|
||||
}
|
||||
};
|
||||
}, [api, dispatch]);
|
||||
}, [api, dispatch, state.projects.length, state.threads.length]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
|
||||
const branches: GitBranch[] = [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
isDefault: true,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "feature/demo",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
describe("deriveSyncedLocalBranch", () => {
|
||||
it("syncs to git current branch in local mode", () => {
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: "thread-1",
|
||||
activeWorktreePath: null,
|
||||
envMode: "local",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBe("main");
|
||||
});
|
||||
|
||||
it("does not sync when creating a new worktree", () => {
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: "thread-1",
|
||||
activeWorktreePath: null,
|
||||
envMode: "worktree",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("does not sync when thread already targets a worktree path", () => {
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: "thread-1",
|
||||
activeWorktreePath: "/tmp/repo/worktrees/feature-demo",
|
||||
envMode: "local",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
|
||||
interface DeriveSyncedLocalBranchInput {
|
||||
activeThreadId: string | undefined;
|
||||
activeWorktreePath: string | null;
|
||||
envMode: "local" | "worktree";
|
||||
activeThreadBranch: string | null;
|
||||
queryBranches: GitBranch[] | undefined;
|
||||
}
|
||||
|
||||
export function deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
}: DeriveSyncedLocalBranchInput): string | null {
|
||||
if (!activeThreadId || activeWorktreePath || envMode !== "local") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const currentBranch = queryBranches?.find((branch) => branch.current);
|
||||
if (!currentBranch || currentBranch.name === activeThreadBranch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return currentBranch.name;
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
gitCreateBranchAndCheckoutMutationOptions,
|
||||
} from "../lib/gitReactQuery";
|
||||
import { useStore } from "../store";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Combobox,
|
||||
@@ -68,35 +67,36 @@ export default function BranchToolbar({
|
||||
: branchNames;
|
||||
// ── Mutations ─────────────────────────────────────────────────────────
|
||||
|
||||
const checkoutMutation = useMutation(
|
||||
gitCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
||||
);
|
||||
const checkoutMutation = useMutation({
|
||||
...gitCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
||||
onError: (error) => {
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch.");
|
||||
setIsBranchMenuOpen(true);
|
||||
},
|
||||
});
|
||||
|
||||
const createBranchMutation = useMutation(
|
||||
gitCreateBranchAndCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
||||
);
|
||||
const createBranchMutation = useMutation({
|
||||
...gitCreateBranchAndCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
||||
onError: (error) =>
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to create branch."),
|
||||
});
|
||||
|
||||
// ── Effects ───────────────────────────────────────────────────────────
|
||||
|
||||
// Keep thread branch synced to git current branch for local threads.
|
||||
const queryBranches = branchesQuery.data?.branches;
|
||||
useEffect(() => {
|
||||
const syncedBranch = deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
});
|
||||
if (!activeThreadId || !syncedBranch) return;
|
||||
|
||||
if (!activeThreadId || activeWorktreePath) return;
|
||||
const current = queryBranches?.find((branch) => branch.current);
|
||||
if (!current) return;
|
||||
if (current.name === activeThreadBranch) return;
|
||||
dispatch({
|
||||
type: "SET_THREAD_BRANCH",
|
||||
threadId: activeThreadId,
|
||||
branch: syncedBranch,
|
||||
branch: current.name,
|
||||
worktreePath: null,
|
||||
});
|
||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
|
||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isBranchMenuOpen) return;
|
||||
@@ -153,10 +153,6 @@ export default function BranchToolbar({
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
},
|
||||
onError: (error) => {
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch.");
|
||||
setIsBranchMenuOpen(true);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -171,9 +167,6 @@ export default function BranchToolbar({
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
},
|
||||
onError: (error) => {
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to create branch.");
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -67,13 +67,13 @@ export function buildGitActionProgressStages(input: {
|
||||
return [...commitStages, pushStage, "Creating PR..."];
|
||||
}
|
||||
|
||||
const withDescription = (title: string, description: string | undefined) =>
|
||||
description ? { title, description } : { title };
|
||||
|
||||
export function summarizeGitResult(result: GitRunStackedActionResult): {
|
||||
title: string;
|
||||
description?: string;
|
||||
} {
|
||||
const withDescription = (title: string, description: string | undefined) =>
|
||||
description ? { title, description } : { title };
|
||||
|
||||
if (result.pr.status === "created" || result.pr.status === "opened_existing") {
|
||||
const prNumber = result.pr.number ? ` #${result.pr.number}` : "";
|
||||
const title = `${result.pr.status === "created" ? "Created PR" : "Opened PR"}${prNumber}`;
|
||||
|
||||
@@ -226,14 +226,17 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
||||
});
|
||||
return;
|
||||
}
|
||||
void api.shell.openExternal(prUrl).catch((err) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
const promise = api.shell.openExternal(prUrl);
|
||||
toastManager.promise(promise, {
|
||||
loading: { title: "Opening PR...", data: threadToastData },
|
||||
success: { title: "PR opened", data: threadToastData },
|
||||
error: (err) => ({
|
||||
title: "Unable to open PR link",
|
||||
description: err instanceof Error ? err.message : "An error occurred.",
|
||||
data: threadToastData,
|
||||
});
|
||||
}),
|
||||
});
|
||||
void promise.catch(() => undefined);
|
||||
}, [api, gitStatusForActions?.openPr?.url, threadToastData]);
|
||||
|
||||
const runGitActionWithToast = useCallback(
|
||||
|
||||
@@ -1,450 +0,0 @@
|
||||
import type {
|
||||
ProjectScript,
|
||||
ProjectScriptIcon,
|
||||
ResolvedKeybindingsConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
BugIcon,
|
||||
ChevronDownIcon,
|
||||
CogIcon,
|
||||
FlaskConicalIcon,
|
||||
HammerIcon,
|
||||
ListChecksIcon,
|
||||
PlayIcon,
|
||||
PlusIcon,
|
||||
WrenchIcon,
|
||||
} from "lucide-react";
|
||||
import React, { type FormEvent, type KeyboardEvent, useMemo, useState } from "react";
|
||||
|
||||
import { commandForProjectScript, primaryProjectScript } from "~/projectScripts";
|
||||
import { shortcutLabelForCommand } from "~/keybindings";
|
||||
import { isMacPlatform } from "~/lib/utils";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogPanel,
|
||||
DialogPopup,
|
||||
DialogTitle,
|
||||
} from "./ui/dialog";
|
||||
import { Group, GroupSeparator } from "./ui/group";
|
||||
import { Input } from "./ui/input";
|
||||
import { Label } from "./ui/label";
|
||||
import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu";
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover";
|
||||
import { Switch } from "./ui/switch";
|
||||
import { Textarea } from "./ui/textarea";
|
||||
|
||||
const SCRIPT_ICONS: Array<{ id: ProjectScriptIcon; label: string }> = [
|
||||
{ id: "play", label: "Play" },
|
||||
{ id: "test", label: "Test" },
|
||||
{ id: "lint", label: "Lint" },
|
||||
{ id: "configure", label: "Configure" },
|
||||
{ id: "build", label: "Build" },
|
||||
{ id: "debug", label: "Debug" },
|
||||
];
|
||||
|
||||
function ScriptIcon({
|
||||
icon,
|
||||
className = "size-3.5",
|
||||
}: {
|
||||
icon: ProjectScriptIcon;
|
||||
className?: string;
|
||||
}) {
|
||||
if (icon === "test") return <FlaskConicalIcon className={className} />;
|
||||
if (icon === "lint") return <ListChecksIcon className={className} />;
|
||||
if (icon === "configure") return <WrenchIcon className={className} />;
|
||||
if (icon === "build") return <HammerIcon className={className} />;
|
||||
if (icon === "debug") return <BugIcon className={className} />;
|
||||
return <PlayIcon className={className} />;
|
||||
}
|
||||
|
||||
export interface NewProjectScriptInput {
|
||||
name: string;
|
||||
command: string;
|
||||
icon: ProjectScriptIcon;
|
||||
runOnWorktreeCreate: boolean;
|
||||
keybinding: string | null;
|
||||
}
|
||||
|
||||
interface ProjectScriptsControlProps {
|
||||
scripts: ProjectScript[];
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
preferredScriptId?: string | null;
|
||||
onRunScript: (script: ProjectScript) => void;
|
||||
onAddScript: (input: NewProjectScriptInput) => Promise<void> | void;
|
||||
onUpdateScript: (scriptId: string, input: NewProjectScriptInput) => Promise<void> | void;
|
||||
}
|
||||
|
||||
function normalizeShortcutKeyToken(key: string): string | null {
|
||||
const normalized = key.toLowerCase();
|
||||
if (
|
||||
normalized === "meta" ||
|
||||
normalized === "control" ||
|
||||
normalized === "ctrl" ||
|
||||
normalized === "shift" ||
|
||||
normalized === "alt" ||
|
||||
normalized === "option"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (normalized === " ") return "space";
|
||||
if (normalized === "escape") return "esc";
|
||||
if (normalized === "arrowup") return "arrowup";
|
||||
if (normalized === "arrowdown") return "arrowdown";
|
||||
if (normalized === "arrowleft") return "arrowleft";
|
||||
if (normalized === "arrowright") return "arrowright";
|
||||
if (normalized.length === 1) return normalized;
|
||||
if (normalized.startsWith("f") && normalized.length <= 3) return normalized;
|
||||
if (normalized === "enter" || normalized === "tab" || normalized === "backspace") {
|
||||
return normalized;
|
||||
}
|
||||
if (normalized === "delete" || normalized === "home" || normalized === "end") {
|
||||
return normalized;
|
||||
}
|
||||
if (normalized === "pageup" || normalized === "pagedown") return normalized;
|
||||
return null;
|
||||
}
|
||||
|
||||
function keybindingFromEvent(event: KeyboardEvent<HTMLInputElement>): string | null {
|
||||
const keyToken = normalizeShortcutKeyToken(event.key);
|
||||
if (!keyToken) return null;
|
||||
|
||||
const parts: string[] = [];
|
||||
if (isMacPlatform(navigator.platform)) {
|
||||
if (event.metaKey) parts.push("mod");
|
||||
if (event.ctrlKey) parts.push("ctrl");
|
||||
} else {
|
||||
if (event.ctrlKey) parts.push("mod");
|
||||
if (event.metaKey) parts.push("meta");
|
||||
}
|
||||
if (event.altKey) parts.push("alt");
|
||||
if (event.shiftKey) parts.push("shift");
|
||||
parts.push(keyToken);
|
||||
return parts.join("+");
|
||||
}
|
||||
|
||||
function keybindingValueForCommand(
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
command: string,
|
||||
): string | null {
|
||||
for (let index = keybindings.length - 1; index >= 0; index -= 1) {
|
||||
const binding = keybindings[index];
|
||||
if (!binding || binding.command !== command) continue;
|
||||
|
||||
const parts: string[] = [];
|
||||
if (binding.shortcut.modKey) parts.push("mod");
|
||||
if (binding.shortcut.ctrlKey) parts.push("ctrl");
|
||||
if (binding.shortcut.metaKey) parts.push("meta");
|
||||
if (binding.shortcut.altKey) parts.push("alt");
|
||||
if (binding.shortcut.shiftKey) parts.push("shift");
|
||||
const keyToken =
|
||||
binding.shortcut.key === " "
|
||||
? "space"
|
||||
: binding.shortcut.key === "escape"
|
||||
? "esc"
|
||||
: binding.shortcut.key;
|
||||
parts.push(keyToken);
|
||||
return parts.join("+");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export default function ProjectScriptsControl({
|
||||
scripts,
|
||||
keybindings,
|
||||
preferredScriptId = null,
|
||||
onRunScript,
|
||||
onAddScript,
|
||||
onUpdateScript,
|
||||
}: ProjectScriptsControlProps) {
|
||||
const addScriptFormId = React.useId();
|
||||
const [editingScriptId, setEditingScriptId] = useState<string | null>(null);
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [name, setName] = useState("");
|
||||
const [command, setCommand] = useState("");
|
||||
const [icon, setIcon] = useState<ProjectScriptIcon>("play");
|
||||
const [iconPickerOpen, setIconPickerOpen] = useState(false);
|
||||
const [runOnWorktreeCreate, setRunOnWorktreeCreate] = useState(false);
|
||||
const [keybinding, setKeybinding] = useState("");
|
||||
const [validationError, setValidationError] = useState<string | null>(null);
|
||||
|
||||
const primaryScript = useMemo(() => {
|
||||
if (preferredScriptId) {
|
||||
const preferred = scripts.find((script) => script.id === preferredScriptId);
|
||||
if (preferred) return preferred;
|
||||
}
|
||||
return primaryProjectScript(scripts);
|
||||
}, [preferredScriptId, scripts]);
|
||||
const isEditing = editingScriptId !== null;
|
||||
const dropdownItemClassName =
|
||||
"data-highlighted:bg-transparent data-highlighted:text-foreground hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground data-highlighted:hover:bg-accent data-highlighted:hover:text-accent-foreground data-highlighted:focus-visible:bg-accent data-highlighted:focus-visible:text-accent-foreground";
|
||||
|
||||
const captureKeybinding = (event: KeyboardEvent<HTMLInputElement>) => {
|
||||
if (event.key === "Tab") return;
|
||||
event.preventDefault();
|
||||
if (event.key === "Backspace" || event.key === "Delete") {
|
||||
setKeybinding("");
|
||||
return;
|
||||
}
|
||||
const next = keybindingFromEvent(event);
|
||||
if (!next) return;
|
||||
setKeybinding(next);
|
||||
};
|
||||
|
||||
const submitAddScript = async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
const trimmedName = name.trim();
|
||||
const trimmedCommand = command.trim();
|
||||
if (trimmedName.length === 0) {
|
||||
setValidationError("Name is required.");
|
||||
return;
|
||||
}
|
||||
if (trimmedCommand.length === 0) {
|
||||
setValidationError("Command is required.");
|
||||
return;
|
||||
}
|
||||
|
||||
setValidationError(null);
|
||||
try {
|
||||
const payload = {
|
||||
name: trimmedName,
|
||||
command: trimmedCommand,
|
||||
icon,
|
||||
runOnWorktreeCreate,
|
||||
keybinding: keybinding.trim() || null,
|
||||
} satisfies NewProjectScriptInput;
|
||||
if (editingScriptId) {
|
||||
await onUpdateScript(editingScriptId, payload);
|
||||
} else {
|
||||
await onAddScript(payload);
|
||||
}
|
||||
setDialogOpen(false);
|
||||
setEditingScriptId(null);
|
||||
setName("");
|
||||
setCommand("");
|
||||
setIcon("play");
|
||||
setIconPickerOpen(false);
|
||||
setRunOnWorktreeCreate(false);
|
||||
setKeybinding("");
|
||||
} catch (error) {
|
||||
setValidationError(error instanceof Error ? error.message : "Failed to save action.");
|
||||
}
|
||||
};
|
||||
|
||||
const openAddDialog = () => {
|
||||
setEditingScriptId(null);
|
||||
setName("");
|
||||
setCommand("");
|
||||
setIcon("play");
|
||||
setIconPickerOpen(false);
|
||||
setRunOnWorktreeCreate(false);
|
||||
setKeybinding("");
|
||||
setValidationError(null);
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
const openEditDialog = (script: ProjectScript) => {
|
||||
setEditingScriptId(script.id);
|
||||
setName(script.name);
|
||||
setCommand(script.command);
|
||||
setIcon(script.icon);
|
||||
setIconPickerOpen(false);
|
||||
setRunOnWorktreeCreate(script.runOnWorktreeCreate);
|
||||
setKeybinding(keybindingValueForCommand(keybindings, commandForProjectScript(script.id)) ?? "");
|
||||
setValidationError(null);
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{primaryScript ? (
|
||||
<Group aria-label="Project scripts">
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => onRunScript(primaryScript)}
|
||||
title={`Run ${primaryScript.name}`}
|
||||
>
|
||||
<ScriptIcon icon={primaryScript.icon} />
|
||||
<span className="ml-0.5">{primaryScript.name}</span>
|
||||
</Button>
|
||||
<GroupSeparator />
|
||||
<Menu highlightItemOnHover={false}>
|
||||
<MenuTrigger
|
||||
render={<Button size="icon-xs" variant="outline" aria-label="Script actions" />}
|
||||
>
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="end">
|
||||
{scripts.map((script) => {
|
||||
const shortcutLabel = shortcutLabelForCommand(
|
||||
keybindings,
|
||||
commandForProjectScript(script.id),
|
||||
);
|
||||
return (
|
||||
<MenuItem
|
||||
key={script.id}
|
||||
className={`group ${dropdownItemClassName}`}
|
||||
onClick={() => onRunScript(script)}
|
||||
>
|
||||
<ScriptIcon icon={script.icon} className="size-4" />
|
||||
<span className="truncate">
|
||||
{script.runOnWorktreeCreate ? `${script.name}` : script.name}
|
||||
</span>
|
||||
<span className="relative ms-auto flex h-6 min-w-6 items-center justify-end">
|
||||
{shortcutLabel && (
|
||||
<MenuShortcut className="ms-0 transition-opacity group-hover:opacity-0 group-focus-visible:opacity-0">
|
||||
{shortcutLabel}
|
||||
</MenuShortcut>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="absolute right-0 top-1/2 size-6 -translate-y-1/2 opacity-0 pointer-events-none transition-opacity group-hover:opacity-100 group-hover:pointer-events-auto group-focus-visible:opacity-100 group-focus-visible:pointer-events-auto"
|
||||
aria-label={`Edit ${script.name}`}
|
||||
onPointerDown={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
openEditDialog(script);
|
||||
}}
|
||||
>
|
||||
<CogIcon className="size-3.5" />
|
||||
</Button>
|
||||
</span>
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
<MenuItem className={dropdownItemClassName} onClick={openAddDialog}>
|
||||
<PlusIcon className="size-4" />
|
||||
Add action
|
||||
</MenuItem>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
</Group>
|
||||
) : (
|
||||
<Button size="xs" variant="outline" onClick={openAddDialog}>
|
||||
<PlusIcon className="size-3.5" />
|
||||
Add action
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Dialog onOpenChange={setDialogOpen} open={dialogOpen}>
|
||||
<DialogPopup>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEditing ? "Edit Action" : "Add Action"}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Actions are project-scoped commands you can run from the top bar or keybindings.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogPanel>
|
||||
<form id={addScriptFormId} className="space-y-4" onSubmit={submitAddScript}>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="script-name">Name</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Popover onOpenChange={setIconPickerOpen} open={iconPickerOpen}>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="size-9 shrink-0 hover:bg-popover active:bg-popover data-pressed:bg-popover data-pressed:shadow-xs/5 data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)]"
|
||||
aria-label="Choose icon"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<ScriptIcon icon={icon} className="size-4.5" />
|
||||
</PopoverTrigger>
|
||||
<PopoverPopup align="start">
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{SCRIPT_ICONS.map((entry) => {
|
||||
const isSelected = entry.id === icon;
|
||||
return (
|
||||
<button
|
||||
key={entry.id}
|
||||
type="button"
|
||||
className={`relative flex flex-col items-center gap-2 rounded-md border px-2 py-2 text-xs ${
|
||||
isSelected
|
||||
? "border-primary/70 bg-primary/10"
|
||||
: "border-border/70 hover:bg-accent/60"
|
||||
}`}
|
||||
onClick={() => {
|
||||
setIcon(entry.id);
|
||||
setIconPickerOpen(false);
|
||||
}}
|
||||
>
|
||||
<ScriptIcon icon={entry.id} className="size-4" />
|
||||
<span>{entry.label}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</PopoverPopup>
|
||||
</Popover>
|
||||
<Input
|
||||
id="script-name"
|
||||
placeholder="Test"
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="script-keybinding">Keybinding</Label>
|
||||
<Input
|
||||
id="script-keybinding"
|
||||
placeholder="Press shortcut"
|
||||
value={keybinding}
|
||||
readOnly
|
||||
onKeyDown={captureKeybinding}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Press a shortcut. Use <code>Backspace</code> to clear.
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="script-command">Command</Label>
|
||||
<Textarea
|
||||
id="script-command"
|
||||
placeholder="bun test"
|
||||
value={command}
|
||||
onChange={(event) => setCommand(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<label className="flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm">
|
||||
<span>Run automatically on worktree creation</span>
|
||||
<Switch
|
||||
checked={runOnWorktreeCreate}
|
||||
onCheckedChange={(checked) => setRunOnWorktreeCreate(Boolean(checked))}
|
||||
/>
|
||||
</label>
|
||||
{validationError && <p className="text-sm text-destructive">{validationError}</p>}
|
||||
</form>
|
||||
</DialogPanel>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setDialogOpen(false);
|
||||
setEditingScriptId(null);
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button form={addScriptFormId} type="submit">
|
||||
{isEditing ? "Save changes" : "Save action"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -214,7 +214,6 @@ export default function Sidebar() {
|
||||
cwd: result.project.cwd,
|
||||
model: DEFAULT_MODEL,
|
||||
expanded: true,
|
||||
scripts: result.project.scripts,
|
||||
};
|
||||
const existingById = state.projects.find((p) => p.id === project.id);
|
||||
const existingByCwd = state.projects.find((p) => p.cwd === project.cwd);
|
||||
@@ -242,7 +241,6 @@ export default function Sidebar() {
|
||||
cwd,
|
||||
model: DEFAULT_MODEL,
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
};
|
||||
dispatch({ type: "ADD_PROJECT", project });
|
||||
handleNewThread(project.id);
|
||||
@@ -507,6 +505,7 @@ export default function Sidebar() {
|
||||
<button
|
||||
key={thread.id}
|
||||
type="button"
|
||||
data-perf-thread-id={thread.id}
|
||||
className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 ${
|
||||
isActive
|
||||
? "bg-accent text-foreground"
|
||||
|
||||
@@ -22,7 +22,6 @@ import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keyb
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
type ThreadTerminalGroup,
|
||||
} from "../types";
|
||||
|
||||
@@ -369,7 +368,7 @@ function TerminalViewport({
|
||||
fitAddonRef.current = null;
|
||||
terminal.dispose();
|
||||
};
|
||||
}, [api, cwd, terminalId, threadId]);
|
||||
}, [api, cwd, terminalId, threadId, autoFocus]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!autoFocus) return;
|
||||
@@ -582,7 +581,6 @@ export default function ThreadTerminalDrawer({
|
||||
const showGroupHeaders =
|
||||
resolvedTerminalGroups.length > 1 ||
|
||||
resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1);
|
||||
const hasReachedTerminalLimit = normalizedTerminalIds.length >= MAX_THREAD_TERMINAL_COUNT;
|
||||
const terminalLabelById = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
@@ -590,23 +588,9 @@ export default function ThreadTerminalDrawer({
|
||||
),
|
||||
[normalizedTerminalIds],
|
||||
);
|
||||
const splitTerminalActionLabel = hasReachedTerminalLimit
|
||||
? `Split Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
|
||||
: (splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal");
|
||||
const newTerminalActionLabel = hasReachedTerminalLimit
|
||||
? `New Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
|
||||
: (newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal");
|
||||
const closeTerminalActionLabel = closeShortcutLabel
|
||||
? `Close Terminal (${closeShortcutLabel})`
|
||||
: "Close Terminal";
|
||||
const onSplitTerminalAction = useCallback(() => {
|
||||
if (hasReachedTerminalLimit) return;
|
||||
onSplitTerminal();
|
||||
}, [hasReachedTerminalLimit, onSplitTerminal]);
|
||||
const onNewTerminalAction = useCallback(() => {
|
||||
if (hasReachedTerminalLimit) return;
|
||||
onNewTerminal();
|
||||
}, [hasReachedTerminalLimit, onNewTerminal]);
|
||||
|
||||
useEffect(() => {
|
||||
onHeightChangeRef.current = onHeightChange;
|
||||
@@ -701,7 +685,7 @@ export default function ThreadTerminalDrawer({
|
||||
|
||||
return (
|
||||
<aside
|
||||
className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
|
||||
className="thread-terminal-drawer relative flex shrink-0 flex-col border-t border-border/80 bg-background"
|
||||
style={{ height: `${drawerHeight}px` }}
|
||||
>
|
||||
<div
|
||||
@@ -716,25 +700,19 @@ export default function ThreadTerminalDrawer({
|
||||
<div className="pointer-events-none absolute right-2 top-2 z-20">
|
||||
<div className="pointer-events-auto inline-flex items-center overflow-hidden rounded-md border border-border/80 bg-background/70">
|
||||
<TerminalActionButton
|
||||
className={`p-1 text-foreground/90 transition-colors ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent"
|
||||
}`}
|
||||
onClick={onSplitTerminalAction}
|
||||
label={splitTerminalActionLabel}
|
||||
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||
onClick={onSplitTerminal}
|
||||
label={
|
||||
splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal"
|
||||
}
|
||||
>
|
||||
<SquareSplitHorizontal className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
<div className="h-4 w-px bg-border/80" />
|
||||
<TerminalActionButton
|
||||
className={`p-1 text-foreground/90 transition-colors ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent"
|
||||
}`}
|
||||
onClick={onNewTerminalAction}
|
||||
label={newTerminalActionLabel}
|
||||
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||
onClick={onNewTerminal}
|
||||
label={newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"}
|
||||
>
|
||||
<Plus className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
@@ -755,9 +733,9 @@ export default function ThreadTerminalDrawer({
|
||||
<div className="min-w-0 flex-1">
|
||||
{isSplitView ? (
|
||||
<div
|
||||
className="grid h-full w-full min-w-0 gap-0 overflow-hidden"
|
||||
className="grid h-full w-full gap-0 overflow-x-auto"
|
||||
style={{
|
||||
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(0, 1fr))`,
|
||||
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(260px, 1fr))`,
|
||||
}}
|
||||
>
|
||||
{visibleTerminalIds.map((terminalId) => (
|
||||
@@ -809,24 +787,20 @@ export default function ThreadTerminalDrawer({
|
||||
<div className="flex h-[22px] items-stretch justify-end border-b border-border/70">
|
||||
<div className="inline-flex h-full items-stretch">
|
||||
<TerminalActionButton
|
||||
className={`inline-flex h-full items-center px-1 text-foreground/90 transition-colors ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent/70"
|
||||
}`}
|
||||
onClick={onSplitTerminalAction}
|
||||
label={splitTerminalActionLabel}
|
||||
className="inline-flex h-full items-center px-1 text-foreground/90 transition-colors hover:bg-accent/70"
|
||||
onClick={onSplitTerminal}
|
||||
label={
|
||||
splitShortcutLabel
|
||||
? `Split Terminal (${splitShortcutLabel})`
|
||||
: "Split Terminal"
|
||||
}
|
||||
>
|
||||
<SquareSplitHorizontal className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
<TerminalActionButton
|
||||
className={`inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent/70"
|
||||
}`}
|
||||
onClick={onNewTerminalAction}
|
||||
label={newTerminalActionLabel}
|
||||
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
|
||||
onClick={onNewTerminal}
|
||||
label={newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"}
|
||||
>
|
||||
<Plus className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
|
||||
@@ -133,7 +133,10 @@ function CommandEmpty({ className, ...props }: React.ComponentProps<typeof Autoc
|
||||
function CommandPanel({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
className="-mx-px not-has-[+[data-slot=command-footer]]:-mb-px relative min-h-0 rounded-t-xl not-has-[+[data-slot=command-footer]]:rounded-b-2xl border border-b-0 bg-popover bg-clip-padding shadow-xs/5 [clip-path:inset(0_1px)] not-has-[+[data-slot=command-footer]]:[clip-path:inset(0_1px_1px_1px_round_0_0_calc(var(--radius-2xl)-1px)_calc(var(--radius-2xl)-1px))] before:pointer-events-none before:absolute before:inset-0 before:rounded-t-[calc(var(--radius-xl)-1px)] **:data-[slot=scroll-area-scrollbar]:mt-2"
|
||||
className={cn(
|
||||
"-mx-px not-has-[+[data-slot=command-footer]]:-mb-px relative min-h-0 rounded-t-xl not-has-[+[data-slot=command-footer]]:rounded-b-2xl border border-b-0 bg-popover bg-clip-padding shadow-xs/5 [clip-path:inset(0_1px)] not-has-[+[data-slot=command-footer]]:[clip-path:inset(0_1px_1px_1px_round_0_0_calc(var(--radius-2xl)-1px)_calc(var(--radius-2xl)-1px))] before:pointer-events-none before:absolute before:inset-0 before:rounded-t-[calc(var(--radius-xl)-1px)] **:data-[slot=scroll-area-scrollbar]:mt-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -49,6 +49,7 @@ function SheetViewport({
|
||||
side === "left" && "flex justify-start",
|
||||
side === "right" && "flex justify-end",
|
||||
variant === "inset" && "sm:p-4",
|
||||
className,
|
||||
)}
|
||||
data-slot="sheet-viewport"
|
||||
{...props}
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { detectComposerTrigger, replaceTextRange } from "./composer-logic";
|
||||
|
||||
describe("detectComposerTrigger", () => {
|
||||
it("detects @path trigger at cursor", () => {
|
||||
const text = "Please check @src/com";
|
||||
const trigger = detectComposerTrigger(text, text.length);
|
||||
|
||||
expect(trigger).toEqual({
|
||||
kind: "path",
|
||||
query: "src/com",
|
||||
rangeStart: "Please check ".length,
|
||||
rangeEnd: text.length,
|
||||
});
|
||||
});
|
||||
|
||||
it("detects slash command token while typing command name", () => {
|
||||
const text = "/mo";
|
||||
const trigger = detectComposerTrigger(text, text.length);
|
||||
|
||||
expect(trigger).toEqual({
|
||||
kind: "slash-command",
|
||||
query: "mo",
|
||||
rangeStart: 0,
|
||||
rangeEnd: text.length,
|
||||
});
|
||||
});
|
||||
|
||||
it("detects slash model query after /model", () => {
|
||||
const text = "/model spark";
|
||||
const trigger = detectComposerTrigger(text, text.length);
|
||||
|
||||
expect(trigger).toEqual({
|
||||
kind: "slash-model",
|
||||
query: "spark",
|
||||
rangeStart: 0,
|
||||
rangeEnd: text.length,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("replaceTextRange", () => {
|
||||
it("replaces a text range and returns new cursor", () => {
|
||||
const replaced = replaceTextRange("hello @src", 6, 10, "");
|
||||
expect(replaced).toEqual({
|
||||
text: "hello ",
|
||||
cursor: 6,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,90 +0,0 @@
|
||||
export type ComposerTriggerKind = "path" | "slash-command" | "slash-model";
|
||||
|
||||
export interface ComposerTrigger {
|
||||
kind: ComposerTriggerKind;
|
||||
query: string;
|
||||
rangeStart: number;
|
||||
rangeEnd: number;
|
||||
}
|
||||
|
||||
function clampCursor(text: string, cursor: number): number {
|
||||
if (!Number.isFinite(cursor)) return text.length;
|
||||
return Math.max(0, Math.min(text.length, Math.floor(cursor)));
|
||||
}
|
||||
|
||||
function isWhitespace(char: string): boolean {
|
||||
return char === " " || char === "\n" || char === "\t" || char === "\r";
|
||||
}
|
||||
|
||||
function tokenStartForCursor(text: string, cursor: number): number {
|
||||
let index = cursor - 1;
|
||||
while (index >= 0 && !isWhitespace(text[index] ?? "")) {
|
||||
index -= 1;
|
||||
}
|
||||
return index + 1;
|
||||
}
|
||||
|
||||
export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null {
|
||||
const cursor = clampCursor(text, cursorInput);
|
||||
const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1;
|
||||
const linePrefix = text.slice(lineStart, cursor);
|
||||
|
||||
if (linePrefix.startsWith("/")) {
|
||||
const commandMatch = /^\/(\S*)$/.exec(linePrefix);
|
||||
if (commandMatch) {
|
||||
const commandQuery = commandMatch[1] ?? "";
|
||||
if (commandQuery.toLowerCase() === "model") {
|
||||
return {
|
||||
kind: "slash-model",
|
||||
query: "",
|
||||
rangeStart: lineStart,
|
||||
rangeEnd: cursor,
|
||||
};
|
||||
}
|
||||
if ("model".startsWith(commandQuery.toLowerCase())) {
|
||||
return {
|
||||
kind: "slash-command",
|
||||
query: commandQuery,
|
||||
rangeStart: lineStart,
|
||||
rangeEnd: cursor,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const modelMatch = /^\/model(?:\s+(.*))?$/.exec(linePrefix);
|
||||
if (modelMatch) {
|
||||
return {
|
||||
kind: "slash-model",
|
||||
query: (modelMatch[1] ?? "").trim(),
|
||||
rangeStart: lineStart,
|
||||
rangeEnd: cursor,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const tokenStart = tokenStartForCursor(text, cursor);
|
||||
const token = text.slice(tokenStart, cursor);
|
||||
if (!token.startsWith("@")) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "path",
|
||||
query: token.slice(1),
|
||||
rangeStart: tokenStart,
|
||||
rangeEnd: cursor,
|
||||
};
|
||||
}
|
||||
|
||||
export function replaceTextRange(
|
||||
text: string,
|
||||
rangeStart: number,
|
||||
rangeEnd: number,
|
||||
replacement: string,
|
||||
): { text: string; cursor: number } {
|
||||
const safeStart = Math.max(0, Math.min(text.length, rangeStart));
|
||||
const safeEnd = Math.max(safeStart, Math.min(text.length, rangeEnd));
|
||||
const nextText = `${text.slice(0, safeStart)}${replacement}${text.slice(safeEnd)}`;
|
||||
return { text: nextText, cursor: safeStart + replacement.length };
|
||||
}
|
||||
@@ -28,6 +28,7 @@ function applyTheme(theme: Theme, suppressTransitions = false) {
|
||||
document.documentElement.classList.toggle("dark", isDark);
|
||||
if (suppressTransitions) {
|
||||
// Force a reflow so the no-transitions class takes effect before removal
|
||||
// oxlint-disable-next-line no-unused-expressions
|
||||
document.documentElement.offsetHeight;
|
||||
requestAnimationFrame(() => {
|
||||
document.documentElement.classList.remove("no-transitions");
|
||||
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
isTerminalNewShortcut,
|
||||
isTerminalSplitShortcut,
|
||||
isTerminalToggleShortcut,
|
||||
resolveShortcutCommand,
|
||||
shortcutLabelForCommand,
|
||||
terminalNavigationShortcutData,
|
||||
type ShortcutEventLike,
|
||||
@@ -340,21 +339,6 @@ describe("cross-command precedence", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveShortcutCommand", () => {
|
||||
it("returns dynamic script commands", () => {
|
||||
const keybindings = compile([
|
||||
{ shortcut: modShortcut("r"), command: "script.setup.run" },
|
||||
]);
|
||||
|
||||
assert.strictEqual(
|
||||
resolveShortcutCommand(event({ key: "r", ctrlKey: true }), keybindings, {
|
||||
platform: "Linux",
|
||||
}),
|
||||
"script.setup.run",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatShortcutLabel", () => {
|
||||
it("formats labels for macOS", () => {
|
||||
assert.strictEqual(
|
||||
|
||||
@@ -100,11 +100,11 @@ function matchesCommandShortcut(
|
||||
return resolveShortcutCommand(event, keybindings, options) === command;
|
||||
}
|
||||
|
||||
export function resolveShortcutCommand(
|
||||
function resolveShortcutCommand(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
options?: ShortcutMatchOptions,
|
||||
): string | null {
|
||||
): KeybindingCommand | null {
|
||||
const platform = resolvePlatform(options);
|
||||
const context = resolveContext(options);
|
||||
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
import type { GitStackedAction, NativeApi } from "@t3tools/contracts";
|
||||
import { mutationOptions, queryOptions, type QueryClient } from "@tanstack/react-query";
|
||||
|
||||
const GIT_STATUS_STALE_TIME_MS = 5_000;
|
||||
const GIT_STATUS_REFETCH_INTERVAL_MS = 15_000;
|
||||
const GIT_BRANCHES_STALE_TIME_MS = 15_000;
|
||||
const GIT_BRANCHES_REFETCH_INTERVAL_MS = 60_000;
|
||||
|
||||
export const gitQueryKeys = {
|
||||
all: ["git"] as const,
|
||||
status: (cwd: string | null) => ["git", "status", cwd] as const,
|
||||
@@ -26,10 +21,6 @@ export function gitStatusQueryOptions(api: NativeApi | undefined, cwd: string |
|
||||
return api.git.status({ cwd });
|
||||
},
|
||||
enabled: !!api && !!cwd,
|
||||
staleTime: GIT_STATUS_STALE_TIME_MS,
|
||||
refetchOnWindowFocus: "always",
|
||||
refetchOnReconnect: "always",
|
||||
refetchInterval: GIT_STATUS_REFETCH_INTERVAL_MS,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -43,10 +34,6 @@ export function gitBranchesQueryOptions(api: NativeApi | undefined, cwd: string
|
||||
return api.git.listBranches({ cwd });
|
||||
},
|
||||
enabled: !!api && !!cwd,
|
||||
staleTime: GIT_BRANCHES_STALE_TIME_MS,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
refetchInterval: GIT_BRANCHES_REFETCH_INTERVAL_MS,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
import type { NativeApi, ProjectSearchEntriesResult } from "@t3tools/contracts";
|
||||
import { queryOptions } from "@tanstack/react-query";
|
||||
|
||||
export const projectQueryKeys = {
|
||||
all: ["projects"] as const,
|
||||
searchEntries: (cwd: string | null, query: string, limit: number) =>
|
||||
["projects", "search-entries", cwd, query, limit] as const,
|
||||
};
|
||||
|
||||
const DEFAULT_SEARCH_ENTRIES_LIMIT = 80;
|
||||
const DEFAULT_SEARCH_ENTRIES_STALE_TIME = 15_000;
|
||||
const EMPTY_SEARCH_ENTRIES_RESULT: ProjectSearchEntriesResult = {
|
||||
entries: [],
|
||||
truncated: false,
|
||||
};
|
||||
|
||||
export function projectSearchEntriesQueryOptions(input: {
|
||||
api: NativeApi | undefined;
|
||||
cwd: string | null;
|
||||
query: string;
|
||||
enabled?: boolean;
|
||||
limit?: number;
|
||||
staleTime?: number;
|
||||
}) {
|
||||
const limit = input.limit ?? DEFAULT_SEARCH_ENTRIES_LIMIT;
|
||||
return queryOptions({
|
||||
queryKey: projectQueryKeys.searchEntries(input.cwd, input.query, limit),
|
||||
queryFn: async () => {
|
||||
if (!input.api || !input.cwd) {
|
||||
throw new Error("Workspace entry search is unavailable.");
|
||||
}
|
||||
return input.api.projects.searchEntries({
|
||||
cwd: input.cwd,
|
||||
query: input.query,
|
||||
limit,
|
||||
});
|
||||
},
|
||||
enabled: (input.enabled ?? true) && Boolean(input.api && input.cwd),
|
||||
staleTime: input.staleTime ?? DEFAULT_SEARCH_ENTRIES_STALE_TIME,
|
||||
placeholderData: (previous) => previous ?? EMPTY_SEARCH_ENTRIES_RESULT,
|
||||
});
|
||||
}
|
||||
@@ -20,7 +20,6 @@ describe("hydratePersistedState", () => {
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.2-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
@@ -70,7 +69,6 @@ describe("hydratePersistedState", () => {
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: false,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
@@ -121,7 +119,6 @@ describe("hydratePersistedState", () => {
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: false,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [],
|
||||
@@ -143,7 +140,6 @@ describe("hydratePersistedState", () => {
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
@@ -191,7 +187,6 @@ describe("hydratePersistedState", () => {
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
@@ -236,7 +231,6 @@ describe("hydratePersistedState", () => {
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
@@ -319,7 +313,6 @@ describe("toPersistedState", () => {
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [thread],
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { z } from "zod";
|
||||
import { projectScriptSchema } from "@t3tools/contracts";
|
||||
|
||||
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
|
||||
import {
|
||||
@@ -20,7 +19,6 @@ const persistedProjectSchema = z.object({
|
||||
cwd: z.string().min(1),
|
||||
model: z.string().min(1),
|
||||
expanded: z.boolean(),
|
||||
scripts: z.array(projectScriptSchema).default([]),
|
||||
});
|
||||
|
||||
const persistedMessageSchema = z.object({
|
||||
@@ -142,7 +140,6 @@ function hydrateProject(
|
||||
return {
|
||||
...project,
|
||||
model: resolveModelSlug(maybeMigrateLegacyModel(project.model, isLegacyPayload)),
|
||||
scripts: project.scripts,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
commandForProjectScript,
|
||||
injectEnvIntoShellCommand,
|
||||
nextProjectScriptId,
|
||||
primaryProjectScript,
|
||||
projectScriptRuntimeEnv,
|
||||
projectScriptIdFromCommand,
|
||||
setupProjectScript,
|
||||
} from "./projectScripts";
|
||||
|
||||
describe("projectScripts helpers", () => {
|
||||
it("builds and parses script run commands", () => {
|
||||
const command = commandForProjectScript("lint");
|
||||
expect(command).toBe("script.lint.run");
|
||||
expect(projectScriptIdFromCommand(command)).toBe("lint");
|
||||
expect(projectScriptIdFromCommand("terminal.toggle")).toBeNull();
|
||||
});
|
||||
|
||||
it("slugifies and dedupes project script ids", () => {
|
||||
expect(nextProjectScriptId("Run Tests", [])).toBe("run-tests");
|
||||
expect(nextProjectScriptId("Run Tests", ["run-tests"])).toBe("run-tests-2");
|
||||
expect(nextProjectScriptId("!!!", [])).toBe("script");
|
||||
});
|
||||
|
||||
it("injects environment variables for posix shells", () => {
|
||||
const command = injectEnvIntoShellCommand(
|
||||
"bun install",
|
||||
{ T3CODE_PROJECT_ROOT: "/tmp/project" },
|
||||
"MacIntel",
|
||||
);
|
||||
expect(command).toBe("env T3CODE_PROJECT_ROOT='/tmp/project' bun install");
|
||||
});
|
||||
|
||||
it("injects environment variables for windows shells", () => {
|
||||
const command = injectEnvIntoShellCommand(
|
||||
"bun install",
|
||||
{ T3CODE_PROJECT_ROOT: "C:\\\\repo path" },
|
||||
"Win32",
|
||||
);
|
||||
expect(command).toBe('set "T3CODE_PROJECT_ROOT=C:\\\\repo path" && bun install');
|
||||
});
|
||||
|
||||
it("escapes windows env values that trigger interpolation", () => {
|
||||
const command = injectEnvIntoShellCommand(
|
||||
"bun install",
|
||||
{ T3CODE_PROJECT_ROOT: '%USERPROFILE%^"repo"' },
|
||||
"Win32",
|
||||
);
|
||||
expect(command).toBe('set "T3CODE_PROJECT_ROOT=%USERPROFILE%^^""repo""" && bun install');
|
||||
});
|
||||
|
||||
it("resolves primary and setup scripts", () => {
|
||||
const scripts = [
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
command: "bun install",
|
||||
icon: "configure" as const,
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
{
|
||||
id: "test",
|
||||
name: "Test",
|
||||
command: "bun test",
|
||||
icon: "test" as const,
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
];
|
||||
|
||||
expect(primaryProjectScript(scripts)?.id).toBe("test");
|
||||
expect(setupProjectScript(scripts)?.id).toBe("setup");
|
||||
});
|
||||
|
||||
it("builds default runtime env for scripts", () => {
|
||||
const env = projectScriptRuntimeEnv({
|
||||
project: { id: "project-1", name: "acme-web", cwd: "/repo" },
|
||||
script: {
|
||||
id: "test",
|
||||
name: "Test",
|
||||
icon: "test",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
threadId: "thread-1",
|
||||
worktreePath: "/repo/worktree-a",
|
||||
});
|
||||
|
||||
expect(env).toMatchObject({
|
||||
T3CODE_PROJECT_ROOT: "/repo",
|
||||
T3CODE_PROJECT_ID: "project-1",
|
||||
T3CODE_PROJECT_NAME: "acme-web",
|
||||
T3CODE_THREAD_ID: "thread-1",
|
||||
T3CODE_SCRIPT_ID: "test",
|
||||
T3CODE_SCRIPT_NAME: "Test",
|
||||
T3CODE_SCRIPT_ICON: "test",
|
||||
T3CODE_SCRIPT_IS_SETUP: "0",
|
||||
T3CODE_WORKTREE_PATH: "/repo/worktree-a",
|
||||
});
|
||||
});
|
||||
|
||||
it("allows overriding runtime env values", () => {
|
||||
const env = projectScriptRuntimeEnv({
|
||||
project: { id: "project-1", name: "acme-web", cwd: "/repo" },
|
||||
script: {
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
threadId: "thread-1",
|
||||
extraEnv: {
|
||||
T3CODE_PROJECT_ROOT: "/custom-root",
|
||||
CUSTOM_FLAG: "1",
|
||||
},
|
||||
});
|
||||
|
||||
expect(env.T3CODE_PROJECT_ROOT).toBe("/custom-root");
|
||||
expect(env.T3CODE_SCRIPT_IS_SETUP).toBe("1");
|
||||
expect(env.CUSTOM_FLAG).toBe("1");
|
||||
expect(env.T3CODE_WORKTREE_PATH).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,130 +0,0 @@
|
||||
import type { ProjectScript } from "@t3tools/contracts";
|
||||
|
||||
import { isWindowsPlatform } from "./lib/utils";
|
||||
|
||||
const SCRIPT_RUN_COMMAND_PATTERN = /^script\.([a-z0-9][a-z0-9-]*)\.run$/;
|
||||
const MAX_SCRIPT_ID_LENGTH = 64;
|
||||
const ENV_KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
||||
|
||||
function normalizeScriptId(value: string): string {
|
||||
const cleaned = value
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
if (cleaned.length === 0) {
|
||||
return "script";
|
||||
}
|
||||
if (cleaned.length <= MAX_SCRIPT_ID_LENGTH) {
|
||||
return cleaned;
|
||||
}
|
||||
return cleaned.slice(0, MAX_SCRIPT_ID_LENGTH).replace(/-+$/g, "") || "script";
|
||||
}
|
||||
|
||||
export function commandForProjectScript(scriptId: string): string {
|
||||
return `script.${scriptId}.run`;
|
||||
}
|
||||
|
||||
export function projectScriptIdFromCommand(command: string): string | null {
|
||||
const match = SCRIPT_RUN_COMMAND_PATTERN.exec(command.trim());
|
||||
return match?.[1] ?? null;
|
||||
}
|
||||
|
||||
export function nextProjectScriptId(name: string, existingIds: Iterable<string>): string {
|
||||
const taken = new Set(Array.from(existingIds));
|
||||
const baseId = normalizeScriptId(name);
|
||||
if (!taken.has(baseId)) return baseId;
|
||||
|
||||
let suffix = 2;
|
||||
while (suffix < 10_000) {
|
||||
const candidate = `${baseId}-${suffix}`;
|
||||
const safeCandidate =
|
||||
candidate.length <= MAX_SCRIPT_ID_LENGTH
|
||||
? candidate
|
||||
: `${baseId.slice(0, Math.max(1, MAX_SCRIPT_ID_LENGTH - String(suffix).length - 1))}-${suffix}`;
|
||||
if (!taken.has(safeCandidate)) {
|
||||
return safeCandidate;
|
||||
}
|
||||
suffix += 1;
|
||||
}
|
||||
|
||||
return `${baseId}-${Date.now()}`.slice(0, MAX_SCRIPT_ID_LENGTH);
|
||||
}
|
||||
|
||||
function shellEscapePosix(value: string): string {
|
||||
return `'${value.replace(/'/g, `'\\''`)}'`;
|
||||
}
|
||||
|
||||
function shellEscapeWindowsSetValue(value: string): string {
|
||||
// Only escape ^ and " for interactive cmd.exe `set "K=V"` commands.
|
||||
// Do NOT escape % → %% here: that substitution only works in batch files.
|
||||
// In an interactive cmd.exe session (which is what terminal.write targets),
|
||||
// %% stays as literal %% and corrupts the value.
|
||||
return value.replace(/\^/g, "^^").replace(/"/g, '""');
|
||||
}
|
||||
|
||||
export function injectEnvIntoShellCommand(
|
||||
command: string,
|
||||
env: Record<string, string>,
|
||||
platform = typeof navigator === "undefined" ? "" : navigator.platform,
|
||||
): string {
|
||||
const entries = Object.entries(env).filter(
|
||||
([key, value]) => ENV_KEY_PATTERN.test(key) && value.length > 0,
|
||||
);
|
||||
if (entries.length === 0) {
|
||||
return command;
|
||||
}
|
||||
|
||||
if (isWindowsPlatform(platform)) {
|
||||
const prefixes = entries.map(
|
||||
([key, value]) => `set "${key}=${shellEscapeWindowsSetValue(value)}"`,
|
||||
);
|
||||
return `${prefixes.join(" && ")} && ${command}`;
|
||||
}
|
||||
|
||||
const assignments = entries.map(([key, value]) => `${key}=${shellEscapePosix(value)}`).join(" ");
|
||||
return `env ${assignments} ${command}`;
|
||||
}
|
||||
|
||||
interface ProjectScriptRuntimeEnvInput {
|
||||
project: {
|
||||
id: string;
|
||||
name: string;
|
||||
cwd: string;
|
||||
};
|
||||
script: Pick<ProjectScript, "id" | "name" | "icon" | "runOnWorktreeCreate">;
|
||||
threadId: string;
|
||||
worktreePath?: string | null;
|
||||
extraEnv?: Record<string, string>;
|
||||
}
|
||||
|
||||
export function projectScriptRuntimeEnv(
|
||||
input: ProjectScriptRuntimeEnvInput,
|
||||
): Record<string, string> {
|
||||
const env: Record<string, string> = {
|
||||
T3CODE_PROJECT_ROOT: input.project.cwd,
|
||||
T3CODE_PROJECT_ID: input.project.id,
|
||||
T3CODE_PROJECT_NAME: input.project.name,
|
||||
T3CODE_THREAD_ID: input.threadId,
|
||||
T3CODE_SCRIPT_ID: input.script.id,
|
||||
T3CODE_SCRIPT_NAME: input.script.name,
|
||||
T3CODE_SCRIPT_ICON: input.script.icon,
|
||||
T3CODE_SCRIPT_IS_SETUP: input.script.runOnWorktreeCreate ? "1" : "0",
|
||||
};
|
||||
if (input.worktreePath) {
|
||||
env.T3CODE_WORKTREE_PATH = input.worktreePath;
|
||||
}
|
||||
if (input.extraEnv) {
|
||||
return { ...env, ...input.extraEnv };
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
export function primaryProjectScript(scripts: ProjectScript[]): ProjectScript | null {
|
||||
const regular = scripts.find((script) => !script.runOnWorktreeCreate);
|
||||
return regular ?? scripts[0] ?? null;
|
||||
}
|
||||
|
||||
export function setupProjectScript(scripts: ProjectScript[]): ProjectScript | null {
|
||||
return scripts.find((script) => script.runOnWorktreeCreate) ?? null;
|
||||
}
|
||||
+1
-145
@@ -2,11 +2,7 @@ import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/con
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { type AppState, reducer } from "./store";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
} from "./types";
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
|
||||
import type { Thread } from "./types";
|
||||
|
||||
type TerminalStartedEvent = Extract<TerminalEvent, { type: "started" }>;
|
||||
@@ -74,7 +70,6 @@ function makeState(thread: Thread): AppState {
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [thread],
|
||||
@@ -260,70 +255,6 @@ describe("store reducer thread continuity", () => {
|
||||
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||
});
|
||||
|
||||
it("caps split terminals at four per thread", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3", "term-4"],
|
||||
activeTerminalId: "term-4",
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3", "term-4"],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "SPLIT_THREAD_TERMINAL",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: "term-5",
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.terminalIds).toHaveLength(MAX_THREAD_TERMINAL_COUNT);
|
||||
expect(next.threads[0]?.terminalIds).toEqual([
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
"term-2",
|
||||
"term-3",
|
||||
"term-4",
|
||||
]);
|
||||
expect(next.threads[0]?.activeTerminalId).toBe("term-4");
|
||||
});
|
||||
|
||||
it("caps new terminals at four per thread", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3", "term-4"],
|
||||
activeTerminalId: "term-4",
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
{ id: "group-term-2", terminalIds: ["term-2"] },
|
||||
{ id: "group-term-3", terminalIds: ["term-3"] },
|
||||
{ id: "group-term-4", terminalIds: ["term-4"] },
|
||||
],
|
||||
activeTerminalGroupId: "group-term-4",
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "NEW_THREAD_TERMINAL",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: "term-5",
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.terminalIds).toHaveLength(MAX_THREAD_TERMINAL_COUNT);
|
||||
expect(next.threads[0]?.terminalIds).toEqual([
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
"term-2",
|
||||
"term-3",
|
||||
"term-4",
|
||||
]);
|
||||
expect(next.threads[0]?.activeTerminalId).toBe("term-4");
|
||||
expect(next.threads[0]?.activeTerminalGroupId).toBe("group-term-4");
|
||||
});
|
||||
|
||||
it("closes a terminal and keeps grouped layout coherent", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
@@ -508,7 +439,6 @@ describe("store reducer thread continuity", () => {
|
||||
cwd: "/tmp/a",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: false,
|
||||
scripts: [],
|
||||
},
|
||||
{
|
||||
id: "project-old-b",
|
||||
@@ -516,7 +446,6 @@ describe("store reducer thread continuity", () => {
|
||||
cwd: "/tmp/b",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
@@ -543,7 +472,6 @@ describe("store reducer thread continuity", () => {
|
||||
cwd: "/tmp/a",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -558,76 +486,6 @@ describe("store reducer thread continuity", () => {
|
||||
expect(next.activeThreadId).toBe("thread-a");
|
||||
});
|
||||
|
||||
it("treats empty scripts from sync as authoritative", () => {
|
||||
const state: AppState = {
|
||||
projects: [
|
||||
{
|
||||
id: "project-old-a",
|
||||
name: "A",
|
||||
cwd: "/tmp/a",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [
|
||||
{
|
||||
id: "test",
|
||||
name: "Test",
|
||||
command: "bun test",
|
||||
icon: "test",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
threads: [makeThread({ id: "thread-a", projectId: "project-old-a" })],
|
||||
activeThreadId: "thread-a",
|
||||
runtimeMode: "full-access",
|
||||
diffOpen: false,
|
||||
};
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "SYNC_PROJECTS",
|
||||
projects: [
|
||||
{
|
||||
id: "project-new-a",
|
||||
name: "A",
|
||||
cwd: "/tmp/a",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: false,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(next.projects[0]?.scripts).toEqual([]);
|
||||
});
|
||||
|
||||
it("updates project scripts", () => {
|
||||
const state = makeState(makeThread());
|
||||
const next = reducer(state, {
|
||||
type: "SET_PROJECT_SCRIPTS",
|
||||
projectId: "project-1",
|
||||
scripts: [
|
||||
{
|
||||
id: "test",
|
||||
name: "Test",
|
||||
command: "bun test",
|
||||
icon: "test",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(next.projects[0]?.scripts).toEqual([
|
||||
{
|
||||
id: "test",
|
||||
name: "Test",
|
||||
command: "bun test",
|
||||
icon: "test",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("deletes a project and all of its threads", () => {
|
||||
const state: AppState = {
|
||||
projects: [
|
||||
@@ -637,7 +495,6 @@ describe("store reducer thread continuity", () => {
|
||||
cwd: "/tmp/one",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
{
|
||||
id: "project-2",
|
||||
@@ -645,7 +502,6 @@ describe("store reducer thread continuity", () => {
|
||||
cwd: "/tmp/two",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
|
||||
+3
-37
@@ -8,12 +8,7 @@ import {
|
||||
useReducer,
|
||||
} from "react";
|
||||
|
||||
import {
|
||||
type ProviderEvent,
|
||||
type ProviderSession,
|
||||
type TerminalEvent,
|
||||
normalizeProjectScripts,
|
||||
} from "@t3tools/contracts";
|
||||
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
|
||||
import { resolveModelSlug } from "./model-logic";
|
||||
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
||||
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
|
||||
@@ -21,8 +16,6 @@ import {
|
||||
type ChatAttachment,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
type ProjectScript,
|
||||
type Project,
|
||||
type RuntimeMode,
|
||||
type Thread,
|
||||
@@ -33,7 +26,6 @@ import {
|
||||
|
||||
type Action =
|
||||
| { type: "ADD_PROJECT"; project: Project }
|
||||
| { type: "SET_PROJECT_SCRIPTS"; projectId: string; scripts: ProjectScript[] }
|
||||
| { type: "SYNC_PROJECTS"; projects: Project[] }
|
||||
| { type: "TOGGLE_PROJECT"; projectId: string }
|
||||
| { type: "DELETE_PROJECT"; projectId: string }
|
||||
@@ -118,12 +110,7 @@ function readPersistedState(): AppState {
|
||||
const hydrated = hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
|
||||
if (!hydrated) return initialState;
|
||||
|
||||
const threads = hydrated.threads.map((thread) => normalizeThreadTerminals(thread));
|
||||
const activeThreadId = threads.some((thread) => thread.id === hydrated.activeThreadId)
|
||||
? hydrated.activeThreadId
|
||||
: (threads[0]?.id ?? null);
|
||||
|
||||
return { ...hydrated, threads, activeThreadId, diffOpen: false };
|
||||
return { ...hydrated, diffOpen: false };
|
||||
} catch {
|
||||
return initialState;
|
||||
}
|
||||
@@ -152,7 +139,7 @@ function updateThread(
|
||||
|
||||
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
|
||||
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
|
||||
const unique = [...new Set(ids)];
|
||||
if (unique.length > 0) {
|
||||
return unique;
|
||||
}
|
||||
@@ -433,33 +420,20 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
{
|
||||
...action.project,
|
||||
model: resolveModelSlug(action.project.model),
|
||||
scripts: normalizeProjectScripts(action.project.scripts),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
case "SET_PROJECT_SCRIPTS":
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.map((project) =>
|
||||
project.id === action.projectId
|
||||
? { ...project, scripts: normalizeProjectScripts(action.scripts) }
|
||||
: project,
|
||||
),
|
||||
};
|
||||
|
||||
case "SYNC_PROJECTS": {
|
||||
const previousByCwd = new Map(
|
||||
state.projects.map((project) => [project.cwd, project] as const),
|
||||
);
|
||||
const nextProjects = action.projects.map((project) => {
|
||||
const previous = previousByCwd.get(project.cwd);
|
||||
const scripts = normalizeProjectScripts(project.scripts);
|
||||
return {
|
||||
...project,
|
||||
model: resolveModelSlug(previous?.model ?? project.model),
|
||||
expanded: previous?.expanded ?? project.expanded,
|
||||
scripts,
|
||||
};
|
||||
});
|
||||
const previousProjectById = new Map(
|
||||
@@ -576,10 +550,6 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
|
||||
if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||
? normalizedThread.terminalIds
|
||||
: [...normalizedThread.terminalIds, action.terminalId];
|
||||
@@ -646,10 +616,6 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
|
||||
if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||
? normalizedThread.terminalIds
|
||||
: [...normalizedThread.terminalIds, action.terminalId];
|
||||
|
||||
@@ -1,16 +1,10 @@
|
||||
import type {
|
||||
ProjectScript as ContractProjectScript,
|
||||
ProviderEvent,
|
||||
ProviderSession,
|
||||
} from "@t3tools/contracts";
|
||||
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
|
||||
|
||||
export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
|
||||
export type RuntimeMode = "approval-required" | "full-access";
|
||||
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
export const DEFAULT_THREAD_TERMINAL_HEIGHT = 280;
|
||||
export const DEFAULT_THREAD_TERMINAL_ID = "default";
|
||||
export const MAX_THREAD_TERMINAL_COUNT = 4;
|
||||
export type ProjectScript = ContractProjectScript;
|
||||
|
||||
export interface ThreadTerminalGroup {
|
||||
id: string;
|
||||
@@ -43,7 +37,6 @@ export interface Project {
|
||||
cwd: string;
|
||||
model: string;
|
||||
expanded: boolean;
|
||||
scripts: ProjectScript[];
|
||||
}
|
||||
|
||||
export interface Thread {
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
{"version":"12.17.0","source":"https://raw.githubusercontent.com/vscode-icons/vscode-icons/v12.17.0/src/iconsManifest/languages.ts","generatedAt":"2026-02-17T20:03:11.362Z","extensionToLanguageId":{"as":"actionscript","ada":"ada","prw":"advpl","affect":"affectscript","agda":"agda","al":"al","alloy":"alloy","ansible":"ansible","g4":"antlr","any":"anyscript","htaccess":"apacheconf","cls":"apex","apib":"apiblueprint","apl":"apl","applescript":"applescript","adoc":"asciidoc","asp":"asp","asm":"arm","astro":"astro","ats":"ats","ahk":"ahk","au3":"autoit","am":"automake","avcs":"avro","azcli":"azcli","azure-pipelines.yml":"azure-pipelines","bal":"ballerina","bat":"bat","bats":"bats","bzl":"bazel","bf":"befunge","bicep":"bicep","bib":"bibtex","biml":"biml","bin":"code-text-binary","rast":"biome_syntax_tree","blade.php":"blade","blitzbasic":"blitzbasic","bolt":"bolt","bsq":"bosque","bru":"bruno","buf.yaml":"buf","lockb":"bun.lockb","c":"c","c3":"c3","cal":"c-al","cabal":"cabal","capnp":"capnp","casc":"casc","cddl":"cddl","ceylon":"ceylon","cfc":"cfc","cfm":"cfmhtml","circom":"circom","clojure":"clojure","clojurescript":"clojurescript","yml":"manifest-yaml","cmake":"cmake","cbl":"cobol","ql":"ql","coffee":"coffeescript","cfml":"cfml","confluence":"confluence","ckbk":"cookbook","instructions.md":"instructions","cpp":"cpp","cr":"crystal","cs":"csharp","css":"css","wxss":"css","acss":"css","mcss":"css","pcss":"css","postcss":"css","nss":"css","ccss":"css","less":"css","scss":"css","sass":"css","csv":"csv","feature":"cucumber","cu":"cuda","cypher":"cypher","pyx":"cython","dal":"dal","dart":"dart","dhall":"dhall","html":"django-html","diff":"diff","d":"d","hcl":"dockerbake","dtx":"doctex","env":"dotenv","dot":"dotjs","dox":"doxygen","drawio":"drawio","drl":"drools","dtd":"dtd","dust":"dustjs","dylan":"dylan","earthfile":"earthfile","edge":"edge","eex":"eex","es":"es","ex":"elixir","elm":"elm","erb":"erb","erl":"erlang","yaml":"esphome","xlsx":"excel","falcon":"falcon","fql":"fql","f":"fortran","ftl":"ftl","fs":"fsharp","fthtml":"fthtml","gspec":"galen","gml":"gml-gms","gcode":"gcode","gen":"genstat","git":"git-commit","gleam":"gleam","gjs":"glimmer-js","glsl":"glsl","glyphs":"glyphs","gp":"gnuplot","go":"go","mod":"go.mod","work":"go.work","api":"goctl","gd":"gdscript","gradle.kts":"gradle-kotlin-dsl","gr":"grain","gql":"graphql","gv":"dot","grit":"grit","groovy":"groovy","haml":"haml","hbs":"handlebars","prg":"harbour","hs":"haskell","haxe":"haxe","helm.tpl":"helm","hjson":"hjson","hlsl":"hlsl","hosts":"hosts","http":"http","aff":"hunspell.aff","hy":"hy","hypr":"hypr","icl":"icl","imba":"imba","4gl":"4GL","ini":"ini","ink":"ink","iss":"innosetup","io":"io","janet":"janet","java":"java","js":"javascript","mjs":"javascript","cjs":"javascript","es6":"javascript","jake":"javascript","jsm":"javascript","jsx":"javascript","njs":"javascript","pac":"javascript","sjs":"javascript","ssjs":"javascript","xsjs":"javascript","xsjslib":"javascript","jekyll":"jekyll","jenkins":"jenkins","jest-snap":"jest-snapshot","jinja":"jinja","json":"json","jsonc":"jsonc","jsonl":"jsonl","jsonnet":"jsonnet","json5":"json5","jl":"julia","id":"iodine","k":"k","kv":"kivy","ks":"kos","kt":"kotlin","kusto":"kusto","tex":"latex","lark":"lark","lat":"latino","lean":"lean4","flex":"lex","ly":"lilypond","lisp":"lisp","lhs":"literate haskell","log":"log","lol":"lolcode","lsl":"lsl","lua":"lua","m4":"m4","mk":"makefile","md":"markdown","markdown":"markdown","mdown":"markdown","mkd":"markdown","marko":"marko","mat":"matlab","ms":"maxscript","mdx":"mdx","mediawiki":"mediawiki","mel":"mel","mmd":"mermaid","metal":"metal","mcfunction":"bc-mcfunction","mjml":"mjml","pq":"powerquery","mojo":"mojo","ep":"mojolicious","mongo":"mongo","mson":"mson","mv":"mv","mvt":"mvt","ne":"nearley","nginx":"nginx","nim":"nim","nimble":"nimble","nix":"nix","nsi":"nsis","nunjucks":"nunjucks","nu":"nushell","m":"objective-c","mm":"objective-cpp","ml":"ocaml","o3":"ogone","w":"abl","things":"openhab","org":"org","pas":"pascal","pddl":"pddl","plan":"plan","happenings":"happenings","pl":"perl","pl6":"perl6","pgsql":"pgsql","php":"php","php4":"php","php5":"php","php7":"php","phtml":"php","phps":"php","phpt":"php","phar":"php","aw":"php","ctp":"php","inc":"php","php3":"php","php8":"php","module":"php","theme":"php","tpl":"php","pine":"pine","txt":"plaintext","dbgasm":"platformio-debug.disassembly","ddl":"plsql","po":"po","dib":"polyglot-notebook","polymer":"polymer","pony":"pony","ps":"postscript","ps1":"powershell","prisma":"prisma","pde":"pde","pro":"prolog","rules":"prometheus","properties":"java-properties","proto":"proto3","pug":"jade","pp":"puppet","purs":"purescript","arr":"pyret","pyscript":"pyscript","py":"python","pyi":"python","pyw":"python","pyc":"python","pyd":"python","pyo":"python","pxd":"python","pxi":"python","rpy":"python","cpy":"python","ipy":"python","pyowo":"pythowo","qvs":"qlik","qml":"qml","qs":"qsharp","r":"r","rkt":"racket","raku":"raku","cshtml":"razor","raml":"raLine truncated
|
||||
@@ -1 +0,0 @@
|
||||
{"iconDefinitions":{"_file":{"iconPath":"../../icons/default_file.svg"},"_folder":{"iconPath":"../../icons/default_folder.svg"},"_folder_open":{"iconPath":"../../icons/default_folder_opened.svg"},"_root_folder":{"iconPath":"../../icons/default_root_folder.svg"},"_root_folder_open":{"iconPath":"../../icons/default_root_folder_opened.svg"},"_file_light":{"iconPath":""},"_folder_light":{"iconPath":""},"_folder_light_open":{"iconPath":""},"_root_folder_light":{"iconPath":""},"_root_folder_light_open":{"iconPath":""},"_fd_android":{"iconPath":"../../icons/folder_type_android.svg"},"_fd_android_open":{"iconPath":"../../icons/folder_type_android_opened.svg"},"_fd_angular":{"iconPath":"../../icons/folder_type_angular.svg"},"_fd_angular_open":{"iconPath":"../../icons/folder_type_angular_opened.svg"},"_fd_apache":{"iconPath":"../../icons/folder_type_apache.svg"},"_fd_apache_open":{"iconPath":"../../icons/folder_type_apache_opened.svg"},"_fd_api":{"iconPath":"../../icons/folder_type_api.svg"},"_fd_api_open":{"iconPath":"../../icons/folder_type_api_opened.svg"},"_fd_app":{"iconPath":"../../icons/folder_type_app.svg"},"_fd_app_open":{"iconPath":"../../icons/folder_type_app_opened.svg"},"_fd_arangodb":{"iconPath":"../../icons/folder_type_arangodb.svg"},"_fd_arangodb_open":{"iconPath":"../../icons/folder_type_arangodb_opened.svg"},"_fd_asset":{"iconPath":"../../icons/folder_type_asset.svg"},"_fd_asset_open":{"iconPath":"../../icons/folder_type_asset_opened.svg"},"_fd_astro":{"iconPath":"../../icons/folder_type_astro.svg"},"_fd_astro_open":{"iconPath":"../../icons/folder_type_astro_opened.svg"},"_fd_audio":{"iconPath":"../../icons/folder_type_audio.svg"},"_fd_audio_open":{"iconPath":"../../icons/folder_type_audio_opened.svg"},"_fd_aurelia":{"iconPath":"../../icons/folder_type_aurelia.svg"},"_fd_aurelia_open":{"iconPath":"../../icons/folder_type_aurelia_opened.svg"},"_fd_aws":{"iconPath":"../../icons/folder_type_aws.svg"},"_fd_aws_open":{"iconPath":"../../icons/folder_type_aws_opened.svg"},"_fd_azure":{"iconPath":"../../icons/folder_type_azure.svg"},"_fd_azure_open":{"iconPath":"../../icons/folder_type_azure_opened.svg"},"_fd_azurepipelines":{"iconPath":"../../icons/folder_type_azurepipelines.svg"},"_fd_azurepipelines_open":{"iconPath":"../../icons/folder_type_azurepipelines_opened.svg"},"_fd_binary":{"iconPath":"../../icons/folder_type_binary.svg"},"_fd_binary_open":{"iconPath":"../../icons/folder_type_binary_opened.svg"},"_fd_bloc":{"iconPath":"../../icons/folder_type_bloc.svg"},"_fd_bloc_open":{"iconPath":"../../icons/folder_type_bloc_opened.svg"},"_fd_blueprint":{"iconPath":"../../icons/folder_type_blueprint.svg"},"_fd_blueprint_open":{"iconPath":"../../icons/folder_type_blueprint_opened.svg"},"_fd_bot":{"iconPath":"../../icons/folder_type_bot.svg"},"_fd_bot_open":{"iconPath":"../../icons/folder_type_bot_opened.svg"},"_fd_bower":{"iconPath":"../../icons/folder_type_bower.svg"},"_fd_bower_open":{"iconPath":"../../icons/folder_type_bower_opened.svg"},"_fd_buildkite":{"iconPath":"../../icons/folder_type_buildkite.svg"},"_fd_buildkite_open":{"iconPath":"../../icons/folder_type_buildkite_opened.svg"},"_fd_cake":{"iconPath":"../../icons/folder_type_cake.svg"},"_fd_cake_open":{"iconPath":"../../icons/folder_type_cake_opened.svg"},"_fd_cargo":{"iconPath":"../../icons/folder_type_cargo.svg"},"_fd_cargo_open":{"iconPath":"../../icons/folder_type_cargo_opened.svg"},"_fd_certificate":{"iconPath":"../../icons/folder_type_certificate.svg"},"_fd_certificate_open":{"iconPath":"../../icons/folder_type_certificate_opened.svg"},"_fd_changesets":{"iconPath":"../../icons/folder_type_changesets.svg"},"_fd_changesets_open":{"iconPath":"../../icons/folder_type_changesets_opened.svg"},"_fd_chef":{"iconPath":"../../icons/folder_type_chef.svg"},"_fd_chef_open":{"iconPath":"../../icons/folder_type_chef_opened.svg"},"_fd_circleci":{"iconPath":"../../icons/folder_type_circleci.svg"},"_fd_circleci_open":{"iconPath":"../../icons/folder_type_circleci_opened.svg"},"_fd_claude":{"iconPath":"../../icons/folder_type_claude.svg"},"_fd_claude_open":{"iconPath":"../../icons/folder_type_claude_opened.svg"},"_fd_cli":{"iconPath":"../../icons/folder_type_cli.svg"},"_fd_cli_open":{"iconPath":"../../icons/folder_type_cli_opened.svg"},"_fd_client":{"iconPath":"../../icons/folder_type_client.svg"},"_fd_client_open":{"iconPath":"../../icons/folder_type_client_opened.svg"},"_fd_cloudflare":{"iconPath":"../../icons/folder_type_cloudflare.svg"},"_fd_cloudflare_open":{"iconPath":"../../icons/folder_type_cloudflare_opened.svg"},"_fd_cmake":{"iconPath":"../../icons/folder_type_cmake.svg"},"_fd_cmake_open":{"iconPath":"../../icons/folder_type_cmake_opened.svg"},"_fd_common":{"iconPath":"../../icons/folder_type_common.svg"},"_fd_common_open":{"iconPath":"../../icons/folder_type_common_opened.svg"},"_fd_component":{"iconPath":"../../icons/folder_type_component.svg"},"_fd_component_open":{"iconPath":"../../icons/folder_type_component_opened.svg"},"_fd_composer":{"iconPath":".Line truncated
|
||||
@@ -1,50 +0,0 @@
|
||||
import { assert, describe, it } from "vitest";
|
||||
|
||||
import { getVscodeIconUrlForEntry } from "./vscode-icons";
|
||||
|
||||
describe("getVscodeIconUrlForEntry", () => {
|
||||
it("uses exact filename matches from the vscode-icons manifest", () => {
|
||||
const darkUrl = getVscodeIconUrlForEntry("pnpm-workspace.yaml", "file", "dark");
|
||||
const lightUrl = getVscodeIconUrlForEntry("pnpm-workspace.yaml", "file", "light");
|
||||
|
||||
assert.isTrue(darkUrl.endsWith("/file_type_pnpm.svg"));
|
||||
assert.isTrue(lightUrl.endsWith("/file_type_light_pnpm.svg"));
|
||||
});
|
||||
|
||||
it("uses longest extension match for compound extensions", () => {
|
||||
const iconUrl = getVscodeIconUrlForEntry("tsconfig.tsbuildinfo", "file", "dark");
|
||||
const manifestStyleUrl = getVscodeIconUrlForEntry("buf.yaml", "file", "dark");
|
||||
assert.isTrue(iconUrl.endsWith("/file_type_tsbuildinfo.svg"));
|
||||
assert.isTrue(manifestStyleUrl.endsWith("/file_type_buf.svg"));
|
||||
});
|
||||
|
||||
it("uses folder mappings and light-aware filename mappings", () => {
|
||||
const folderUrl = getVscodeIconUrlForEntry("packages/src", "directory", "light");
|
||||
const fileUrl = getVscodeIconUrlForEntry("AGENTS.md", "file", "light");
|
||||
|
||||
assert.isTrue(folderUrl.endsWith("/folder_type_src.svg"));
|
||||
assert.isTrue(fileUrl.endsWith("/file_type_light_agents.svg"));
|
||||
});
|
||||
|
||||
it("falls back to language-based mappings for path-only cases", () => {
|
||||
const tsxUrl = getVscodeIconUrlForEntry("checkbox.tsx", "file", "light");
|
||||
const dockerfileUrl = getVscodeIconUrlForEntry("Dockerfile", "file", "dark");
|
||||
const shellUrl = getVscodeIconUrlForEntry("entrypoint.sh", "file", "dark");
|
||||
const cursorRulesUrl = getVscodeIconUrlForEntry("general.mdc", "file", "dark");
|
||||
const githubWorkflowUrl = getVscodeIconUrlForEntry(".github/workflows/ci.yml", "file", "light");
|
||||
|
||||
assert.isTrue(tsxUrl.endsWith("/file_type_reactts.svg"));
|
||||
assert.isTrue(dockerfileUrl.endsWith("/file_type_docker.svg"));
|
||||
assert.isTrue(shellUrl.endsWith("/file_type_shell.svg"));
|
||||
assert.isTrue(cursorRulesUrl.endsWith("/file_type_markdown.svg"));
|
||||
assert.isTrue(githubWorkflowUrl.endsWith("/file_type_light_yaml.svg"));
|
||||
});
|
||||
|
||||
it("falls back to defaults when there is no match", () => {
|
||||
const fileUrl = getVscodeIconUrlForEntry("foo.unknown-ext", "file", "dark");
|
||||
const folderUrl = getVscodeIconUrlForEntry("totally-unknown-folder", "directory", "dark");
|
||||
|
||||
assert.isTrue(fileUrl.endsWith("/default_file.svg"));
|
||||
assert.isTrue(folderUrl.endsWith("/default_folder.svg"));
|
||||
});
|
||||
});
|
||||
@@ -1,168 +0,0 @@
|
||||
import vscodeIconsManifest from "./vscode-icons-manifest.json";
|
||||
import languageAssociationsData from "./vscode-icons-language-associations.json";
|
||||
|
||||
const VSCODE_ICONS_VERSION = "v12.17.0";
|
||||
const VSCODE_ICONS_BASE_URL = `https://cdn.jsdelivr.net/gh/vscode-icons/vscode-icons@${VSCODE_ICONS_VERSION}/icons`;
|
||||
|
||||
interface IconDefinition {
|
||||
iconPath: string;
|
||||
}
|
||||
|
||||
interface IconLookupSection {
|
||||
file?: string;
|
||||
folder?: string;
|
||||
fileNames: Record<string, string>;
|
||||
fileExtensions: Record<string, string>;
|
||||
folderNames: Record<string, string>;
|
||||
languageIds?: Record<string, string>;
|
||||
}
|
||||
|
||||
interface VscodeIconsManifest extends IconLookupSection {
|
||||
iconDefinitions: Record<string, IconDefinition>;
|
||||
light: IconLookupSection;
|
||||
}
|
||||
|
||||
interface LanguageAssociations {
|
||||
version: string;
|
||||
extensionToLanguageId: Record<string, string>;
|
||||
fileNameToLanguageId: Record<string, string>;
|
||||
}
|
||||
|
||||
const manifest = vscodeIconsManifest as VscodeIconsManifest;
|
||||
const languageAssociations = languageAssociationsData as LanguageAssociations;
|
||||
const iconDefinitions = manifest.iconDefinitions;
|
||||
|
||||
const darkFileNames = toLowercaseLookup(manifest.fileNames);
|
||||
const lightFileNames = toLowercaseLookup(manifest.light.fileNames);
|
||||
const darkFileExtensions = toLowercaseLookup(manifest.fileExtensions);
|
||||
const lightFileExtensions = toLowercaseLookup(manifest.light.fileExtensions);
|
||||
const darkFolderNames = toLowercaseLookup(manifest.folderNames);
|
||||
const lightFolderNames = toLowercaseLookup(manifest.light.folderNames);
|
||||
const darkLanguageIds = toLowercaseLookup(manifest.languageIds ?? {});
|
||||
const lightLanguageIds = toLowercaseLookup(manifest.light.languageIds ?? {});
|
||||
const languageIdByExtension = toLowercaseLookup(languageAssociations.extensionToLanguageId);
|
||||
const languageIdByFileName = toLowercaseLookup(languageAssociations.fileNameToLanguageId);
|
||||
const localLanguageIdByExtensionOverrides = {
|
||||
// Cursor rules files (*.mdc) are commonly treated as markdown in VSCode/Cursor.
|
||||
mdc: "markdown",
|
||||
// Upstream languages.ts maps yml/yaml to specialized language ids that can produce
|
||||
// non-generic YAML icons (for example cloudfoundry/esphome). Prefer the base YAML icon
|
||||
// unless a more specific basename/extension match (e.g. azure-pipelines.yml) is found.
|
||||
yml: "yaml",
|
||||
yaml: "yaml",
|
||||
} as const;
|
||||
|
||||
const defaultDarkFileIconDefinition = manifest.file ?? "_file";
|
||||
const defaultLightFileIconDefinition = manifest.light.file ?? defaultDarkFileIconDefinition;
|
||||
const defaultDarkFolderIconDefinition = manifest.folder ?? "_folder";
|
||||
const defaultLightFolderIconDefinition = manifest.light.folder ?? defaultDarkFolderIconDefinition;
|
||||
|
||||
function toLowercaseLookup(source: Record<string, string>): Record<string, string> {
|
||||
const entries = Object.entries(source);
|
||||
const lookup: Record<string, string> = {};
|
||||
for (const [key, value] of entries) {
|
||||
lookup[key.toLowerCase()] = value;
|
||||
}
|
||||
return lookup;
|
||||
}
|
||||
|
||||
export function basenameOfPath(pathValue: string): string {
|
||||
const slashIndex = pathValue.lastIndexOf("/");
|
||||
if (slashIndex === -1) return pathValue;
|
||||
return pathValue.slice(slashIndex + 1);
|
||||
}
|
||||
|
||||
function extensionCandidates(fileName: string): string[] {
|
||||
const candidates = new Set<string>();
|
||||
if (fileName.includes(".")) {
|
||||
candidates.add(fileName);
|
||||
}
|
||||
let dotIndex = fileName.indexOf(".");
|
||||
while (dotIndex !== -1 && dotIndex < fileName.length - 1) {
|
||||
const candidate = fileName.slice(dotIndex + 1);
|
||||
if (candidate.length > 0) {
|
||||
candidates.add(candidate);
|
||||
}
|
||||
dotIndex = fileName.indexOf(".", dotIndex + 1);
|
||||
}
|
||||
return [...candidates];
|
||||
}
|
||||
|
||||
function resolveLanguageFallbackDefinition(
|
||||
pathValue: string,
|
||||
theme: "light" | "dark",
|
||||
): string | null {
|
||||
const basename = basenameOfPath(pathValue).toLowerCase();
|
||||
const languageIds = theme === "light" ? lightLanguageIds : darkLanguageIds;
|
||||
|
||||
const fromBasenameLanguage = languageIdByFileName[basename];
|
||||
if (fromBasenameLanguage) {
|
||||
return languageIds[fromBasenameLanguage] ?? darkLanguageIds[fromBasenameLanguage] ?? null;
|
||||
}
|
||||
|
||||
for (const candidate of extensionCandidates(basename)) {
|
||||
const languageId =
|
||||
localLanguageIdByExtensionOverrides[
|
||||
candidate as keyof typeof localLanguageIdByExtensionOverrides
|
||||
] ?? languageIdByExtension[candidate];
|
||||
if (!languageId) continue;
|
||||
return languageIds[languageId] ?? darkLanguageIds[languageId] ?? null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function iconFilenameForDefinitionKey(definitionKey: string | undefined): string | null {
|
||||
if (!definitionKey) return null;
|
||||
const iconPath = iconDefinitions[definitionKey]?.iconPath;
|
||||
if (!iconPath) return null;
|
||||
const slashIndex = iconPath.lastIndexOf("/");
|
||||
if (slashIndex === -1) {
|
||||
return iconPath;
|
||||
}
|
||||
return iconPath.slice(slashIndex + 1);
|
||||
}
|
||||
|
||||
function resolveFileDefinition(pathValue: string, theme: "light" | "dark"): string {
|
||||
const basename = basenameOfPath(pathValue).toLowerCase();
|
||||
const fileNames = theme === "light" ? lightFileNames : darkFileNames;
|
||||
const fileExtensions = theme === "light" ? lightFileExtensions : darkFileExtensions;
|
||||
|
||||
const fromFileName = fileNames[basename] ?? darkFileNames[basename];
|
||||
if (fromFileName) return fromFileName;
|
||||
|
||||
for (const candidate of extensionCandidates(basename)) {
|
||||
const fromExtension = fileExtensions[candidate] ?? darkFileExtensions[candidate];
|
||||
if (fromExtension) return fromExtension;
|
||||
}
|
||||
|
||||
const fromLanguage = resolveLanguageFallbackDefinition(pathValue, theme);
|
||||
if (fromLanguage) return fromLanguage;
|
||||
|
||||
return theme === "light" ? defaultLightFileIconDefinition : defaultDarkFileIconDefinition;
|
||||
}
|
||||
|
||||
function resolveFolderDefinition(pathValue: string, theme: "light" | "dark"): string {
|
||||
const basename = basenameOfPath(pathValue).toLowerCase();
|
||||
const folderNames = theme === "light" ? lightFolderNames : darkFolderNames;
|
||||
return (
|
||||
folderNames[basename] ??
|
||||
darkFolderNames[basename] ??
|
||||
(theme === "light" ? defaultLightFolderIconDefinition : defaultDarkFolderIconDefinition)
|
||||
);
|
||||
}
|
||||
|
||||
export function getVscodeIconUrlForEntry(
|
||||
pathValue: string,
|
||||
kind: "file" | "directory",
|
||||
theme: "light" | "dark",
|
||||
): string {
|
||||
const definitionKey =
|
||||
kind === "directory"
|
||||
? resolveFolderDefinition(pathValue, theme)
|
||||
: resolveFileDefinition(pathValue, theme);
|
||||
const iconFilename =
|
||||
iconFilenameForDefinitionKey(definitionKey) ??
|
||||
(kind === "directory" ? "default_folder.svg" : "default_file.svg");
|
||||
return `${VSCODE_ICONS_BASE_URL}/${iconFilename}`;
|
||||
}
|
||||
@@ -98,8 +98,6 @@ export function createWsNativeApi(): NativeApi {
|
||||
list: () => transport.request(WS_METHODS.projectsList),
|
||||
add: (input) => transport.request(WS_METHODS.projectsAdd, input),
|
||||
remove: (input) => transport.request(WS_METHODS.projectsRemove, input),
|
||||
searchEntries: (input) => transport.request(WS_METHODS.projectsSearchEntries, input),
|
||||
updateScripts: (input) => transport.request(WS_METHODS.projectsUpdateScripts, input),
|
||||
},
|
||||
shell: {
|
||||
openInEditor: (cwd, editor) =>
|
||||
@@ -143,7 +141,6 @@ export function createWsNativeApi(): NativeApi {
|
||||
},
|
||||
server: {
|
||||
getConfig: () => transport.request(WS_METHODS.serverGetConfig),
|
||||
upsertKeybinding: (input) => transport.request(WS_METHODS.serverUpsertKeybinding, input),
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -34,12 +34,12 @@
|
||||
"t3": "./dist/index.mjs",
|
||||
},
|
||||
"dependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/node": "^22.10.2",
|
||||
"@types/ws": "^8.5.13",
|
||||
@@ -53,8 +53,8 @@
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
"@tanstack/react-virtual": "^3.13.18",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
@@ -426,19 +426,13 @@
|
||||
|
||||
"@tailwindcss/vite": ["@tailwindcss/[email protected]", "", { "dependencies": { "@tailwindcss/node": "4.1.18", "@tailwindcss/oxide": "4.1.18", "tailwindcss": "4.1.18" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7" } }, "sha512-jVA+/UpKL1vRLg6Hkao5jldawNmRo7mQYrZtNHMIVpLfLhDml5nMRUo/8MwoX2vNXvnaXNNMedrMfMugAVX1nA=="],
|
||||
|
||||
"@tanstack/devtools-event-client": ["@tanstack/[email protected]", "", {}, "sha512-RPfGuk2bDZgcu9bAJodvO2lnZeHuz4/71HjZ0bGb/SPg8+lyTA+RLSKQvo7fSmPSi8/vcH3aKQ8EM9ywf1olaw=="],
|
||||
|
||||
"@tanstack/pacer": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/devtools-event-client": "^0.4.0", "@tanstack/store": "^0.8.0" } }, "sha512-qhCRSFei0hokQr3xYcQXqxsRD/LKlgHCxHXtKHrQoImp4x2Zu6tUOpUGVH4y2qexIrzSu3aibQBNNfC3Eay6Mg=="],
|
||||
|
||||
"@tanstack/query-core": ["@tanstack/[email protected]", "", {}, "sha512-OMD2HLpNouXEfZJWcKeVKUgQ5n+n3A2JFmBaScpNDUqSrQSjiveC7dKMe53uJUg1nDG16ttFPz2xfilz6i2uVg=="],
|
||||
|
||||
"@tanstack/react-pacer": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/pacer": "0.18.0", "@tanstack/react-store": "^0.8.0" }, "peerDependencies": { "react": ">=16.8", "react-dom": ">=16.8" } }, "sha512-coj8ULAuR0qFpjAKD44gTgRuZyjxU6Xu+IX5MwwYvr4e61OtZcJshaExoOBKpCGde0Edb12jDnzzj2Im13Qm9Q=="],
|
||||
|
||||
"@tanstack/react-query": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/query-core": "5.90.20" }, "peerDependencies": { "react": "^18 || ^19" } }, "sha512-0Lu6y5t+tvlTJMTO7oh5NSpJfpg/5D41LlThfepTixPYkJ0sE2Jj0m0f6yYqujBwIXlId87e234+MxG3D3g7kg=="],
|
||||
|
||||
"@tanstack/react-store": ["@tanstack/react-[email protected].1", "", { "dependencies": { "@tanstack/store": "0.8.1", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-XItJt+rG8c5Wn/2L/bnxys85rBpm0BfMbhb4zmPVLXAKY9POrp1xd6IbU4PKoOI+jSEGc3vntPRfLGSgXfE2Ig=="],
|
||||
"@tanstack/react-virtual": ["@tanstack/react-[email protected].18", "", { "dependencies": { "@tanstack/virtual-core": "3.13.18" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-dZkhyfahpvlaV0rIKnvQiVoWPyURppl6w4m9IwMDpuIjcJ1sD9YGWrt0wISvgU7ewACXx2Ct46WPgI6qAD4v6A=="],
|
||||
|
||||
"@tanstack/store": ["@tanstack/[email protected].1", "", {}, "sha512-PtOisLjUZPz5VyPRSCGjNOlwTvabdTBQ2K80DpVL1chGVr35WRxfeavAPdNq6pm/t7F8GhoR2qtmkkqtCEtHYw=="],
|
||||
"@tanstack/virtual-core": ["@tanstack/[email protected].18", "", {}, "sha512-Mx86Hqu1k39icq2Zusq+Ey2J6dDWTjDvEv43PJtRCoEYTLyfaPnxIQ6iy7YAOK0NV/qOEmZQ/uCufrppZxTgcg=="],
|
||||
|
||||
"@tybys/wasm-util": ["@tybys/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg=="],
|
||||
|
||||
|
||||
+3
-3
@@ -18,10 +18,10 @@
|
||||
"lint": "oxlint --report-unused-disable-directives",
|
||||
"test": "turbo run test",
|
||||
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
|
||||
"test:desktop-perf": "node scripts/desktop-perf-trace.mjs",
|
||||
"test:desktop-perf:post": "node scripts/desktop-perf-trace.mjs --post-pr",
|
||||
"fmt": "oxfmt",
|
||||
"build:contracts": "turbo run build --filter=@t3tools/contracts",
|
||||
"clean": "rm -rf node_modules apps/*/node_modules packages/*/node_modules apps/*/dist apps/*/dist-electron packages/*/dist .turbo apps/*/.turbo packages/*/.turbo",
|
||||
"sync:vscode-icons": "node scripts/sync-vscode-icons.mjs"
|
||||
"build:contracts": "turbo run build --filter=@t3tools/contracts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"oxfmt": "^0.28.0",
|
||||
|
||||
@@ -29,11 +29,7 @@ import type {
|
||||
ProjectAddInput,
|
||||
ProjectAddResult,
|
||||
ProjectListResult,
|
||||
ProjectSearchEntriesInput,
|
||||
ProjectSearchEntriesResult,
|
||||
ProjectRemoveInput,
|
||||
ProjectUpdateScriptsInput,
|
||||
ProjectUpdateScriptsResult,
|
||||
} from "./project";
|
||||
import type { ServerConfig } from "./server";
|
||||
import type {
|
||||
@@ -46,7 +42,6 @@ import type {
|
||||
TerminalWriteInput,
|
||||
} from "./terminal";
|
||||
import type { NewTodoInput, Todo } from "./todo";
|
||||
import type { ServerUpsertKeybindingInput, ServerUpsertKeybindingResult } from "./server";
|
||||
|
||||
export const EDITORS = [
|
||||
{ id: "cursor", label: "Cursor", command: "cursor" },
|
||||
@@ -95,8 +90,6 @@ export interface NativeApi {
|
||||
list: () => Promise<ProjectListResult>;
|
||||
add: (input: ProjectAddInput) => Promise<ProjectAddResult>;
|
||||
remove: (input: ProjectRemoveInput) => Promise<void>;
|
||||
searchEntries: (input: ProjectSearchEntriesInput) => Promise<ProjectSearchEntriesResult>;
|
||||
updateScripts: (input: ProjectUpdateScriptsInput) => Promise<ProjectUpdateScriptsResult>;
|
||||
};
|
||||
shell: {
|
||||
openInEditor: (cwd: string, editor: EditorId) => Promise<void>;
|
||||
@@ -123,6 +116,5 @@ export interface NativeApi {
|
||||
};
|
||||
server: {
|
||||
getConfig: () => Promise<ServerConfig>;
|
||||
upsertKeybinding: (input: ServerUpsertKeybindingInput) => Promise<ServerUpsertKeybindingResult>;
|
||||
};
|
||||
}
|
||||
@@ -32,19 +32,11 @@ describe("keybindings contracts", () => {
|
||||
assert.throws(() =>
|
||||
keybindingRuleSchema.parse({
|
||||
key: "mod+j",
|
||||
command: "script.Test.run",
|
||||
command: "invalid.command",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts dynamic script run commands", () => {
|
||||
const parsed = keybindingRuleSchema.parse({
|
||||
key: "mod+r",
|
||||
command: "script.setup.run",
|
||||
});
|
||||
assert.strictEqual(parsed.command, "script.setup.run");
|
||||
});
|
||||
|
||||
it("parses keybindings array payload", () => {
|
||||
const parsed = keybindingsConfigSchema.parse([
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const STATIC_KEYBINDING_COMMANDS = [
|
||||
export const keybindingCommandSchema = z.enum([
|
||||
"terminal.toggle",
|
||||
"terminal.split",
|
||||
"terminal.new",
|
||||
@@ -8,16 +8,6 @@ export const STATIC_KEYBINDING_COMMANDS = [
|
||||
"chat.new",
|
||||
"chat.newLocal",
|
||||
"editor.openFavorite",
|
||||
] as const;
|
||||
|
||||
export const keybindingCommandSchema = z.union([
|
||||
z.enum(STATIC_KEYBINDING_COMMANDS),
|
||||
z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(96)
|
||||
.regex(/^script\.[a-z0-9][a-z0-9-]*\.run$/),
|
||||
]);
|
||||
|
||||
const keybindingValueSchema = z.string().trim().min(1).max(64);
|
||||
|
||||
@@ -3,12 +3,8 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
projectAddInputSchema,
|
||||
projectAddResultSchema,
|
||||
projectSearchEntriesInputSchema,
|
||||
projectSearchEntriesResultSchema,
|
||||
projectListResultSchema,
|
||||
projectRemoveInputSchema,
|
||||
projectUpdateScriptsInputSchema,
|
||||
projectUpdateScriptsResultSchema,
|
||||
} from "./project";
|
||||
|
||||
describe("project contracts", () => {
|
||||
@@ -18,7 +14,6 @@ describe("project contracts", () => {
|
||||
id: "project-1",
|
||||
cwd: "/tmp/project",
|
||||
name: "project",
|
||||
scripts: [],
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
@@ -39,7 +34,6 @@ describe("project contracts", () => {
|
||||
id: "project-1",
|
||||
cwd: "/tmp/project",
|
||||
name: "project",
|
||||
scripts: [],
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
@@ -52,96 +46,4 @@ describe("project contracts", () => {
|
||||
const parsed = projectRemoveInputSchema.parse({ id: "project-1" });
|
||||
expect(parsed.id).toBe("project-1");
|
||||
});
|
||||
|
||||
it("parses workspace entry search input with defaults", () => {
|
||||
const parsed = projectSearchEntriesInputSchema.parse({
|
||||
cwd: " /tmp/project ",
|
||||
query: " src ",
|
||||
});
|
||||
|
||||
expect(parsed).toEqual({
|
||||
cwd: "/tmp/project",
|
||||
query: "src",
|
||||
limit: 80,
|
||||
});
|
||||
});
|
||||
|
||||
it("parses workspace entry search result", () => {
|
||||
const parsed = projectSearchEntriesResultSchema.parse({
|
||||
entries: [
|
||||
{
|
||||
path: "src/components",
|
||||
kind: "directory",
|
||||
parentPath: "src",
|
||||
},
|
||||
{
|
||||
path: "src/components/Button.tsx",
|
||||
kind: "file",
|
||||
parentPath: "src/components",
|
||||
},
|
||||
],
|
||||
truncated: false,
|
||||
});
|
||||
|
||||
expect(parsed.entries).toHaveLength(2);
|
||||
expect(parsed.entries[0]?.kind).toBe("directory");
|
||||
});
|
||||
|
||||
it("parses update scripts input", () => {
|
||||
const parsed = projectUpdateScriptsInputSchema.parse({
|
||||
id: "project-1",
|
||||
scripts: [
|
||||
{
|
||||
id: "test",
|
||||
name: "Test",
|
||||
command: "bun test",
|
||||
icon: "test",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(parsed.scripts).toHaveLength(1);
|
||||
expect(parsed.scripts[0]?.id).toBe("test");
|
||||
});
|
||||
|
||||
it("parses debug icon in scripts", () => {
|
||||
const parsed = projectUpdateScriptsInputSchema.parse({
|
||||
id: "project-1",
|
||||
scripts: [
|
||||
{
|
||||
id: "debug",
|
||||
name: "Debug",
|
||||
command: "bun --inspect test",
|
||||
icon: "debug",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(parsed.scripts[0]?.icon).toBe("debug");
|
||||
});
|
||||
|
||||
it("parses update scripts result", () => {
|
||||
const parsed = projectUpdateScriptsResultSchema.parse({
|
||||
project: {
|
||||
id: "project-1",
|
||||
cwd: "/tmp/project",
|
||||
name: "project",
|
||||
scripts: [
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
command: "bun install",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
expect(parsed.project.scripts[0]?.id).toBe("setup");
|
||||
});
|
||||
});
|
||||
@@ -1,38 +1,9 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const PROJECT_SCRIPT_ICON_VALUES = [
|
||||
"play",
|
||||
"test",
|
||||
"lint",
|
||||
"configure",
|
||||
"build",
|
||||
"debug",
|
||||
] as const;
|
||||
|
||||
export const projectScriptIconSchema = z.enum(PROJECT_SCRIPT_ICON_VALUES);
|
||||
|
||||
export const projectScriptSchema = z
|
||||
.object({
|
||||
id: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(64)
|
||||
.regex(/^[a-z0-9][a-z0-9-]*$/),
|
||||
name: z.string().trim().min(1).max(64),
|
||||
command: z.string().trim().min(1).max(10_000),
|
||||
icon: projectScriptIconSchema,
|
||||
runOnWorktreeCreate: z.boolean().default(false),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const projectScriptsSchema = z.array(projectScriptSchema).max(64);
|
||||
|
||||
export const projectRecordSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
cwd: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
scripts: projectScriptsSchema.default([]),
|
||||
createdAt: z.string().datetime(),
|
||||
updatedAt: z.string().datetime(),
|
||||
});
|
||||
@@ -52,83 +23,8 @@ export const projectRemoveInputSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
});
|
||||
|
||||
export const PROJECT_SEARCH_ENTRIES_MAX_LIMIT = 200;
|
||||
|
||||
export const projectSearchEntriesInputSchema = z.object({
|
||||
cwd: z.string().trim().min(1),
|
||||
query: z.string().trim().max(256).default(""),
|
||||
limit: z.number().int().min(1).max(PROJECT_SEARCH_ENTRIES_MAX_LIMIT).default(80),
|
||||
});
|
||||
|
||||
export const projectEntryKindSchema = z.enum(["file", "directory"]);
|
||||
|
||||
export const projectEntrySchema = z.object({
|
||||
path: z.string().min(1),
|
||||
kind: projectEntryKindSchema,
|
||||
parentPath: z.string().optional(),
|
||||
});
|
||||
|
||||
export const projectSearchEntriesResultSchema = z.object({
|
||||
entries: z.array(projectEntrySchema),
|
||||
truncated: z.boolean(),
|
||||
});
|
||||
|
||||
export const projectUpdateScriptsInputSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
scripts: projectScriptsSchema,
|
||||
});
|
||||
|
||||
export const projectUpdateScriptsResultSchema = z.object({
|
||||
project: projectRecordSchema,
|
||||
});
|
||||
|
||||
export type ProjectScriptIcon = z.infer<typeof projectScriptIconSchema>;
|
||||
export type ProjectScript = z.infer<typeof projectScriptSchema>;
|
||||
export type ProjectRecord = z.infer<typeof projectRecordSchema>;
|
||||
export type ProjectListResult = z.infer<typeof projectListResultSchema>;
|
||||
export type ProjectAddInput = z.input<typeof projectAddInputSchema>;
|
||||
export type ProjectAddResult = z.infer<typeof projectAddResultSchema>;
|
||||
export type ProjectRemoveInput = z.input<typeof projectRemoveInputSchema>;
|
||||
export type ProjectSearchEntriesInput = z.input<typeof projectSearchEntriesInputSchema>;
|
||||
export type ProjectEntryKind = z.infer<typeof projectEntryKindSchema>;
|
||||
export type ProjectEntry = z.infer<typeof projectEntrySchema>;
|
||||
export type ProjectSearchEntriesResult = z.infer<typeof projectSearchEntriesResultSchema>;
|
||||
export type ProjectUpdateScriptsInput = z.input<typeof projectUpdateScriptsInputSchema>;
|
||||
export type ProjectUpdateScriptsResult = z.infer<typeof projectUpdateScriptsResultSchema>;
|
||||
|
||||
/**
|
||||
* Deduplicate scripts by ID (first occurrence wins), trim string fields,
|
||||
* and enforce at most one script with `runOnWorktreeCreate: true`.
|
||||
*/
|
||||
export function normalizeProjectScripts(scripts: readonly ProjectScript[]): ProjectScript[] {
|
||||
const seenIds = new Set<string>();
|
||||
const deduped: ProjectScript[] = [];
|
||||
for (const script of scripts) {
|
||||
const id = script.id.trim();
|
||||
if (id.length === 0 || seenIds.has(id)) continue;
|
||||
seenIds.add(id);
|
||||
deduped.push({
|
||||
id,
|
||||
name: script.name.trim(),
|
||||
command: script.command.trim(),
|
||||
icon: script.icon,
|
||||
runOnWorktreeCreate: script.runOnWorktreeCreate,
|
||||
});
|
||||
}
|
||||
|
||||
let setupAssigned = false;
|
||||
const normalized: ProjectScript[] = [];
|
||||
for (const script of deduped) {
|
||||
if (!script.runOnWorktreeCreate) {
|
||||
normalized.push(script);
|
||||
continue;
|
||||
}
|
||||
if (!setupAssigned) {
|
||||
setupAssigned = true;
|
||||
normalized.push(script);
|
||||
continue;
|
||||
}
|
||||
normalized.push({ ...script, runOnWorktreeCreate: false });
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
@@ -1,17 +1,9 @@
|
||||
import { z } from "zod";
|
||||
import { keybindingRuleSchema, resolvedKeybindingsConfigSchema } from "./keybindings";
|
||||
import { resolvedKeybindingsConfigSchema } from "./keybindings";
|
||||
|
||||
export const serverConfigSchema = z.object({
|
||||
cwd: z.string().min(1),
|
||||
keybindings: resolvedKeybindingsConfigSchema.default([]),
|
||||
});
|
||||
|
||||
export const serverUpsertKeybindingInputSchema = keybindingRuleSchema;
|
||||
|
||||
export const serverUpsertKeybindingResultSchema = z.object({
|
||||
keybindings: resolvedKeybindingsConfigSchema.default([]),
|
||||
});
|
||||
|
||||
export type ServerConfig = z.infer<typeof serverConfigSchema>;
|
||||
export type ServerUpsertKeybindingInput = z.infer<typeof serverUpsertKeybindingInputSchema>;
|
||||
export type ServerUpsertKeybindingResult = z.infer<typeof serverUpsertKeybindingResultSchema>;
|
||||
@@ -15,8 +15,6 @@ export const WS_METHODS = {
|
||||
projectsList: "projects.list",
|
||||
projectsAdd: "projects.add",
|
||||
projectsRemove: "projects.remove",
|
||||
projectsSearchEntries: "projects.searchEntries",
|
||||
projectsUpdateScripts: "projects.updateScripts",
|
||||
|
||||
// Shell methods
|
||||
shellOpenInEditor: "shell.openInEditor",
|
||||
@@ -42,7 +40,6 @@ export const WS_METHODS = {
|
||||
|
||||
// Server meta
|
||||
serverGetConfig: "server.getConfig",
|
||||
serverUpsertKeybinding: "server.upsertKeybinding",
|
||||
} as const;
|
||||
|
||||
// ── Push Event Channels ──────────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,842 @@
|
||||
import { spawn, execFileSync } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
const repoRoot = path.resolve(import.meta.dirname, "..");
|
||||
const marker = "<!-- desktop-perf-trace-summary -->";
|
||||
const defaultPerfProjects = [
|
||||
{
|
||||
id: "perf-project-1",
|
||||
cwd: "/tmp/perf/codething-mvp",
|
||||
name: "codething-mvp",
|
||||
},
|
||||
{
|
||||
id: "perf-project-2",
|
||||
cwd: "/tmp/perf/contracts-bench",
|
||||
name: "contracts-bench",
|
||||
},
|
||||
];
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
let postPr = false;
|
||||
let seedPath = null;
|
||||
|
||||
for (let index = 2; index < argv.length; index += 1) {
|
||||
const arg = argv[index];
|
||||
if (arg === "--post-pr") {
|
||||
postPr = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--seed") {
|
||||
const value = argv[index + 1];
|
||||
if (!value || value.startsWith("--")) {
|
||||
throw new Error("--seed requires a file path");
|
||||
}
|
||||
seedPath = value;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith("--seed=")) {
|
||||
const value = arg.slice("--seed=".length).trim();
|
||||
if (value.length === 0) {
|
||||
throw new Error("--seed= requires a non-empty path");
|
||||
}
|
||||
seedPath = value;
|
||||
continue;
|
||||
}
|
||||
throw new Error(`Unknown argument: ${arg}`);
|
||||
}
|
||||
|
||||
return {
|
||||
postPr,
|
||||
seedPath,
|
||||
};
|
||||
}
|
||||
|
||||
function toMs(us) {
|
||||
return us / 1000;
|
||||
}
|
||||
|
||||
function round(n, digits = 3) {
|
||||
return Number(n.toFixed(digits));
|
||||
}
|
||||
|
||||
function mb(bytes) {
|
||||
return bytes / (1024 * 1024);
|
||||
}
|
||||
|
||||
function parseNumericEnv({ name, value, predicate, expectation, fallback }) {
|
||||
if (typeof value !== "string") {
|
||||
return null;
|
||||
}
|
||||
const raw = value.trim();
|
||||
if (raw.length === 0) {
|
||||
console.warn(
|
||||
`[desktop-perf] invalid ${name}="${value}" (expected ${expectation}); using ${fallback}`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
const parsed = Number(raw);
|
||||
if (Number.isFinite(parsed) && predicate(parsed)) {
|
||||
return {
|
||||
parsed,
|
||||
raw,
|
||||
};
|
||||
}
|
||||
console.warn(
|
||||
`[desktop-perf] invalid ${name}="${value}" (expected ${expectation}); using ${fallback}`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveNonNegativeNumberEnv({ name, value, fallback }) {
|
||||
const resolved = parseNumericEnv({
|
||||
name,
|
||||
value,
|
||||
predicate: (parsed) => parsed >= 0,
|
||||
expectation: "non-negative number",
|
||||
fallback,
|
||||
});
|
||||
return resolved?.parsed ?? fallback;
|
||||
}
|
||||
|
||||
function resolveNonNegativeIntegerEnv({ name, value, fallback }) {
|
||||
const resolved = parseNumericEnv({
|
||||
name,
|
||||
value,
|
||||
predicate: (parsed) => parsed >= 0,
|
||||
expectation: "non-negative number",
|
||||
fallback,
|
||||
});
|
||||
if (!resolved) {
|
||||
return fallback;
|
||||
}
|
||||
const normalized = Math.trunc(resolved.parsed);
|
||||
if (normalized !== resolved.parsed) {
|
||||
console.warn(
|
||||
`[desktop-perf] non-integer ${name}="${resolved.raw}" truncated to ${normalized} for consistency`,
|
||||
);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function resolvePositiveIntegerEnv({ name, value, fallback }) {
|
||||
const resolved = parseNumericEnv({
|
||||
name,
|
||||
value,
|
||||
predicate: (parsed) => parsed > 0,
|
||||
expectation: "positive number",
|
||||
fallback,
|
||||
});
|
||||
if (!resolved) {
|
||||
return fallback;
|
||||
}
|
||||
const normalized = Math.trunc(resolved.parsed);
|
||||
if (normalized !== resolved.parsed) {
|
||||
console.warn(
|
||||
`[desktop-perf] non-integer ${name}="${resolved.raw}" truncated to ${normalized} for consistency`,
|
||||
);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function summarizeTrace(tracePath) {
|
||||
const payload = JSON.parse(fs.readFileSync(tracePath, "utf8"));
|
||||
const events = payload.traceEvents;
|
||||
|
||||
const durationByName = new Map();
|
||||
const dispatchRows = [];
|
||||
const functionRows = [];
|
||||
const userTiming = new Map();
|
||||
const updateCounters = [];
|
||||
|
||||
for (const event of events) {
|
||||
if (event.name === "UpdateCounters" && event.args?.data) {
|
||||
const heap = event.args.data.jsHeapSizeUsed;
|
||||
if (typeof heap === "number") {
|
||||
updateCounters.push(heap);
|
||||
}
|
||||
}
|
||||
|
||||
if (event.cat === "blink.user_timing" && typeof event.name === "string") {
|
||||
userTiming.set(event.name, (userTiming.get(event.name) ?? 0) + 1);
|
||||
}
|
||||
|
||||
if (event.ph !== "X" || typeof event.dur !== "number" || typeof event.name !== "string") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const byName = durationByName.get(event.name) ?? { count: 0, dur: 0, max: 0 };
|
||||
byName.count += 1;
|
||||
byName.dur += event.dur;
|
||||
byName.max = Math.max(byName.max, event.dur);
|
||||
durationByName.set(event.name, byName);
|
||||
|
||||
if (event.name === "EventDispatch") {
|
||||
const type = event.args?.data?.type ?? "";
|
||||
dispatchRows.push({ type, dur: event.dur });
|
||||
}
|
||||
|
||||
if (event.name === "FunctionCall") {
|
||||
const functionName = event.args?.data?.functionName ?? "(unknown)";
|
||||
functionRows.push({ functionName, dur: event.dur });
|
||||
}
|
||||
}
|
||||
|
||||
const aggregateDispatchType = (type) => {
|
||||
const rows = dispatchRows.filter((row) => row.type === type);
|
||||
if (rows.length === 0) {
|
||||
return {
|
||||
count: 0,
|
||||
totalMs: 0,
|
||||
avgMs: 0,
|
||||
maxMs: 0,
|
||||
};
|
||||
}
|
||||
const totalDur = rows.reduce((sum, row) => sum + row.dur, 0);
|
||||
const maxDur = rows.reduce((max, row) => Math.max(max, row.dur), 0);
|
||||
return {
|
||||
count: rows.length,
|
||||
totalMs: round(toMs(totalDur)),
|
||||
avgMs: round(toMs(totalDur / rows.length)),
|
||||
maxMs: round(toMs(maxDur)),
|
||||
};
|
||||
};
|
||||
|
||||
const aggregateFunction = (name) => {
|
||||
const rows = functionRows.filter((row) => row.functionName === name);
|
||||
if (rows.length === 0) {
|
||||
return {
|
||||
count: 0,
|
||||
totalMs: 0,
|
||||
avgMs: 0,
|
||||
maxMs: 0,
|
||||
};
|
||||
}
|
||||
const totalDur = rows.reduce((sum, row) => sum + row.dur, 0);
|
||||
const maxDur = rows.reduce((max, row) => Math.max(max, row.dur), 0);
|
||||
return {
|
||||
count: rows.length,
|
||||
totalMs: round(toMs(totalDur)),
|
||||
avgMs: round(toMs(totalDur / rows.length)),
|
||||
maxMs: round(toMs(maxDur)),
|
||||
};
|
||||
};
|
||||
|
||||
const topUserTiming = [...userTiming.entries()]
|
||||
.toSorted((a, b) => b[1] - a[1])
|
||||
.slice(0, 10)
|
||||
.map(([name, count]) => ({ name, count }));
|
||||
|
||||
const topDurationEvents = [...durationByName.entries()]
|
||||
.map(([name, value]) => ({
|
||||
name,
|
||||
count: value.count,
|
||||
totalMs: round(toMs(value.dur), 2),
|
||||
avgMs: round(toMs(value.dur / value.count)),
|
||||
maxMs: round(toMs(value.max)),
|
||||
}))
|
||||
.toSorted((a, b) => b.totalMs - a.totalMs)
|
||||
.slice(0, 10);
|
||||
|
||||
const heap = (() => {
|
||||
if (updateCounters.length === 0) return null;
|
||||
const first = updateCounters[0];
|
||||
const last = updateCounters[updateCounters.length - 1];
|
||||
const min = Math.min(...updateCounters);
|
||||
const max = Math.max(...updateCounters);
|
||||
return {
|
||||
firstMb: round(mb(first), 1),
|
||||
lastMb: round(mb(last), 1),
|
||||
minMb: round(mb(min), 1),
|
||||
maxMb: round(mb(max), 1),
|
||||
deltaMb: round(mb(last - first), 1),
|
||||
};
|
||||
})();
|
||||
|
||||
const longDispatchCount = dispatchRows.filter((row) => row.dur >= 50_000).length;
|
||||
|
||||
return {
|
||||
keypress: aggregateDispatchType("keypress"),
|
||||
textInput: aggregateDispatchType("textInput"),
|
||||
input: aggregateDispatchType("input"),
|
||||
keydown: aggregateDispatchType("keydown"),
|
||||
dispatchDiscreteEvent: aggregateFunction("dispatchDiscreteEvent"),
|
||||
performWorkUntilDeadline: aggregateFunction("performWorkUntilDeadline"),
|
||||
longDispatchCount,
|
||||
heap,
|
||||
topUserTiming,
|
||||
topDurationEvents,
|
||||
};
|
||||
}
|
||||
|
||||
const pad = (value, width) => String(value).padEnd(width, " ");
|
||||
|
||||
function createMarkdownSummary({ tracePath, donePayload, summary, thresholds }) {
|
||||
const THREAD_COL_WIDTH = 8;
|
||||
const TITLE_COL_WIDTH = 15;
|
||||
const largeThreadRenderStats = Array.isArray(donePayload.interactions?.largeThreadRenderStats)
|
||||
? donePayload.interactions.largeThreadRenderStats
|
||||
: [];
|
||||
const formatThreadRenderRow = (stat) => {
|
||||
const threadShort =
|
||||
typeof stat.threadId === "string" ? stat.threadId.slice(0, THREAD_COL_WIDTH) : "n/a";
|
||||
const titleShort =
|
||||
typeof stat.threadTitleShort === "string"
|
||||
? stat.threadTitleShort
|
||||
: typeof stat.threadId === "string"
|
||||
? stat.threadId.slice(0, 15)
|
||||
: "n/a";
|
||||
const firstRenderMs =
|
||||
typeof stat.firstRenderMs === "number"
|
||||
? stat.firstRenderMs
|
||||
: typeof stat.renderMs === "number"
|
||||
? stat.renderMs
|
||||
: "n/a";
|
||||
const followUpRenderMs =
|
||||
typeof stat.followUpRenderMs === "number" ? stat.followUpRenderMs : "n/a";
|
||||
const followUpMinMs = typeof stat.followUpMinMs === "number" ? stat.followUpMinMs : "n/a";
|
||||
const followUpMaxMs = typeof stat.followUpMaxMs === "number" ? stat.followUpMaxMs : "n/a";
|
||||
const followUpSampleCount =
|
||||
typeof stat.followUpSampleCount === "number" ? stat.followUpSampleCount : "n/a";
|
||||
const deltaMs = typeof stat.deltaMs === "number" ? stat.deltaMs : "n/a";
|
||||
const deltaPct = typeof stat.deltaPct === "number" ? stat.deltaPct : "n/a";
|
||||
const followUpRange =
|
||||
typeof followUpMinMs === "number" && typeof followUpMaxMs === "number"
|
||||
? `${followUpMinMs}-${followUpMaxMs} (${followUpSampleCount}x)`
|
||||
: "n/a";
|
||||
return `| ${pad(threadShort, THREAD_COL_WIDTH)} | ${pad(titleShort, TITLE_COL_WIDTH)} | ${stat.messageCount} | ${firstRenderMs} | ${followUpRenderMs} | ${followUpRange} | ${deltaMs} | ${deltaPct}% |`;
|
||||
};
|
||||
const seedSource =
|
||||
donePayload.seed?.source === "file"
|
||||
? `file (\`${donePayload.seed?.path ?? "unknown"}\`)`
|
||||
: (donePayload.seed?.source ?? "generated");
|
||||
const lines = [
|
||||
marker,
|
||||
"## Desktop Dev Perf Trace",
|
||||
"",
|
||||
`- Command: \`bun dev:desktop\``,
|
||||
`- Trace: \`${tracePath}\``,
|
||||
`- Started: ${donePayload.startedAt ?? "n/a"}`,
|
||||
`- Completed: ${donePayload.completedAt ?? "n/a"}`,
|
||||
`- Duration: ${donePayload.durationMs ?? "n/a"} ms`,
|
||||
`- Seed source: ${seedSource}`,
|
||||
"",
|
||||
"### Interaction Run",
|
||||
"",
|
||||
`- Thread clicks: ${donePayload.interactions?.threadClicks ?? "n/a"}`,
|
||||
`- Typed chars: ${donePayload.interactions?.typedChars ?? "n/a"}`,
|
||||
`- Benchmark thread ids exercised: ${
|
||||
Array.isArray(donePayload.interactions?.benchmarkThreadIds) &&
|
||||
donePayload.interactions.benchmarkThreadIds.length > 0
|
||||
? donePayload.interactions.benchmarkThreadIds.join(", ")
|
||||
: "none"
|
||||
}`,
|
||||
`- Model selected: ${donePayload.interactions?.selectedModel ?? "n/a"}`,
|
||||
`- Terminal opened by shortcut: ${donePayload.interactions?.terminal?.openedByShortcut ?? "n/a"}`,
|
||||
`- Terminal shortcut modifier: ${donePayload.interactions?.terminal?.modifierUsed ?? "n/a"}`,
|
||||
`- Terminal splits: ${donePayload.interactions?.terminal?.splitCount ?? "n/a"}`,
|
||||
`- Terminal command executed: ${donePayload.interactions?.terminal?.commandFileTouched ?? "n/a"}`,
|
||||
`- Terminal output observed: ${donePayload.interactions?.terminal?.commandEchoObserved ?? "n/a"}`,
|
||||
`- Terminal marker: ${donePayload.interactions?.terminal?.commandMarker ?? "n/a"}`,
|
||||
`- Terminal interactions enabled: ${donePayload.config?.runTerminalInteractions ?? "n/a"}`,
|
||||
`- Optional renderer interactions enabled: ${donePayload.config?.runOptionalRendererInteractions ?? "n/a"}`,
|
||||
`- Benchmark sweep enabled: ${donePayload.config?.runBenchmarkThreadSweep ?? "n/a"}`,
|
||||
`- Benchmark follow-up pass count: ${donePayload.config?.benchmarkFollowUpPassCount ?? "n/a"}`,
|
||||
"",
|
||||
"### Threshold Config",
|
||||
"",
|
||||
`- keypress avg max: ${thresholds.maxKeypressAvgMs}ms`,
|
||||
`- keypress max max: ${thresholds.maxKeypressMaxMs}ms`,
|
||||
`- long EventDispatch spike cap: ${thresholds.maxLongDispatchCount}`,
|
||||
"",
|
||||
"### Benchmark Thread Render",
|
||||
"",
|
||||
"| Thread | Title (15) | Messages | First Nav (ms) | Follow-up Median (ms) | Follow-up Range | Delta (ms) | Delta (%) |",
|
||||
"| --- | --- | ---: | ---: | ---: | --- | ---: | ---: |",
|
||||
...(largeThreadRenderStats.length > 0
|
||||
? largeThreadRenderStats.map((stat) => formatThreadRenderRow(stat))
|
||||
: ["| n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a |"]),
|
||||
"",
|
||||
"### Input Event Metrics",
|
||||
"",
|
||||
"| Event | Count | Avg (ms) | Max (ms) | Total (ms) |",
|
||||
"| --- | ---: | ---: | ---: | ---: |",
|
||||
`| keypress | ${summary.keypress.count} | ${summary.keypress.avgMs} | ${summary.keypress.maxMs} | ${summary.keypress.totalMs} |`,
|
||||
`| textInput | ${summary.textInput.count} | ${summary.textInput.avgMs} | ${summary.textInput.maxMs} | ${summary.textInput.totalMs} |`,
|
||||
`| input | ${summary.input.count} | ${summary.input.avgMs} | ${summary.input.maxMs} | ${summary.input.totalMs} |`,
|
||||
`| keydown | ${summary.keydown.count} | ${summary.keydown.avgMs} | ${summary.keydown.maxMs} | ${summary.keydown.totalMs} |`,
|
||||
"",
|
||||
"### Scheduler/Event Hotspots",
|
||||
"",
|
||||
`- dispatchDiscreteEvent: ${summary.dispatchDiscreteEvent.totalMs}ms total (${summary.dispatchDiscreteEvent.count} calls)`,
|
||||
`- performWorkUntilDeadline: ${summary.performWorkUntilDeadline.totalMs}ms total (${summary.performWorkUntilDeadline.count} calls)`,
|
||||
`- EventDispatch spikes >= 50ms: ${summary.longDispatchCount}`,
|
||||
"",
|
||||
"### Threshold Check",
|
||||
"",
|
||||
`- keypress avg <= ${thresholds.maxKeypressAvgMs}ms: ${
|
||||
summary.keypress.avgMs <= thresholds.maxKeypressAvgMs ? "pass" : "fail"
|
||||
}`,
|
||||
`- keypress max <= ${thresholds.maxKeypressMaxMs}ms: ${
|
||||
summary.keypress.maxMs <= thresholds.maxKeypressMaxMs ? "pass" : "fail"
|
||||
}`,
|
||||
`- long dispatch spikes <= ${thresholds.maxLongDispatchCount}: ${
|
||||
summary.longDispatchCount <= thresholds.maxLongDispatchCount ? "pass" : "fail"
|
||||
}`,
|
||||
"",
|
||||
];
|
||||
|
||||
if (summary.heap) {
|
||||
lines.push("### Heap Counters", "");
|
||||
lines.push(
|
||||
`- first=${summary.heap.firstMb}MB, last=${summary.heap.lastMb}MB, min=${summary.heap.minMb}MB, max=${summary.heap.maxMb}MB, delta=${summary.heap.deltaMb}MB`,
|
||||
"",
|
||||
);
|
||||
}
|
||||
|
||||
lines.push("### Top User Timing Marks", "");
|
||||
for (const entry of summary.topUserTiming) {
|
||||
lines.push(`- ${entry.count}x ${entry.name}`);
|
||||
}
|
||||
lines.push("", "### Top Duration Events", "");
|
||||
for (const entry of summary.topDurationEvents) {
|
||||
lines.push(
|
||||
`- ${entry.name}: total=${entry.totalMs}ms, avg=${entry.avgMs}ms, max=${entry.maxMs}ms, count=${entry.count}`,
|
||||
);
|
||||
}
|
||||
lines.push("");
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
async function waitForDoneFile(donePath, child, timeoutMs) {
|
||||
const startedAt = Date.now();
|
||||
while (Date.now() - startedAt < timeoutMs) {
|
||||
if (fs.existsSync(donePath)) {
|
||||
return JSON.parse(fs.readFileSync(donePath, "utf8"));
|
||||
}
|
||||
if (child.exitCode !== null) {
|
||||
throw new Error(`desktop dev process exited early (code ${child.exitCode})`);
|
||||
}
|
||||
// oxlint-disable-next-line no-await-in-loop
|
||||
await sleep(500);
|
||||
}
|
||||
throw new Error(`Timed out waiting for done marker at ${donePath}`);
|
||||
}
|
||||
|
||||
function tailLogText(logChunks, lineCount = 120) {
|
||||
const lines = logChunks.join("").split(/\r?\n/);
|
||||
return lines.slice(-lineCount).join("\n").trim();
|
||||
}
|
||||
|
||||
function inferDesktopPerfTimeoutHint(logChunks) {
|
||||
const joined = logChunks.join("");
|
||||
const lowered = joined.toLowerCase();
|
||||
|
||||
if (lowered.includes("waiting for bundles") && lowered.includes("outdated:")) {
|
||||
return "Desktop bundles were present but older than desktop source files; dev bundler did not refresh outputs in time.";
|
||||
}
|
||||
if (lowered.includes("waiting for bundles") && lowered.includes("stale:")) {
|
||||
return "Desktop bundles were detected as stale by startup freshness checks.";
|
||||
}
|
||||
if (lowered.includes("error while loading shared libraries")) {
|
||||
return "Electron failed to start due missing Linux shared libraries.";
|
||||
}
|
||||
if (lowered.includes("setuid_sandbox_host.cc") || lowered.includes("chrome-sandbox")) {
|
||||
return "Electron sandbox setup failed on Linux CI (setuid sandbox helper).";
|
||||
}
|
||||
if (lowered.includes("no usable sandbox")) {
|
||||
return "Electron sandbox failed to initialize in CI.";
|
||||
}
|
||||
if (lowered.includes("port is already in use")) {
|
||||
return "Dev server port collision prevented Electron from loading the renderer.";
|
||||
}
|
||||
if (!joined.includes("[desktop-perf]")) {
|
||||
return "Desktop perf automation never started; Electron likely did not boot successfully.";
|
||||
}
|
||||
if (joined.includes("[desktop-perf]") && !joined.includes("[desktop-perf] trace recorded")) {
|
||||
return "Desktop perf automation started but did not complete trace recording.";
|
||||
}
|
||||
|
||||
return "Desktop perf automation timed out before writing the done marker.";
|
||||
}
|
||||
|
||||
async function terminateProcessTree(child) {
|
||||
if (child.exitCode !== null) return;
|
||||
|
||||
if (process.platform === "win32") {
|
||||
try {
|
||||
execFileSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
||||
} catch {
|
||||
child.kill("SIGTERM");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
process.kill(-child.pid, "SIGTERM");
|
||||
} catch {
|
||||
child.kill("SIGTERM");
|
||||
}
|
||||
|
||||
await sleep(1_500);
|
||||
if (child.exitCode === null) {
|
||||
try {
|
||||
process.kill(-child.pid, "SIGKILL");
|
||||
} catch {
|
||||
child.kill("SIGKILL");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function detectPrNumber() {
|
||||
const githubRef = process.env.GITHUB_REF ?? "";
|
||||
const match = githubRef.match(/refs\/pull\/(\d+)\//);
|
||||
if (match?.[1]) {
|
||||
return match[1];
|
||||
}
|
||||
|
||||
return execFileSync("gh", ["pr", "view", "--json", "number", "--jq", ".number"], {
|
||||
cwd: repoRoot,
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
}
|
||||
|
||||
function postSummaryToPr(summaryPath) {
|
||||
const prNumber = detectPrNumber();
|
||||
execFileSync(
|
||||
"gh",
|
||||
["pr", "comment", prNumber, "--body-file", summaryPath, "--edit-last", "--create-if-none"],
|
||||
{
|
||||
cwd: repoRoot,
|
||||
stdio: "inherit",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function prepareDesktopPerfState(stateDir, perfProjects = defaultPerfProjects) {
|
||||
fs.mkdirSync(stateDir, { recursive: true });
|
||||
|
||||
for (const project of perfProjects) {
|
||||
try {
|
||||
fs.mkdirSync(project.cwd, { recursive: true });
|
||||
} catch {
|
||||
// Some seeded paths may point to unavailable locations in CI; registry entries still work.
|
||||
}
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
fs.writeFileSync(
|
||||
path.join(stateDir, "projects.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
version: 1,
|
||||
projects: perfProjects.map((project) => ({
|
||||
id: project.id,
|
||||
cwd: project.cwd,
|
||||
name: project.name,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function resolveSeedPath(seedPathArg) {
|
||||
const candidateArg = seedPathArg ?? process.env.T3CODE_DESKTOP_PERF_SEED_PATH ?? "";
|
||||
if (!candidateArg || candidateArg.trim().length === 0) {
|
||||
const defaultCandidates = ["scripts/perf-seed.json", "apps/desktop/scripts/perf-seed.json"];
|
||||
for (const candidate of defaultCandidates) {
|
||||
const resolved = path.resolve(repoRoot, candidate);
|
||||
if (fs.existsSync(resolved)) {
|
||||
return resolved;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const resolved = path.isAbsolute(candidateArg)
|
||||
? candidateArg
|
||||
: path.resolve(repoRoot, candidateArg);
|
||||
if (!fs.existsSync(resolved)) {
|
||||
throw new Error(`Seed file not found: ${resolved}`);
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
function normalizeProjectPathForRuntime(rawCwd, projectName, projectId, projectIndex) {
|
||||
const attemptedPath = path.resolve(rawCwd);
|
||||
try {
|
||||
fs.mkdirSync(attemptedPath, { recursive: true });
|
||||
return attemptedPath;
|
||||
} catch {
|
||||
const safeName = (projectName || projectId || `project-${projectIndex + 1}`)
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9._-]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 48);
|
||||
const fallbackPath = path.join(
|
||||
os.tmpdir(),
|
||||
"t3code-desktop-perf-seed-projects",
|
||||
`${String(projectIndex + 1).padStart(2, "0")}-${safeName || "project"}`,
|
||||
);
|
||||
fs.mkdirSync(fallbackPath, { recursive: true });
|
||||
return fallbackPath;
|
||||
}
|
||||
}
|
||||
|
||||
function materializeRuntimeSeed(seedPath, artifactsDir) {
|
||||
const raw = JSON.parse(fs.readFileSync(seedPath, "utf8"));
|
||||
if (!raw || typeof raw !== "object" || !Array.isArray(raw.projects)) {
|
||||
return { runtimeSeedPath: seedPath, projects: null };
|
||||
}
|
||||
|
||||
const rewrittenProjects = [];
|
||||
let rewroteAnyProject = false;
|
||||
for (let index = 0; index < raw.projects.length; index += 1) {
|
||||
const project = raw.projects[index];
|
||||
if (!project || typeof project !== "object") {
|
||||
rewrittenProjects.push(project);
|
||||
continue;
|
||||
}
|
||||
|
||||
const id = typeof project.id === "string" ? project.id : "";
|
||||
const name = typeof project.name === "string" ? project.name : "";
|
||||
const cwd = typeof project.cwd === "string" ? project.cwd : "";
|
||||
if (id.length === 0 || name.length === 0 || cwd.length === 0) {
|
||||
rewrittenProjects.push(project);
|
||||
continue;
|
||||
}
|
||||
|
||||
const runtimeCwd = normalizeProjectPathForRuntime(cwd, name, id, index);
|
||||
if (runtimeCwd !== cwd) {
|
||||
rewroteAnyProject = true;
|
||||
}
|
||||
rewrittenProjects.push({
|
||||
...project,
|
||||
cwd: runtimeCwd,
|
||||
});
|
||||
}
|
||||
|
||||
if (!rewroteAnyProject) {
|
||||
const projects = rewrittenProjects
|
||||
.map((project) => {
|
||||
if (!project || typeof project !== "object") return null;
|
||||
const id = typeof project.id === "string" ? project.id : "";
|
||||
const cwd = typeof project.cwd === "string" ? project.cwd : "";
|
||||
const name = typeof project.name === "string" ? project.name : "";
|
||||
if (id.length === 0 || cwd.length === 0 || name.length === 0) return null;
|
||||
return { id, cwd, name };
|
||||
})
|
||||
.filter((project) => project !== null);
|
||||
|
||||
return {
|
||||
runtimeSeedPath: seedPath,
|
||||
projects: projects.length > 0 ? projects : null,
|
||||
};
|
||||
}
|
||||
|
||||
const runtimeSeedPath = path.join(artifactsDir, "perf-seed.runtime.json");
|
||||
fs.writeFileSync(
|
||||
runtimeSeedPath,
|
||||
JSON.stringify(
|
||||
{
|
||||
...raw,
|
||||
projects: rewrittenProjects,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
|
||||
const projects = rewrittenProjects
|
||||
.map((project) => {
|
||||
if (!project || typeof project !== "object") return null;
|
||||
const id = typeof project.id === "string" ? project.id : "";
|
||||
const cwd = typeof project.cwd === "string" ? project.cwd : "";
|
||||
const name = typeof project.name === "string" ? project.name : "";
|
||||
if (id.length === 0 || cwd.length === 0 || name.length === 0) return null;
|
||||
return { id, cwd, name };
|
||||
})
|
||||
.filter((project) => project !== null);
|
||||
|
||||
return {
|
||||
runtimeSeedPath,
|
||||
projects: projects.length > 0 ? projects : null,
|
||||
};
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = parseArgs(process.argv);
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
|
||||
const artifactsDir = path.join(os.tmpdir(), "t3code-perf-artifacts", `desktop-dev-${timestamp}`);
|
||||
fs.mkdirSync(artifactsDir, { recursive: true });
|
||||
|
||||
const tracePath = path.join(artifactsDir, "trace.json");
|
||||
const donePath = path.join(artifactsDir, "done.json");
|
||||
const summaryPath = path.join(artifactsDir, "summary.md");
|
||||
const logPath = path.join(artifactsDir, "run.log");
|
||||
const stateDir = path.join(artifactsDir, "state");
|
||||
const seedPath = resolveSeedPath(args.seedPath);
|
||||
const materializedSeed = seedPath ? materializeRuntimeSeed(seedPath, artifactsDir) : null;
|
||||
const runtimeSeedPath = materializedSeed?.runtimeSeedPath ?? seedPath;
|
||||
const seedProjects = materializedSeed?.projects ?? null;
|
||||
if (seedPath && runtimeSeedPath && runtimeSeedPath !== seedPath) {
|
||||
console.log(
|
||||
`[desktop-perf] rewrote seed project cwd paths for runtime compatibility: ${runtimeSeedPath}`,
|
||||
);
|
||||
}
|
||||
prepareDesktopPerfState(stateDir, seedProjects ?? defaultPerfProjects);
|
||||
|
||||
const maxKeypressAvgMs = resolveNonNegativeNumberEnv({
|
||||
name: "T3CODE_PERF_MAX_KEYPRESS_AVG_MS",
|
||||
value: process.env.T3CODE_PERF_MAX_KEYPRESS_AVG_MS,
|
||||
fallback: 12,
|
||||
});
|
||||
const maxKeypressMaxMs = resolveNonNegativeNumberEnv({
|
||||
name: "T3CODE_PERF_MAX_KEYPRESS_MAX_MS",
|
||||
value: process.env.T3CODE_PERF_MAX_KEYPRESS_MAX_MS,
|
||||
fallback: 24,
|
||||
});
|
||||
const maxLongDispatchCount = resolveNonNegativeIntegerEnv({
|
||||
name: "T3CODE_PERF_MAX_LONG_DISPATCH_COUNT",
|
||||
value: process.env.T3CODE_PERF_MAX_LONG_DISPATCH_COUNT,
|
||||
fallback: 0,
|
||||
});
|
||||
const timeoutMs = resolvePositiveIntegerEnv({
|
||||
name: "T3CODE_PERF_TIMEOUT_MS",
|
||||
value: process.env.T3CODE_PERF_TIMEOUT_MS,
|
||||
fallback: 420000,
|
||||
});
|
||||
console.log(
|
||||
`[desktop-perf] thresholds: keypressAvg<=${maxKeypressAvgMs}ms, keypressMax<=${maxKeypressMaxMs}ms, longDispatch<=${maxLongDispatchCount}, timeoutMs=${timeoutMs}`,
|
||||
);
|
||||
|
||||
const child = spawn("bun", ["dev:desktop"], {
|
||||
cwd: repoRoot,
|
||||
detached: process.platform !== "win32",
|
||||
env: {
|
||||
...process.env,
|
||||
T3CODE_DESKTOP_PERF_AUTOMATION: "1",
|
||||
T3CODE_DESKTOP_PERF_TRACE_OUT: tracePath,
|
||||
T3CODE_DESKTOP_PERF_DONE_OUT: donePath,
|
||||
...(runtimeSeedPath ? { T3CODE_DESKTOP_PERF_SEED_PATH: runtimeSeedPath } : {}),
|
||||
T3CODE_DEV_INSTANCE: `desktop-perf-${timestamp}`,
|
||||
T3CODE_LOG_WS_EVENTS: "0",
|
||||
T3CODE_STATE_DIR: stateDir,
|
||||
},
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
const logs = [];
|
||||
const appendLog = (chunk) => {
|
||||
const text = chunk.toString();
|
||||
logs.push(text);
|
||||
if (logs.length > 1200) {
|
||||
logs.splice(0, logs.length - 1200);
|
||||
}
|
||||
fs.appendFileSync(logPath, text);
|
||||
process.stdout.write(text);
|
||||
};
|
||||
|
||||
child.stdout.on("data", appendLog);
|
||||
child.stderr.on("data", appendLog);
|
||||
|
||||
let donePayload;
|
||||
try {
|
||||
donePayload = await waitForDoneFile(donePath, child, timeoutMs);
|
||||
} catch (error) {
|
||||
const baseMessage = error instanceof Error ? error.message : String(error);
|
||||
const hint = inferDesktopPerfTimeoutHint(logs);
|
||||
const logTail = tailLogText(logs);
|
||||
throw new Error(
|
||||
[
|
||||
baseMessage,
|
||||
`Hint: ${hint}`,
|
||||
`Artifacts dir: ${artifactsDir}`,
|
||||
`Run log: ${logPath}`,
|
||||
logTail.length > 0 ? `Recent log tail:\n${logTail}` : "Recent log tail: <empty>",
|
||||
].join("\n"),
|
||||
{ cause: error },
|
||||
);
|
||||
} finally {
|
||||
await terminateProcessTree(child);
|
||||
}
|
||||
|
||||
if (!donePayload || donePayload.status !== "ok") {
|
||||
throw new Error(
|
||||
`Desktop perf automation failed. ${donePayload?.error ?? "No completion payload written."}`,
|
||||
);
|
||||
}
|
||||
|
||||
const interactionChecks = [];
|
||||
const threadClicks = Number(donePayload.interactions?.threadClicks ?? 0);
|
||||
const typedChars = Number(donePayload.interactions?.typedChars ?? 0);
|
||||
if (threadClicks <= 0) {
|
||||
interactionChecks.push("thread clicks");
|
||||
}
|
||||
if (typedChars <= 0) {
|
||||
interactionChecks.push("typed chars");
|
||||
}
|
||||
if (interactionChecks.length > 0) {
|
||||
throw new Error(
|
||||
`Desktop perf automation completed without required scripted interactions: ${interactionChecks.join(", ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
const summary = summarizeTrace(tracePath);
|
||||
const markdown = createMarkdownSummary({
|
||||
tracePath,
|
||||
donePayload,
|
||||
summary,
|
||||
thresholds: {
|
||||
maxKeypressAvgMs,
|
||||
maxKeypressMaxMs,
|
||||
maxLongDispatchCount,
|
||||
},
|
||||
});
|
||||
fs.writeFileSync(summaryPath, markdown);
|
||||
|
||||
console.log(`\nPerf summary written to ${summaryPath}\n`);
|
||||
console.log(markdown);
|
||||
|
||||
const thresholdFailures = [];
|
||||
if (summary.keypress.avgMs > maxKeypressAvgMs) {
|
||||
thresholdFailures.push(
|
||||
`keypress avg ${summary.keypress.avgMs}ms exceeds ${maxKeypressAvgMs}ms`,
|
||||
);
|
||||
}
|
||||
if (summary.keypress.maxMs > maxKeypressMaxMs) {
|
||||
thresholdFailures.push(
|
||||
`keypress max ${summary.keypress.maxMs}ms exceeds ${maxKeypressMaxMs}ms`,
|
||||
);
|
||||
}
|
||||
if (summary.longDispatchCount > maxLongDispatchCount) {
|
||||
thresholdFailures.push(
|
||||
`long EventDispatch count ${summary.longDispatchCount} exceeds ${maxLongDispatchCount}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (args.postPr) {
|
||||
postSummaryToPr(summaryPath);
|
||||
}
|
||||
|
||||
if (thresholdFailures.length > 0) {
|
||||
throw new Error(`Performance thresholds failed:\n- ${thresholdFailures.join("\n- ")}`);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.error("\nDesktop perf trace test failed:\n" + message);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,153 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import vm from "node:vm";
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
const VERSION = process.argv[2] ?? "12.17.0";
|
||||
const VERSION_TAG = `v${VERSION}`;
|
||||
const VSIX_URL = `https://open-vsx.org/api/vscode-icons-team/vscode-icons/${VERSION}/file/vscode-icons-team.vscode-icons-${VERSION}.vsix`;
|
||||
const LANGUAGES_URL = `https://raw.githubusercontent.com/vscode-icons/vscode-icons/${VERSION_TAG}/src/iconsManifest/languages.ts`;
|
||||
|
||||
const REPO_ROOT = process.cwd();
|
||||
const MANIFEST_PATH = path.join(REPO_ROOT, "apps/web/src/vscode-icons-manifest.json");
|
||||
const ASSOCIATIONS_PATH = path.join(
|
||||
REPO_ROOT,
|
||||
"apps/web/src/vscode-icons-language-associations.json",
|
||||
);
|
||||
|
||||
function normalizeExtension(value) {
|
||||
return value.trim().toLowerCase().replace(/^\./, "");
|
||||
}
|
||||
|
||||
function normalizeFileName(value) {
|
||||
return value.trim().toLowerCase();
|
||||
}
|
||||
|
||||
function putIfAbsent(target, key, value) {
|
||||
if (!(key in target)) {
|
||||
target[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadVsix(tmpDir) {
|
||||
const vsixPath = path.join(tmpDir, `vscode-icons-${VERSION}.vsix`);
|
||||
const response = await fetch(VSIX_URL);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to download VSIX: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
const bytes = Buffer.from(await response.arrayBuffer());
|
||||
await fs.writeFile(vsixPath, bytes);
|
||||
return vsixPath;
|
||||
}
|
||||
|
||||
async function extractManifestFromVsix(vsixPath) {
|
||||
const { stdout } = await execFileAsync("unzip", [
|
||||
"-p",
|
||||
vsixPath,
|
||||
"extension/dist/src/vsicons-icon-theme.json",
|
||||
]);
|
||||
if (!stdout || stdout.trim().length === 0) {
|
||||
throw new Error("Could not extract vsicons-icon-theme.json from VSIX");
|
||||
}
|
||||
return JSON.parse(stdout);
|
||||
}
|
||||
|
||||
async function loadLanguagesCollection() {
|
||||
const response = await fetch(LANGUAGES_URL);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch languages.ts: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
const rawSource = await response.text();
|
||||
const source = rawSource
|
||||
.replace(/^import[^;]+;\s*/gm, "")
|
||||
.replace(/export const languages(?:\s*:\s*[^=]+)?\s*=/, "const languages =")
|
||||
.replace(/\}\s*satisfies\s*Record<[^;]+>;/, "};");
|
||||
|
||||
const context = {};
|
||||
vm.createContext(context);
|
||||
vm.runInContext(`${source}\n;globalThis.__languages = languages;`, context);
|
||||
const languages = context.__languages;
|
||||
if (!languages || typeof languages !== "object") {
|
||||
throw new Error("Failed to parse languages.ts into a collection");
|
||||
}
|
||||
return languages;
|
||||
}
|
||||
|
||||
function buildLanguageAssociations(manifest, languages) {
|
||||
const availableLanguageIds = new Set(Object.keys(manifest.languageIds ?? {}));
|
||||
const extensionToLanguageId = {};
|
||||
const fileNameToLanguageId = {};
|
||||
|
||||
for (const entry of Object.values(languages)) {
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
const idsRaw = entry.ids;
|
||||
const ids = Array.isArray(idsRaw) ? idsRaw : [idsRaw];
|
||||
const knownExtensions = Array.isArray(entry.knownExtensions) ? entry.knownExtensions : [];
|
||||
const knownFilenames = Array.isArray(entry.knownFilenames) ? entry.knownFilenames : [];
|
||||
|
||||
for (const idValue of ids) {
|
||||
if (typeof idValue !== "string") continue;
|
||||
const languageId = idValue.trim();
|
||||
if (languageId.length === 0) continue;
|
||||
if (!availableLanguageIds.has(languageId)) continue;
|
||||
|
||||
for (const extensionValue of knownExtensions) {
|
||||
if (typeof extensionValue !== "string") continue;
|
||||
const extension = normalizeExtension(extensionValue);
|
||||
if (extension.length === 0) continue;
|
||||
putIfAbsent(extensionToLanguageId, extension, languageId);
|
||||
}
|
||||
|
||||
for (const fileNameValue of knownFilenames) {
|
||||
if (typeof fileNameValue !== "string") continue;
|
||||
const fileName = normalizeFileName(fileNameValue);
|
||||
if (fileName.length === 0) continue;
|
||||
putIfAbsent(fileNameToLanguageId, fileName, languageId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
version: VERSION,
|
||||
source: LANGUAGES_URL,
|
||||
generatedAt: new Date().toISOString(),
|
||||
extensionToLanguageId,
|
||||
fileNameToLanguageId,
|
||||
};
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "t3-vscode-icons-sync-"));
|
||||
try {
|
||||
const vsixPath = await downloadVsix(tmpDir);
|
||||
const manifest = await extractManifestFromVsix(vsixPath);
|
||||
const languages = await loadLanguagesCollection();
|
||||
const associations = buildLanguageAssociations(manifest, languages);
|
||||
|
||||
await fs.writeFile(MANIFEST_PATH, `${JSON.stringify(manifest)}\n`, "utf8");
|
||||
await fs.writeFile(ASSOCIATIONS_PATH, `${JSON.stringify(associations)}\n`, "utf8");
|
||||
|
||||
process.stdout.write(
|
||||
[
|
||||
`Synced vscode-icons ${VERSION}`,
|
||||
`manifest: ${MANIFEST_PATH}`,
|
||||
`language associations: ${ASSOCIATIONS_PATH}`,
|
||||
`extension mappings: ${Object.keys(associations.extensionToLanguageId).length}`,
|
||||
`filename mappings: ${Object.keys(associations.fileNameToLanguageId).length}`,
|
||||
].join("\n") + "\n",
|
||||
);
|
||||
} finally {
|
||||
await fs.rm(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
||||
process.exit(1);
|
||||
});
|
||||
+7
-1
@@ -5,13 +5,19 @@
|
||||
"VITE_WS_URL",
|
||||
"VITE_DEV_SERVER_URL",
|
||||
"ELECTRON_RENDERER_PORT",
|
||||
"ELECTRON_DISABLE_SANDBOX",
|
||||
"T3CODE_LOG_WS_EVENTS",
|
||||
"T3CODE_MODE",
|
||||
"T3CODE_PORT",
|
||||
"T3CODE_NO_BROWSER",
|
||||
"T3CODE_STATE_DIR",
|
||||
"T3CODE_AUTH_TOKEN",
|
||||
"T3CODE_DESKTOP_WS_URL"
|
||||
"T3CODE_DESKTOP_WS_URL",
|
||||
"T3CODE_DESKTOP_PERF_AUTOMATION",
|
||||
"T3CODE_DESKTOP_PERF_TRACE_OUT",
|
||||
"T3CODE_DESKTOP_PERF_DONE_OUT",
|
||||
"T3CODE_DESKTOP_PERF_SEED_PATH",
|
||||
"T3CODE_ELECTRON_STARTUP_TIMEOUT_MS"
|
||||
],
|
||||
"tasks": {
|
||||
"build": {
|
||||
|
||||
Reference in new issue
Block a user