Compare commits

...
Author SHA1 Message Date
Cursor Agent a13ed5078c Fix path helper shadowing Node's path module in dev-electron script
The helper function `f` declared a parameter named `path` which shadowed
the intended use of Node's `path.join()`. Since strings don't have a
`.join` method, this caused a runtime TypeError before Electron could start.

Fix: import `node:path` and rename the parameter to `p`.
2026-02-17 01:59:09 +00:00
Julius Marminge 88d600370b maybe? 2026-02-16 17:56:57 -08:00
cursor[bot] 1478184dec fix: update CI preload artifact name to .cjs and add freshness grace period for dev startup
- Update CI verification step to check preload.cjs instead of preload.js,
  matching the tsdown CJS output format.
- Add 10s grace period to bundle freshness check in dev-electron.mjs to
  avoid race condition when parallel processes write bundles before the
  script records its start time.

Applied via @cursor push command
2026-02-17 01:40:20 +00:00
Julius Marminge 6a8c803d0e lint fix 2026-02-16 17:38:02 -08:00
Cursor Agent 354a8c30c5 fix: update CI preload artifact name to .cjs and add freshness grace period for dev startup
- Update CI verification step to check preload.cjs instead of preload.js,
  matching the tsdown CJS output format.
- Add 10s grace period to bundle freshness check in dev-electron.mjs to
  avoid race condition when parallel processes write bundles before the
  script records its start time.
2026-02-17 01:31:38 +00:00
Julius Marminge ae4ca8b3c4 maybe fix errors? 2026-02-16 17:28:19 -08:00
Julius Marmingeandcodex 36812206b6 Avoid cleaning desktop bundle in watch mode for perf CI
Co-authored-by: codex <[email protected]>
2026-02-16 11:21:41 -08:00
Julius Marmingeandcodex f9ba69adad Fix dev-electron bundle readiness race in CI
Co-authored-by: codex <[email protected]>
2026-02-16 11:09:10 -08:00
Julius Marminge c2388e0b74 Enable Linux Electron sandbox override for desktop perf runs
- Set `ELECTRON_DISABLE_SANDBOX=1` in CI desktop perf trace jobs
- Auto-enable the same override in Linux `dev-electron` runs when unset
- Add sandbox-failure log hint in perf trace diagnostics
- Include `ELECTRON_DISABLE_SANDBOX` in Turbo passthrough env
2026-02-16 10:54:10 -08:00
Julius Marminge c807fa684a Replace wait-on with native bundle readiness polling
- remove `wait-on` usage in `dev-electron.mjs`
- add `fs.existsSync` polling for desktop/server bundle files with timeout error details
- keep startup flow the same while reducing external dependency
2026-02-16 10:42:03 -08:00
Julius Marminge 30f8a395a9 Harden Electron startup waits in dev and CI
- add configurable `T3CODE_ELECTRON_STARTUP_TIMEOUT_MS` to desktop startup and CI perf jobs
- replace simple TCP wait with explicit renderer host probes and clearer timeout errors
- include Electron startup timeout env in Turborepo global env passthrough
2026-02-16 10:34:44 -08:00
Julius Marminge d45fe79148 Raise desktop perf timeout and long-dispatch threshold in CI
- Set `T3CODE_PERF_TIMEOUT_MS` default to 420000 in perf trace script
- Export `T3CODE_PERF_MAX_LONG_DISPATCH_COUNT=5` across CI desktop perf jobs
2026-02-16 10:18:09 -08:00
Julius Marminge 23a6e29933 Harden desktop perf CI with deps, artifacts, and timeout hints
- Install required Linux desktop runtime packages before perf trace runs
- Increase perf trace timeout in CI and always upload `/tmp/t3code-perf-artifacts`
- Add timeout failure hints and recent log-tail output to `desktop-perf-trace` errors
2026-02-16 10:04:21 -08:00
Julius Marminge a2b1f8ecd7 Pad perf trace summary columns for stable markdown tables
- define thread/title column widths as constants
- pad thread IDs and titles so large-thread render rows align consistently
2026-02-16 09:46:31 -08:00
Julius Marminge a4941ec9f2 Expand desktop perf trace with terminal and render delta metrics
- Add terminal shortcut/split/command interactions to desktop perf automation
- Benchmark all seeded threads from file seeds and include short title previews
- Report first vs follow-up thread render timings with min/max range and deltas
2026-02-16 09:43:51 -08:00
Julius Marminge ed2ef9634f Add desktop perf seed data and update perf trace workflow
- add `apps/desktop/scripts/perf-seed.json` for seeded desktop perf automation runs
- update desktop/web perf automation and trace scripts to use the new seeded flow
- refresh workspace task/dependency config (`turbo.json`, `apps/web/package.json`, `bun.lock`) to support the perf tooling changes
2026-02-16 09:13:14 -08:00
Julius Marminge 257b52db10 Track large-thread render timings in desktop perf trace
- Seed each perf project with a large synthetic thread for stress coverage
- Measure thread-switch render latency/message counts via ChatView data attributes
- Include a Large Thread Render table in `desktop-perf-trace` markdown output
2026-02-16 08:51:50 -08:00
Julius Marminge af40c4aa5a Handle fork PR desktop perf runs and harden trace shutdown
- Run desktop perf tests on forked pull requests without posting PR summaries
- Restrict PR summary posting to same-repo pull requests
- Add timeout-wrapped trace stop logic and guarded cleanup to avoid hangs
2026-02-16 08:41:15 -08:00
Julius Marminge 7fb2051e67 Extract desktop perf automation into dedicated module
- Move seeding, scripted UI interactions, and trace recording into `desktopPerfAutomation.ts`
- Keep `main.ts` lightweight with lazy module loading and explicit load-failure reporting
2026-02-16 08:31:28 -08:00
Julius Marminge 0cd5642de2 Add desktop perf trace automation and CI reporting
- add automated Electron renderer perf tracing with seeded state and scripted UI interactions
- add `test:desktop-perf` and `test:desktop-perf:post` scripts to generate, validate, and summarize traces
- run desktop perf trace in CI and post/update PR perf summaries on pull requests
2026-02-16 08:10:03 -08:00
31 changed files with 5771 additions and 293 deletions

No files matched your search

+63 -2
View File
@@ -6,6 +6,10 @@ on:
branches:
- main
permissions:
contents: read
pull-requests: write
jobs:
quality:
name: Lint, Typecheck, Test, Build
@@ -46,5 +50,62 @@ 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_LONG_DISPATCH_COUNT: "5"
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_LONG_DISPATCH_COUNT: "5"
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_LONG_DISPATCH_COUNT: "5"
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
+4 -3
View File
@@ -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"
+146 -12
View File
@@ -1,24 +1,153 @@
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 waitForDesktopBundles(timeoutMs) {
const FRESHNESS_GRACE_MS = 10_000;
const startedAt = Date.now();
const bundleFiles = [
{ path: f("dist-electron/main.mjs"), requireFresh: true },
{ path: f("dist-electron/preload.cjs"), requireFresh: true },
{ path: f("../server/dist/index.mjs"), requireFresh: false },
];
return new Promise((resolve, reject) => {
const tick = () => {
const missing = [];
const stale = [];
for (const bundleFile of bundleFiles) {
if (!fs.existsSync(bundleFile.path)) {
missing.push(bundleFile.path);
continue;
}
if (!bundleFile.requireFresh) {
continue;
}
try {
const stat = fs.statSync(bundleFile.path);
if (stat.mtimeMs < startedAt - FRESHNESS_GRACE_MS) {
stale.push(bundleFile.path);
}
} catch {
missing.push(bundleFile.path);
}
}
if (missing.length === 0 && stale.length === 0) {
resolve();
return;
}
if (Date.now() - startedAt >= timeoutMs) {
const parts = [];
if (missing.length > 0) {
parts.push(`missing: ${missing.join(", ")}`);
}
if (stale.length > 0) {
parts.push(`stale: ${stale.join(", ")}`);
}
reject(
new Error(
`[dev-electron] timed out after ${timeoutMs}ms waiting for bundles (${parts.join("; ")})`,
),
);
return;
}
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 +158,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
+3 -5
View File
@@ -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
+37 -4
View File
@@ -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,
@@ -229,7 +257,9 @@ function createWindow(): BrowserWindow {
if (isDevelopment) {
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
window.webContents.openDevTools({ mode: "detach" });
if (!PERF_AUTOMATION_ENABLED) {
window.webContents.openDevTools({ mode: "detach" });
}
} else {
if (!fs.existsSync(WEB_ENTRY)) {
throw new Error(`Web bundle missing at ${WEB_ENTRY}`);
@@ -255,6 +285,9 @@ async function bootstrap(): Promise<void> {
registerIpcHandlers();
startBackend();
mainWindow = createWindow();
if (mainWindow && PERF_AUTOMATION_ENABLED) {
void runPerfAutomationIfEnabled(mainWindow);
}
}
app.on("before-quit", () => {
+8 -9
View File
@@ -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",
},
]);
+1 -1
View File
@@ -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",
+2 -4
View File
@@ -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(
+2 -5
View File
@@ -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;
+3
View File
@@ -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;
+2 -1
View File
@@ -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;
+20 -21
View File
@@ -69,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,
@@ -197,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;
@@ -452,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)) {
-1
View File
@@ -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",
+1
View File
@@ -14,6 +14,7 @@
"@base-ui/react": "^1.2.0",
"@t3tools/contracts": "workspace:*",
"@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",
+1 -4
View File
@@ -1,9 +1,6 @@
import { describe, expect, it } from "vitest";
import {
AUTO_SCROLL_BOTTOM_THRESHOLD_PX,
isScrollContainerNearBottom,
} from "./chat-scroll";
import { AUTO_SCROLL_BOTTOM_THRESHOLD_PX, isScrollContainerNearBottom } from "./chat-scroll";
describe("isScrollContainerNearBottom", () => {
it("returns true when already at bottom", () => {
+275 -180
View File
@@ -14,7 +14,6 @@ import {
type ClipboardEvent,
type DragEvent,
type FormEvent,
Fragment,
type KeyboardEvent,
memo,
type RefObject,
@@ -26,6 +25,7 @@ import {
useState,
} from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { type VirtualItem, useVirtualizer } from "@tanstack/react-virtual";
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
import { serverConfigQueryOptions } from "~/lib/serverReactQuery";
@@ -159,7 +159,6 @@ export default function ChatView() {
const [nowTick, setNowTick] = useState(() => Date.now());
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const messagesScrollRef = useRef<HTMLDivElement>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);
const shouldAutoScrollRef = useRef(true);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
@@ -1012,12 +1011,16 @@ export default function ChatView() {
{/* Messages */}
<div
ref={messagesScrollRef}
data-perf-messages-scroll
data-perf-active-thread-id={activeThread.id}
data-perf-message-count={activeThread.messages.length}
className="min-h-0 flex-1 overflow-y-auto px-5 py-4"
onScroll={onMessagesScroll}
>
<MessagesTimeline
hasMessages={activeThread.messages.length > 0}
isWorking={isWorking}
scrollContainerRef={messagesScrollRef}
timelineEntries={timelineEntries}
completionDividerBeforeEntryId={completionDividerBeforeEntryId}
completionSummary={completionSummary}
@@ -1026,7 +1029,6 @@ export default function ChatView() {
expandedWorkGroups={expandedWorkGroups}
onToggleWorkGroup={onToggleWorkGroup}
onImageExpand={onExpandTimelineImage}
messagesEndRef={messagesEndRef}
/>
</div>
@@ -1080,6 +1082,7 @@ export default function ChatView() {
)}
<textarea
ref={textareaRef}
data-perf-composer-input
className="w-full resize-none bg-transparent text-[14px] leading-relaxed text-foreground placeholder:text-muted-foreground/35 focus:outline-none"
rows={2}
value={prompt}
@@ -1116,6 +1119,7 @@ export default function ChatView() {
className="text-muted-foreground/70 hover:text-foreground/80"
size="sm"
type="button"
data-perf-runtime-toggle
disabled={isSwitchingRuntimeMode}
onClick={() =>
void handleRuntimeModeChange(
@@ -1314,6 +1318,7 @@ const ChatHeader = memo(function ChatHeader({
<Button
size="xs"
variant="ghost"
data-perf-diff-toggle
className={cn(
"text-muted-foreground/70 hover:text-foreground/80",
diffOpen && "bg-accent text-accent-foreground",
@@ -1416,6 +1421,7 @@ const PendingApprovalsPanel = memo(function PendingApprovalsPanel({
interface MessagesTimelineProps {
hasMessages: boolean;
isWorking: boolean;
scrollContainerRef: RefObject<HTMLDivElement | null>;
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
completionDividerBeforeEntryId: string | null;
completionSummary: string | null;
@@ -1424,12 +1430,34 @@ interface MessagesTimelineProps {
expandedWorkGroups: Record<string, boolean>;
onToggleWorkGroup: (groupId: string) => void;
onImageExpand: (image: ExpandedImagePreview) => void;
messagesEndRef: RefObject<HTMLDivElement | null>;
}
type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
type TimelineMessage = Extract<TimelineEntry, { kind: "message" }>["message"];
type TimelineRow =
| {
kind: "work";
id: string;
groupedEntries: {
id: string;
tone: "thinking" | "tool" | "info" | "error";
label: string;
detail?: string | null;
}[];
}
| {
kind: "message";
id: string;
message: TimelineMessage;
showCompletionDivider: boolean;
}
| { kind: "working"; id: string };
const MessagesTimeline = memo(function MessagesTimeline({
hasMessages,
isWorking,
scrollContainerRef,
timelineEntries,
completionDividerBeforeEntryId,
completionSummary,
@@ -1438,192 +1466,259 @@ const MessagesTimeline = memo(function MessagesTimeline({
expandedWorkGroups,
onToggleWorkGroup,
onImageExpand,
messagesEndRef,
}: MessagesTimelineProps) {
const rows = useMemo<TimelineRow[]>(() => {
const nextRows: TimelineRow[] = [];
for (let index = 0; index < timelineEntries.length; index += 1) {
const timelineEntry = timelineEntries[index];
if (!timelineEntry) {
continue;
}
if (timelineEntry.kind === "work") {
const groupedEntries = [timelineEntry.entry];
let cursor = index + 1;
while (cursor < timelineEntries.length) {
const nextEntry = timelineEntries[cursor];
if (!nextEntry || nextEntry.kind !== "work") break;
groupedEntries.push(nextEntry.entry);
cursor += 1;
}
nextRows.push({
kind: "work",
id: timelineEntry.id,
groupedEntries,
});
index = cursor - 1;
continue;
}
nextRows.push({
kind: "message",
id: timelineEntry.id,
message: timelineEntry.message,
showCompletionDivider:
timelineEntry.message.role === "assistant" &&
completionDividerBeforeEntryId === timelineEntry.id,
});
}
if (isWorking) {
nextRows.push({ kind: "working", id: "working-indicator-row" });
}
return nextRows;
}, [timelineEntries, completionDividerBeforeEntryId, isWorking]);
const rowVirtualizer = useVirtualizer({
count: rows.length,
getScrollElement: () => scrollContainerRef.current,
estimateSize: (index: number) => {
const row = rows[index];
if (!row) return 96;
if (row.kind === "work") return 112;
if (row.kind === "working") return 40;
return row.message.role === "assistant" ? 180 : 150;
},
measureElement: (element: HTMLElement) => element.getBoundingClientRect().height,
overscan: 8,
});
const virtualRows = rowVirtualizer.getVirtualItems();
if (!hasMessages && !isWorking) {
return (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-muted-foreground/30">Send a message to start the conversation.</p>
<p className="text-sm text-muted-foreground/30">
Send a message to start the conversation.
</p>
</div>
);
}
return (
<div className="mx-auto max-w-3xl space-y-4">
{timelineEntries.map((timelineEntry, index) => {
if (timelineEntry.kind === "work" && timelineEntries[index - 1]?.kind === "work") {
return null;
}
const showCompletionDivider =
timelineEntry.kind === "message" &&
timelineEntry.message.role === "assistant" &&
completionDividerBeforeEntryId === timelineEntry.id;
if (timelineEntry.kind === "work") {
const groupedEntries = [timelineEntry.entry];
let cursor = index + 1;
while (cursor < timelineEntries.length) {
const nextEntry = timelineEntries[cursor];
if (!nextEntry || nextEntry.kind !== "work") break;
groupedEntries.push(nextEntry.entry);
cursor += 1;
}
const groupId = timelineEntry.id;
const isExpanded = expandedWorkGroups[groupId] ?? false;
const hasOverflow = groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleEntries =
hasOverflow && !isExpanded
? groupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES)
: groupedEntries;
const hiddenCount = groupedEntries.length - visibleEntries.length;
const onlyToolEntries = groupedEntries.every((entry) => entry.tone === "tool");
const groupLabel = onlyToolEntries
? groupedEntries.length === 1
? "Tool call"
: `Tool calls (${groupedEntries.length})`
: groupedEntries.length === 1
? "Work event"
: `Work log (${groupedEntries.length})`;
return (
<Fragment key={timelineEntry.id}>
<div className="rounded-lg border border-border/80 bg-card/45 px-3 py-2">
<div className="mb-1.5 flex items-center justify-between gap-3">
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
{groupLabel}
</p>
{hasOverflow && (
<button
type="button"
className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/55 transition-colors duration-150 hover:text-muted-foreground/80"
onClick={() => onToggleWorkGroup(groupId)}
>
{isExpanded ? "Show less" : `Show ${hiddenCount} more`}
</button>
)}
</div>
<div className="space-y-1">
{visibleEntries.map((workEntry) => (
<div key={`work-row:${workEntry.id}`} className="flex items-start gap-2 py-0.5">
<span className="mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
<p
className={`py-[2px] text-[11px] leading-relaxed ${workToneClass(workEntry.tone)}`}
>
{workEntry.detail ? (
<>
{workEntry.label}
<span
className="ml-1.5 inline-block max-w-[70ch] truncate align-bottom font-mono text-[11px] opacity-60"
title={workEntry.detail}
>
{workEntry.detail}
</span>
</>
) : (
workEntry.label
)}
</p>
</div>
))}
</div>
</div>
</Fragment>
);
}
if (timelineEntry.message.role === "user") {
const userImages = timelineEntry.message.attachments ?? [];
return (
<Fragment key={timelineEntry.id}>
<div className="flex justify-end">
<div className="max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
{userImages.length > 0 && (
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
{userImages.map((image) => (
<div
key={image.id}
className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
>
{image.previewUrl ? (
<img
src={image.previewUrl}
alt={image.name}
className="h-full max-h-[220px] w-full cursor-zoom-in object-cover"
onClick={() =>
onImageExpand({ src: image.previewUrl!, name: image.name })
}
/>
) : (
<div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
{image.name}
</div>
)}
</div>
))}
</div>
)}
{timelineEntry.message.text && (
<pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
{timelineEntry.message.text}
</pre>
)}
<p className="mt-1.5 text-right text-[10px] text-muted-foreground/30">
{formatTimestamp(timelineEntry.message.createdAt)}
</p>
</div>
</div>
</Fragment>
);
}
<div
className="relative mx-auto max-w-3xl"
style={{ height: `${rowVirtualizer.getTotalSize()}px` }}
>
{virtualRows.map((virtualRow: VirtualItem) => {
const row = rows[virtualRow.index];
if (!row) return null;
return (
<Fragment key={timelineEntry.id}>
{showCompletionDivider && (
<div className="my-3 flex items-center gap-3">
<span className="h-px flex-1 bg-border" />
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
{completionSummary ? `Response • ${completionSummary}` : "Response"}
</span>
<span className="h-px flex-1 bg-border" />
</div>
)}
<div className="px-1 py-0.5">
<ChatMarkdown
text={
timelineEntry.message.text ||
(timelineEntry.message.streaming ? "" : "(empty response)")
}
/>
<p className="mt-1.5 text-[10px] text-muted-foreground/30">
{formatMessageMeta(
timelineEntry.message.createdAt,
timelineEntry.message.streaming
? formatElapsed(timelineEntry.message.createdAt, nowIso)
: formatElapsed(
timelineEntry.message.createdAt,
assistantCompletionByItemId.get(timelineEntry.message.id),
),
)}
</p>
<div
key={row.id}
data-index={virtualRow.index}
ref={rowVirtualizer.measureElement}
className="absolute left-0 top-0 w-full"
style={{ transform: `translateY(${virtualRow.start}px)` }}
>
<div className="pb-4">
{row.kind === "work" &&
(() => {
const groupId = row.id;
const groupedEntries = row.groupedEntries;
const isExpanded = expandedWorkGroups[groupId] ?? false;
const hasOverflow = groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleEntries =
hasOverflow && !isExpanded
? groupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES)
: groupedEntries;
const hiddenCount = groupedEntries.length - visibleEntries.length;
const onlyToolEntries = groupedEntries.every((entry) => entry.tone === "tool");
const groupLabel = onlyToolEntries
? groupedEntries.length === 1
? "Tool call"
: `Tool calls (${groupedEntries.length})`
: groupedEntries.length === 1
? "Work event"
: `Work log (${groupedEntries.length})`;
return (
<div className="rounded-lg border border-border/80 bg-card/45 px-3 py-2">
<div className="mb-1.5 flex items-center justify-between gap-3">
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
{groupLabel}
</p>
{hasOverflow && (
<button
type="button"
className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/55 transition-colors duration-150 hover:text-muted-foreground/80"
onClick={() => onToggleWorkGroup(groupId)}
>
{isExpanded ? "Show less" : `Show ${hiddenCount} more`}
</button>
)}
</div>
<div className="space-y-1">
{visibleEntries.map((workEntry) => (
<div
key={`work-row:${workEntry.id}`}
className="flex items-start gap-2 py-0.5"
>
<span className="mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
<p
className={`py-[2px] text-[11px] leading-relaxed ${workToneClass(workEntry.tone)}`}
>
{workEntry.detail ? (
<>
{workEntry.label}
<span
className="ml-1.5 inline-block max-w-[70ch] truncate align-bottom font-mono text-[11px] opacity-60"
title={workEntry.detail}
>
{workEntry.detail}
</span>
</>
) : (
workEntry.label
)}
</p>
</div>
))}
</div>
</div>
);
})()}
{row.kind === "message" &&
row.message.role === "user" &&
(() => {
const userImages = row.message.attachments ?? [];
return (
<div className="flex justify-end">
<div className="max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
{userImages.length > 0 && (
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
{userImages.map(
(image: NonNullable<TimelineMessage["attachments"]>[number]) => (
<div
key={image.id}
className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
>
{image.previewUrl ? (
<img
src={image.previewUrl}
alt={image.name}
className="h-full max-h-[220px] w-full cursor-zoom-in object-cover"
onClick={() =>
onImageExpand({ src: image.previewUrl!, name: image.name })
}
/>
) : (
<div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
{image.name}
</div>
)}
</div>
),
)}
</div>
)}
{row.message.text && (
<pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
{row.message.text}
</pre>
)}
<p className="mt-1.5 text-right text-[10px] text-muted-foreground/30">
{formatTimestamp(row.message.createdAt)}
</p>
</div>
</div>
);
})()}
{row.kind === "message" &&
row.message.role === "assistant" &&
(() => {
const messageText =
row.message.text || (row.message.streaming ? "" : "(empty response)");
return (
<>
{row.showCompletionDivider && (
<div className="my-3 flex items-center gap-3">
<span className="h-px flex-1 bg-border" />
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
{completionSummary ? `Response • ${completionSummary}` : "Response"}
</span>
<span className="h-px flex-1 bg-border" />
</div>
)}
<div className="px-1 py-0.5">
<ChatMarkdown text={messageText} />
<p className="mt-1.5 text-[10px] text-muted-foreground/30">
{formatMessageMeta(
row.message.createdAt,
row.message.streaming
? formatElapsed(row.message.createdAt, nowIso)
: formatElapsed(
row.message.createdAt,
assistantCompletionByItemId.get(row.message.id),
),
)}
</p>
</div>
</>
);
})()}
{row.kind === "working" && (
<div className="flex items-center gap-2 py-0.5 pl-1.5">
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
<div className="flex items-center pt-1">
<span className="inline-flex items-center gap-[3px]">
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
</span>
</div>
</div>
)}
</div>
</Fragment>
</div>
);
})}
{isWorking && (
<div className="flex items-center gap-2 py-0.5 pl-1.5">
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
<div className="flex items-center pt-1">
<span className="inline-flex items-center gap-[3px]">
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
</span>
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
);
});
@@ -1638,12 +1733,12 @@ const ModelPicker = memo(function ModelPicker(props: {
value={props.model}
onValueChange={(value) => (value ? props.onModelChange(value) : undefined)}
>
<SelectTrigger size="sm" variant="ghost">
<SelectTrigger size="sm" variant="ghost" data-perf-model-trigger>
<SelectValue />
</SelectTrigger>
<SelectPopup alignItemWithTrigger={false}>
{MODEL_OPTIONS.map(({ slug, name }) => (
<SelectItem key={slug} value={slug}>
<SelectItem key={slug} value={slug} data-perf-model-option={slug}>
{name}
</SelectItem>
))}
@@ -1661,12 +1756,12 @@ const ReasoningEffortPicker = memo(function ReasoningEffortPicker(props: {
value={props.effort}
onValueChange={(value) => (value ? props.onEffortChange(value) : undefined)}
>
<SelectTrigger variant="ghost" size="sm">
<SelectTrigger variant="ghost" size="sm" data-perf-reasoning-trigger>
<SelectValue />
</SelectTrigger>
<SelectPopup alignItemWithTrigger={false}>
{REASONING_OPTIONS.map((effort) => (
<SelectItem key={effort} value={effort}>
<SelectItem key={effort} value={effort} data-perf-reasoning-option={effort}>
{effort}
{effort === DEFAULT_REASONING ? " (default)" : ""}
</SelectItem>
@@ -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}`;
@@ -630,7 +630,8 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
: gitStatusForActions.aheadCount === 0 &&
gitStatusForActions.behindCount === 0
? "Up to date"
: gitStatusForActions.aheadCount > 0 && gitStatusForActions.behindCount > 0
: gitStatusForActions.aheadCount > 0 &&
gitStatusForActions.behindCount > 0
? `Diverged (+${gitStatusForActions.aheadCount} / -${gitStatusForActions.behindCount})`
: gitStatusForActions.aheadCount > 0
? `Ahead by ${gitStatusForActions.aheadCount}`
+1
View File
@@ -505,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"
@@ -368,7 +368,7 @@ function TerminalViewport({
fitAddonRef.current = null;
terminal.dispose();
};
}, [api, cwd, terminalId, threadId]);
}, [api, cwd, terminalId, threadId, autoFocus]);
useEffect(() => {
if (!autoFocus) return;
+4 -1
View File
@@ -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}
/>
);
+1
View File
@@ -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
View File
@@ -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");
+27 -20
View File
@@ -98,7 +98,9 @@ const DEFAULT_BINDINGS = compile([
describe("isTerminalToggleShortcut", () => {
it("matches Cmd+J on macOS", () => {
assert.isTrue(
isTerminalToggleShortcut(event({ metaKey: true }), DEFAULT_BINDINGS, { platform: "MacIntel" }),
isTerminalToggleShortcut(event({ metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
}),
);
});
@@ -219,7 +221,10 @@ describe("shortcutLabelForCommand", () => {
whenAst: whenNot(whenIdentifier("terminalFocus")),
},
]);
assert.strictEqual(shortcutLabelForCommand(bindings, "terminal.split", "Linux"), "Ctrl+Shift+\\");
assert.strictEqual(
shortcutLabelForCommand(bindings, "terminal.split", "Linux"),
"Ctrl+Shift+\\",
);
});
it("returns labels for non-terminal commands", () => {
@@ -247,22 +252,14 @@ describe("chat/editor shortcuts", () => {
it("matches chat.newLocal shortcut", () => {
assert.isTrue(
isChatNewLocalShortcut(
event({ key: "n", metaKey: true, shiftKey: true }),
DEFAULT_BINDINGS,
{
platform: "MacIntel",
},
),
isChatNewLocalShortcut(event({ key: "n", metaKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
}),
);
assert.isTrue(
isChatNewLocalShortcut(
event({ key: "n", ctrlKey: true, shiftKey: true }),
DEFAULT_BINDINGS,
{
platform: "Linux",
},
),
isChatNewLocalShortcut(event({ key: "n", ctrlKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
platform: "Linux",
}),
);
});
@@ -344,11 +341,17 @@ describe("cross-command precedence", () => {
describe("formatShortcutLabel", () => {
it("formats labels for macOS", () => {
assert.strictEqual(formatShortcutLabel(modShortcut("d", { shiftKey: true }), "MacIntel"), "⇧⌘D");
assert.strictEqual(
formatShortcutLabel(modShortcut("d", { shiftKey: true }), "MacIntel"),
"⇧⌘D",
);
});
it("formats labels for non-macOS", () => {
assert.strictEqual(formatShortcutLabel(modShortcut("d", { shiftKey: true }), "Linux"), "Ctrl+Shift+D");
assert.strictEqual(
formatShortcutLabel(modShortcut("d", { shiftKey: true }), "Linux"),
"Ctrl+Shift+D",
);
});
it("formats labels for plus key", () => {
@@ -368,7 +371,9 @@ describe("isTerminalClearShortcut", () => {
});
it("ignores non-keydown events", () => {
assert.isFalse(isTerminalClearShortcut(event({ type: "keyup", key: "l", ctrlKey: true }), "Linux"));
assert.isFalse(
isTerminalClearShortcut(event({ type: "keyup", key: "l", ctrlKey: true }), "Linux"),
);
});
});
@@ -413,7 +418,9 @@ describe("terminalNavigationShortcutData", () => {
"MacIntel",
),
);
assert.isNull(terminalNavigationShortcutData(event({ key: "ArrowLeft", metaKey: true }), "Linux"));
assert.isNull(
terminalNavigationShortcutData(event({ key: "ArrowLeft", metaKey: true }), "Linux"),
);
assert.isNull(terminalNavigationShortcutData(event({ key: "a", altKey: true }), "MacIntel"));
});
+6 -1
View File
@@ -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",
@@ -54,6 +54,7 @@
"@base-ui/react": "^1.2.0",
"@t3tools/contracts": "workspace:*",
"@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",
@@ -429,6 +430,10 @@
"@tanstack/react-query": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/query-core": "5.90.20" }, "peerDependencies": { "react": "^18 || ^19" } }, "sha512-0Lu6y5t+tvlTJMTO7oh5NSpJfpg/5D41LlThfepTixPYkJ0sE2Jj0m0f6yYqujBwIXlId87e234+MxG3D3g7kg=="],
"@tanstack/react-virtual": ["@tanstack/[email protected]", "", { "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/virtual-core": ["@tanstack/[email protected]", "", {}, "sha512-Mx86Hqu1k39icq2Zusq+Ey2J6dDWTjDvEv43PJtRCoEYTLyfaPnxIQ6iy7YAOK0NV/qOEmZQ/uCufrppZxTgcg=="],
"@tybys/wasm-util": ["@tybys/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg=="],
"@types/babel__core": ["@types/[email protected]", "", { "dependencies": { "@babel/parser": "^7.20.7", "@babel/types": "^7.20.7", "@types/babel__generator": "*", "@types/babel__template": "*", "@types/babel__traverse": "*" } }, "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA=="],
+2
View File
@@ -18,6 +18,8 @@
"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"
},
+17 -13
View File
@@ -21,14 +21,16 @@ export const keybindingRuleSchema = z.object({
export const keybindingsConfigSchema = z.array(keybindingRuleSchema).max(256);
export const keybindingShortcutSchema = z.object({
key: z.string().trim().min(1).max(32),
metaKey: z.boolean(),
ctrlKey: z.boolean(),
shiftKey: z.boolean(),
altKey: z.boolean(),
modKey: z.boolean(),
}).strict();
export const keybindingShortcutSchema = z
.object({
key: z.string().trim().min(1).max(32),
metaKey: z.boolean(),
ctrlKey: z.boolean(),
shiftKey: z.boolean(),
altKey: z.boolean(),
modKey: z.boolean(),
})
.strict();
export type KeybindingWhenNode =
| { type: "identifier"; name: string }
@@ -59,11 +61,13 @@ export const keybindingWhenNodeSchema: z.ZodType<KeybindingWhenNode> = z.lazy(()
]),
);
export const resolvedKeybindingRuleSchema = z.object({
command: keybindingCommandSchema,
shortcut: keybindingShortcutSchema,
whenAst: keybindingWhenNodeSchema.optional(),
}).strict();
export const resolvedKeybindingRuleSchema = z
.object({
command: keybindingCommandSchema,
shortcut: keybindingShortcutSchema,
whenAst: keybindingWhenNodeSchema.optional(),
})
.strict();
export const resolvedKeybindingsConfigSchema = z.array(resolvedKeybindingRuleSchema).max(256);
+626
View File
@@ -0,0 +1,626 @@
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 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"}`,
`- 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"}`,
"",
"### 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("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 extractProjectsFromSeed(seedPath) {
const raw = JSON.parse(fs.readFileSync(seedPath, "utf8"));
if (!raw || typeof raw !== "object" || !Array.isArray(raw.projects)) {
return null;
}
const projects = raw.projects
.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);
if (projects.length === 0) {
return null;
}
return projects;
}
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 seedProjects = seedPath ? extractProjectsFromSeed(seedPath) : null;
prepareDesktopPerfState(stateDir, seedProjects ?? defaultPerfProjects);
const maxKeypressAvgMs = Number(process.env.T3CODE_PERF_MAX_KEYPRESS_AVG_MS ?? "12");
const maxKeypressMaxMs = Number(process.env.T3CODE_PERF_MAX_KEYPRESS_MAX_MS ?? "24");
const maxLongDispatchCount = Number(process.env.T3CODE_PERF_MAX_LONG_DISPATCH_COUNT ?? "0");
const timeoutMs = Number(process.env.T3CODE_PERF_TIMEOUT_MS ?? "420000");
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,
...(seedPath ? { T3CODE_DESKTOP_PERF_SEED_PATH: seedPath } : {}),
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 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);
});
+7 -1
View File
@@ -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": {