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
Julius Marminge 73fa2d66c7 Use stable IDs for approval actions in ChatView
- Derive `activeSessionId` and `activeThreadId` before approval callbacks
- Avoid stale thread/session captures when submitting approval decisions
- Pass `hasMessages` to `MessagesTimeline` instead of the full thread
2026-02-16 00:55:31 -08:00
Julius Marminge 51dcb547ed Refactor ChatView into memoized subcomponents
- Extract header, error, approvals, and timeline into memoized components
- Memoize `ChatMarkdown`, pickers, and handlers to reduce avoidable re-renders
- Reduce running-time ticker frequency from 250ms to 1000ms
2026-02-16 00:55:31 -08:00
Julius Marminge 228862ac56 doc 2026-02-15 23:08:37 -08:00
Julius Marminge bc22a71f10 Rename local chat shortcut and surface terminal close hints
- Replace `chat.newSameGitState` with `chat.newLocal` across contracts, server/web defaults, docs, and tests
- Make `chat.new` preserve branch/worktree state while `chat.newLocal` creates a local thread
- Show terminal close shortcut labels in drawer action tooltips and tab close controls
2026-02-15 23:08:37 -08:00
Julius Marminge c42d6a6a64 Add shortcuts for terminal close and chat with same Git state
- Extend keybinding contracts/defaults with `terminal.close` and `chat.newSameGitState`
- Wire web handlers for `mod+w` to close focused terminal and `mod+shift+n` to open a thread preserving branch/worktree
- Update docs and keybinding tests across server, web, and contracts
2026-02-15 23:08:37 -08:00
Julius Marminge 5242bbbade Fix top-right toast enter and exit transforms
- Add position-specific start transform for top-right toasts
- Apply matching top-right end transform when dismissing without swipe
2026-02-15 20:12:24 -08:00
Julius Marminge 05b47e748f Fix collapsed toast content visibility in filtered stacks
- keep the front-most visible toast readable when thread filtering hides others
- extract visibility rule into `toast.logic.ts`
- add unit tests for collapsed-content visibility behavior
2026-02-15 20:12:24 -08:00
Julius Marminge 3863901085 Auto-dismiss thread toasts after 10s of visible time
- Add `dismissAfterVisibleMs` support to thread toasts
- Pause/resume countdown based on tab visibility and window focus
- Set Git action result toasts to dismiss after 10s when visible
2026-02-15 19:16:49 -08:00
Julius Marminge f864ef189d Ignore non-keydown terminal shortcuts
- guard terminal clear/navigation shortcut handlers to only process `keydown`
- add tests verifying `keyup` events are ignored
2026-02-15 17:06:16 -08:00
Julius Marminge 765f4cd00b Add terminal word and line navigation arrow shortcuts
- handle platform-specific modifier+arrow combos in terminal input
- reuse terminal write path for clear and navigation actions
- add shortcut tests for macOS and non-macOS mappings
2026-02-15 17:06:16 -08:00
39 changed files with 6519 additions and 550 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
+7 -2
View File
@@ -22,7 +22,10 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`](
{ "key": "mod+j", "command": "terminal.toggle" },
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
{ "key": "mod+shift+o", "command": "chat.new" },
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
{ "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
{ "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" },
{ "key": "mod+o", "command": "editor.openFavorite" }
]
```
@@ -46,7 +49,9 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
- `terminal.toggle`: open/close terminal drawer
- `terminal.split`: split terminal (in focused terminal context by default)
- `terminal.new`: create new terminal (in focused terminal context by default)
- `chat.new`: create a new chat thread for the active project
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
- `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
### Key Syntax
+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;
+4 -1
View File
@@ -28,7 +28,10 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
{ key: "mod+shift+o", command: "chat.new" },
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
{ key: "mod+o", command: "editor.openFavorite" },
];
+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", () => {
+4 -1
View File
@@ -1,3 +1,4 @@
import { memo } from "react";
import type { Components } from "react-markdown";
import ReactMarkdown from "react-markdown";
import rehypeHighlight from "rehype-highlight";
@@ -13,7 +14,7 @@ const markdownComponents: Components = {
},
};
export default function ChatMarkdown({ text }: ChatMarkdownProps) {
function ChatMarkdown({ text }: ChatMarkdownProps) {
return (
<div className="chat-markdown text-sm leading-relaxed text-foreground/80">
<ReactMarkdown
@@ -26,3 +27,5 @@ export default function ChatMarkdown({ text }: ChatMarkdownProps) {
</div>
);
}
export default memo(ChatMarkdown);
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}`;
@@ -312,7 +312,10 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
title: resultToast.title,
description: resultToast.description,
timeout: 0,
data: threadToastData,
data: {
...threadToastData,
dismissAfterVisibleMs: 10_000,
},
...(shouldOfferPushCta
? {
actionProps: {
@@ -627,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}`
+24 -8
View File
@@ -7,7 +7,7 @@ import { useTheme } from "../hooks/useTheme";
import { DEFAULT_MODEL } from "../model-logic";
import { derivePendingApprovals } from "../session-logic";
import { useStore } from "../store";
import { isChatNewShortcut } from "../keybindings";
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
@@ -140,7 +140,13 @@ export default function Sidebar() {
}, [state.threads]);
const handleNewThread = useCallback(
(projectId: string) => {
(
projectId: string,
options?: {
branch?: string | null;
worktreePath?: string | null;
},
) => {
dispatch({
type: "ADD_THREAD",
thread: {
@@ -166,8 +172,8 @@ export default function Sidebar() {
events: [],
error: null,
createdAt: new Date().toISOString(),
branch: null,
worktreePath: null,
branch: options?.branch ?? null,
worktreePath: options?.worktreePath ?? null,
},
});
},
@@ -381,14 +387,23 @@ export default function Sidebar() {
useEffect(() => {
const onWindowKeyDown = (event: KeyboardEvent) => {
if (!isChatNewShortcut(event, keybindings)) return;
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
if (isChatNewLocalShortcut(event, keybindings)) {
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
handleNewThread(projectId);
return;
}
if (!isChatNewShortcut(event, keybindings)) return;
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
handleNewThread(projectId);
handleNewThread(projectId, {
branch: activeThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? null,
});
};
window.addEventListener("keydown", onWindowKeyDown);
@@ -490,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"
@@ -1,5 +1,5 @@
import { FitAddon } from "@xterm/addon-fit";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2 } from "lucide-react";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react";
import { type NativeApi } from "@t3tools/contracts";
import { Terminal, type ITheme } from "@xterm/xterm";
import {
@@ -18,7 +18,7 @@ import {
preferredTerminalEditor,
resolvePathLinkTarget,
} from "../terminal-links";
import { isTerminalClearShortcut } from "../keybindings";
import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keybindings";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
@@ -152,24 +152,29 @@ function TerminalViewport({
terminalRef.current = terminal;
fitAddonRef.current = fitAddon;
const sendClearShortcut = async () => {
const sendTerminalInput = async (data: string, fallbackError: string) => {
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
try {
await api.terminal.write({ threadId, terminalId, data: "\u000c" });
await api.terminal.write({ threadId, terminalId, data });
} catch (error) {
writeSystemMessage(
activeTerminal,
error instanceof Error ? error.message : "Failed to clear terminal",
);
writeSystemMessage(activeTerminal, error instanceof Error ? error.message : fallbackError);
}
};
terminal.attachCustomKeyEventHandler((event) => {
const navigationData = terminalNavigationShortcutData(event);
if (navigationData !== null) {
event.preventDefault();
event.stopPropagation();
void sendTerminalInput(navigationData, "Failed to move cursor");
return false;
}
if (!isTerminalClearShortcut(event)) return true;
event.preventDefault();
event.stopPropagation();
void sendClearShortcut();
void sendTerminalInput("\u000c", "Failed to clear terminal");
return false;
});
@@ -363,7 +368,7 @@ function TerminalViewport({
fitAddonRef.current = null;
terminal.dispose();
};
}, [api, cwd, terminalId, threadId]);
}, [api, cwd, terminalId, threadId, autoFocus]);
useEffect(() => {
if (!autoFocus) return;
@@ -418,6 +423,7 @@ interface ThreadTerminalDrawerProps {
onNewTerminal: () => void;
splitShortcutLabel?: string | undefined;
newShortcutLabel?: string | undefined;
closeShortcutLabel?: string | undefined;
onActiveTerminalChange: (terminalId: string) => void;
onCloseTerminal: (terminalId: string) => void;
onHeightChange: (height: number) => void;
@@ -433,15 +439,9 @@ interface TerminalActionButtonProps {
function TerminalActionButton({ label, className, onClick, children }: TerminalActionButtonProps) {
return (
<Popover>
<PopoverTrigger openOnHover
render={
<button
type="button"
className={className}
onClick={onClick}
aria-label={label}
/>
}
<PopoverTrigger
openOnHover
render={<button type="button" className={className} onClick={onClick} aria-label={label} />}
>
{children}
</PopoverTrigger>
@@ -472,6 +472,7 @@ export default function ThreadTerminalDrawer({
onNewTerminal,
splitShortcutLabel,
newShortcutLabel,
closeShortcutLabel,
onActiveTerminalChange,
onCloseTerminal,
onHeightChange,
@@ -587,6 +588,9 @@ export default function ThreadTerminalDrawer({
),
[normalizedTerminalIds],
);
const closeTerminalActionLabel = closeShortcutLabel
? `Close Terminal (${closeShortcutLabel})`
: "Close Terminal";
useEffect(() => {
onHeightChangeRef.current = onHeightChange;
@@ -698,7 +702,9 @@ export default function ThreadTerminalDrawer({
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onSplitTerminal}
label={splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal"}
label={
splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal"
}
>
<SquareSplitHorizontal className="size-3.25" />
</TerminalActionButton>
@@ -714,7 +720,7 @@ export default function ThreadTerminalDrawer({
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
label="Close Terminal"
label={closeTerminalActionLabel}
>
<Trash2 className="size-3.25" />
</TerminalActionButton>
@@ -794,16 +800,14 @@ export default function ThreadTerminalDrawer({
<TerminalActionButton
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"
}
label={newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"}
>
<Plus 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 hover:bg-accent/70"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
label="Close Terminal"
label={closeTerminalActionLabel}
>
<Trash2 className="size-3.25" />
</TerminalActionButton>
@@ -841,6 +845,9 @@ export default function ThreadTerminalDrawer({
>
{terminalGroup.terminalIds.map((terminalId) => {
const isActive = terminalId === resolvedActiveTerminalId;
const closeTerminalLabel = `Close ${
terminalLabelById.get(terminalId) ?? "terminal"
}${isActive && closeShortcutLabel ? ` (${closeShortcutLabel})` : ""}`;
return (
<div
key={terminalId}
@@ -864,18 +871,30 @@ export default function ThreadTerminalDrawer({
</span>
</button>
{normalizedTerminalIds.length > 1 && (
<button
type="button"
className="rounded px-1 text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
onClick={(event) => {
event.stopPropagation();
onCloseTerminal(terminalId);
}}
aria-label={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
title={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
>
×
</button>
<Popover>
<PopoverTrigger
openOnHover
render={
<button
type="button"
className="inline-flex size-3.5 items-center justify-center rounded text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
onClick={() => onCloseTerminal(terminalId)}
aria-label={closeTerminalLabel}
/>
}
>
<XIcon className="size-2.5" />
</PopoverTrigger>
<PopoverPopup
tooltipStyle
side="bottom"
sideOffset={6}
align="center"
className="pointer-events-none select-none"
>
{closeTerminalLabel}
</PopoverPopup>
</Popover>
)}
</div>
);
+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}
@@ -0,0 +1,16 @@
import { assert, describe, it } from "vitest";
import { shouldHideCollapsedToastContent } from "./toast.logic";
describe("shouldHideCollapsedToastContent", () => {
it("keeps a single visible toast readable", () => {
assert.equal(shouldHideCollapsedToastContent(0, 1), false);
});
it("keeps the front-most toast readable in a visible stack", () => {
assert.equal(shouldHideCollapsedToastContent(0, 3), false);
});
it("hides non-front toasts until the stack is expanded", () => {
assert.equal(shouldHideCollapsedToastContent(1, 3), true);
});
});
@@ -0,0 +1,9 @@
export function shouldHideCollapsedToastContent(
visibleToastIndex: number,
visibleToastCount: number,
): boolean {
// Keep the front-most toast readable even if Base UI marks it as "behind"
// due to toasts hidden by thread filtering.
if (visibleToastCount <= 1) return false;
return visibleToastIndex > 0;
}
+190 -84
View File
@@ -1,6 +1,7 @@
"use client";
import { Toast } from "@base-ui/react/toast";
import { useEffect } from "react";
import {
CircleAlertIcon,
CircleCheckIcon,
@@ -12,14 +13,18 @@ import {
import { cn } from "~/lib/utils";
import { buttonVariants } from "~/components/ui/button";
import { useStore } from "~/store";
import { shouldHideCollapsedToastContent } from "./toast.logic";
type ThreadToastData = {
threadId?: string | null;
tooltipStyle?: boolean;
dismissAfterVisibleMs?: number;
};
const toastManager = Toast.createToastManager<ThreadToastData>();
const anchoredToastManager = Toast.createToastManager<ThreadToastData>();
type ToastId = ReturnType<typeof toastManager.add>;
const threadToastVisibleTimeoutRemainingMs = new Map<ToastId, number>();
const TOAST_ICONS = {
error: CircleAlertIcon,
@@ -50,6 +55,84 @@ function shouldRenderForActiveThread(
return toastThreadId === activeThreadId;
}
function ThreadToastVisibleAutoDismiss({
toastId,
dismissAfterVisibleMs,
}: {
toastId: ToastId;
dismissAfterVisibleMs: number | undefined;
}) {
useEffect(() => {
if (!dismissAfterVisibleMs || dismissAfterVisibleMs <= 0) return;
if (typeof window === "undefined" || typeof document === "undefined") return;
let remainingMs = threadToastVisibleTimeoutRemainingMs.get(toastId) ?? dismissAfterVisibleMs;
let startedAtMs: number | null = null;
let timeoutId: number | null = null;
let closed = false;
const clearTimer = () => {
if (timeoutId === null) return;
window.clearTimeout(timeoutId);
timeoutId = null;
};
const closeToast = () => {
if (closed) return;
closed = true;
threadToastVisibleTimeoutRemainingMs.delete(toastId);
toastManager.close(toastId);
};
const pause = () => {
if (startedAtMs === null) return;
remainingMs = Math.max(0, remainingMs - (Date.now() - startedAtMs));
startedAtMs = null;
clearTimer();
threadToastVisibleTimeoutRemainingMs.set(toastId, remainingMs);
};
const start = () => {
if (closed || startedAtMs !== null) return;
if (remainingMs <= 0) {
closeToast();
return;
}
startedAtMs = Date.now();
clearTimer();
timeoutId = window.setTimeout(() => {
remainingMs = 0;
startedAtMs = null;
closeToast();
}, remainingMs);
};
const syncTimer = () => {
const shouldRun = document.visibilityState === "visible" && document.hasFocus();
if (shouldRun) {
start();
return;
}
pause();
};
syncTimer();
document.addEventListener("visibilitychange", syncTimer);
window.addEventListener("focus", syncTimer);
window.addEventListener("blur", syncTimer);
return () => {
document.removeEventListener("visibilitychange", syncTimer);
window.removeEventListener("focus", syncTimer);
window.removeEventListener("blur", syncTimer);
pause();
clearTimer();
};
}, [dismissAfterVisibleMs, toastId]);
return null;
}
function ToastProvider({ children, position = "top-right", ...props }: ToastProviderProps) {
return (
<Toast.Provider toastManager={toastManager} {...props}>
@@ -64,6 +147,18 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
const { toasts } = Toast.useToastManager<ThreadToastData>();
const activeThreadId = state.activeThreadId;
const isTop = position.startsWith("top");
const visibleToasts = toasts.filter((toast) =>
shouldRenderForActiveThread(toast.data, activeThreadId),
);
useEffect(() => {
const activeToastIds = new Set(toasts.map((toast) => toast.id));
for (const toastId of threadToastVisibleTimeoutRemainingMs.keys()) {
if (!activeToastIds.has(toastId)) {
threadToastVisibleTimeoutRemainingMs.delete(toastId);
}
}
}, [toasts]);
return (
<Toast.Portal data-slot="toast-portal">
@@ -81,96 +176,107 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
data-position={position}
data-slot="toast-viewport"
>
{toasts
.filter((toast) => shouldRenderForActiveThread(toast.data, activeThreadId))
.map((toast) => {
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
{visibleToasts.map((toast, visibleIndex) => {
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
const hideCollapsedContent = shouldHideCollapsedToastContent(
visibleIndex,
visibleToasts.length,
);
return (
<Toast.Root
return (
<Toast.Root
className={cn(
"absolute z-[calc(9999-var(--toast-index))] h-(--toast-calc-height) w-full select-none rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 [transition:transform_.5s_cubic-bezier(.22,1,.36,1),opacity_.5s,height_.15s] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
// Base positioning using data-position
"data-[position*=right]:right-0 data-[position*=right]:left-auto",
"data-[position*=left]:right-auto data-[position*=left]:left-0",
"data-[position*=center]:right-0 data-[position*=center]:left-0",
"data-[position*=top]:top-0 data-[position*=top]:bottom-auto data-[position*=top]:origin-top",
"data-[position*=bottom]:top-auto data-[position*=bottom]:bottom-0 data-[position*=bottom]:origin-bottom",
// Gap fill for hover
"after:absolute after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full",
"data-[position*=top]:after:top-full",
"data-[position*=bottom]:after:bottom-full",
// Define some variables
"[--toast-calc-height:var(--toast-frontmost-height,var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
// Define offset-y variable
"data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
"data-[position*=bottom]:[--toast-calc-offset-y:calc(var(--toast-offset-y)*-1+var(--toast-index)*var(--toast-gap)*-1+var(--toast-swipe-movement-y))]",
// Default state transform
"data-[position*=top]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)+(var(--toast-index)*var(--toast-peek))+(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
"data-[position*=bottom]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--toast-peek))-(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
// Limited state
"data-limited:opacity-0",
// Expanded state
"data-expanded:h-(--toast-height)",
"data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]",
// Starting and ending animations
"data-[position*=top]:data-starting-style:transform-[translateY(calc(-100%-var(--toast-inset)))]",
"data-[position*=bottom]:data-starting-style:transform-[translateY(calc(100%+var(--toast-inset)))]",
"data-[position*=top]:data-[position*=right]:data-starting-style:transform-[translateX(calc(100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:opacity-0",
// Ending animations (direction-aware)
"data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(100%+var(--toast-inset)))]",
"data-[position*=top]:data-[position*=right]:data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateX(calc(100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
// Ending animations (expanded)
"data-expanded:data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-expanded:data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
)}
data-position={position}
key={toast.id}
swipeDirection={
position.includes("center")
? [isTop ? "up" : "down"]
: position.includes("left")
? ["left", isTop ? "up" : "down"]
: ["right", isTop ? "up" : "down"]
}
toast={toast}
>
<ThreadToastVisibleAutoDismiss
dismissAfterVisibleMs={toast.data?.dismissAfterVisibleMs}
toastId={toast.id}
/>
<Toast.Content
className={cn(
"absolute z-[calc(9999-var(--toast-index))] h-(--toast-calc-height) w-full select-none rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 [transition:transform_.5s_cubic-bezier(.22,1,.36,1),opacity_.5s,height_.15s] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
// Base positioning using data-position
"data-[position*=right]:right-0 data-[position*=right]:left-auto",
"data-[position*=left]:right-auto data-[position*=left]:left-0",
"data-[position*=center]:right-0 data-[position*=center]:left-0",
"data-[position*=top]:top-0 data-[position*=top]:bottom-auto data-[position*=top]:origin-top",
"data-[position*=bottom]:top-auto data-[position*=bottom]:bottom-0 data-[position*=bottom]:origin-bottom",
// Gap fill for hover
"after:absolute after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full",
"data-[position*=top]:after:top-full",
"data-[position*=bottom]:after:bottom-full",
// Define some variables
"[--toast-calc-height:var(--toast-frontmost-height,var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
// Define offset-y variable
"data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
"data-[position*=bottom]:[--toast-calc-offset-y:calc(var(--toast-offset-y)*-1+var(--toast-index)*var(--toast-gap)*-1+var(--toast-swipe-movement-y))]",
// Default state transform
"data-[position*=top]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)+(var(--toast-index)*var(--toast-peek))+(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
"data-[position*=bottom]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--toast-peek))-(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
// Limited state
"data-limited:opacity-0",
// Expanded state
"data-expanded:h-(--toast-height)",
"data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]",
// Starting and ending animations
"data-[position*=top]:data-starting-style:transform-[translateY(calc(-100%-var(--toast-inset)))]",
"data-[position*=bottom]:data-starting-style:transform-[translateY(calc(100%+var(--toast-inset)))]",
"data-ending-style:opacity-0",
// Ending animations (direction-aware)
"data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(100%+var(--toast-inset)))]",
"data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
// Ending animations (expanded)
"data-expanded:data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-expanded:data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
"pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm transition-opacity duration-250 data-expanded:opacity-100",
hideCollapsedContent &&
"not-data-expanded:pointer-events-none not-data-expanded:opacity-0",
)}
data-position={position}
key={toast.id}
swipeDirection={
position.includes("center")
? [isTop ? "up" : "down"]
: position.includes("left")
? ["left", isTop ? "up" : "down"]
: ["right", isTop ? "up" : "down"]
}
toast={toast}
>
<Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm transition-opacity duration-250 data-behind:not-data-expanded:pointer-events-none data-behind:opacity-0 data-expanded:opacity-100">
<div className="flex gap-2">
{Icon && (
<div
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
data-slot="toast-icon"
>
<Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
</div>
)}
<div className="flex flex-col gap-0.5">
<Toast.Title className="font-medium" data-slot="toast-title" />
<Toast.Description
className="text-muted-foreground"
data-slot="toast-description"
/>
</div>
</div>
{toast.actionProps && (
<Toast.Action
className={buttonVariants({ size: "xs" })}
data-slot="toast-action"
<div className="flex gap-2">
{Icon && (
<div
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
data-slot="toast-icon"
>
{toast.actionProps.children}
</Toast.Action>
<Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
</div>
)}
</Toast.Content>
</Toast.Root>
);
})}
<div className="flex flex-col gap-0.5">
<Toast.Title className="font-medium" data-slot="toast-title" />
<Toast.Description
className="text-muted-foreground"
data-slot="toast-description"
/>
</div>
</div>
{toast.actionProps && (
<Toast.Action className={buttonVariants({ size: "xs" })} data-slot="toast-action">
{toast.actionProps.children}
</Toast.Action>
)}
</Toast.Content>
</Toast.Root>
);
})}
</Toast.Viewport>
</Toast.Portal>
);
+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");
+114 -6
View File
@@ -9,12 +9,15 @@ import {
import {
formatShortcutLabel,
isChatNewShortcut,
isChatNewLocalShortcut,
isOpenFavoriteEditorShortcut,
isTerminalClearShortcut,
isTerminalCloseShortcut,
isTerminalNewShortcut,
isTerminalSplitShortcut,
isTerminalToggleShortcut,
shortcutLabelForCommand,
terminalNavigationShortcutData,
type ShortcutEventLike,
} from "./keybindings";
@@ -82,14 +85,22 @@ const DEFAULT_BINDINGS = compile([
command: "terminal.new",
whenAst: whenIdentifier("terminalFocus"),
},
{
shortcut: modShortcut("w"),
command: "terminal.close",
whenAst: whenIdentifier("terminalFocus"),
},
{ shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" },
{ shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newLocal" },
{ shortcut: modShortcut("o"), command: "editor.openFavorite" },
]);
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",
}),
);
});
@@ -100,8 +111,8 @@ describe("isTerminalToggleShortcut", () => {
});
});
describe("split/new terminal shortcuts", () => {
it("requires terminalFocus for default split/new bindings", () => {
describe("split/new/close terminal shortcuts", () => {
it("requires terminalFocus for default split/new/close bindings", () => {
assert.isFalse(
isTerminalSplitShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
@@ -114,6 +125,12 @@ describe("split/new terminal shortcuts", () => {
context: { terminalFocus: false },
}),
);
assert.isFalse(
isTerminalCloseShortcut(event({ key: "w", ctrlKey: true }), DEFAULT_BINDINGS, {
platform: "Linux",
context: { terminalFocus: false },
}),
);
});
it("matches split/new when terminalFocus is true", () => {
@@ -129,6 +146,12 @@ describe("split/new terminal shortcuts", () => {
context: { terminalFocus: true },
}),
);
assert.isTrue(
isTerminalCloseShortcut(event({ key: "w", ctrlKey: true }), DEFAULT_BINDINGS, {
platform: "Linux",
context: { terminalFocus: true },
}),
);
});
it("supports when expressions", () => {
@@ -198,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", () => {
@@ -224,6 +250,19 @@ describe("chat/editor shortcuts", () => {
);
});
it("matches chat.newLocal shortcut", () => {
assert.isTrue(
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",
}),
);
});
it("matches editor.openFavorite shortcut", () => {
assert.isTrue(
isOpenFavoriteEditorShortcut(event({ key: "o", metaKey: true }), DEFAULT_BINDINGS, {
@@ -302,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", () => {
@@ -324,6 +369,69 @@ describe("isTerminalClearShortcut", () => {
it("matches Cmd+K on macOS", () => {
assert.isTrue(isTerminalClearShortcut(event({ key: "k", metaKey: true }), "MacIntel"));
});
it("ignores non-keydown events", () => {
assert.isFalse(
isTerminalClearShortcut(event({ type: "keyup", key: "l", ctrlKey: true }), "Linux"),
);
});
});
describe("terminalNavigationShortcutData", () => {
it("maps Option+Arrow on macOS to word movement", () => {
assert.strictEqual(
terminalNavigationShortcutData(event({ key: "ArrowLeft", altKey: true }), "MacIntel"),
"\u001bb",
);
assert.strictEqual(
terminalNavigationShortcutData(event({ key: "ArrowRight", altKey: true }), "MacIntel"),
"\u001bf",
);
});
it("maps Cmd+Arrow on macOS to line movement", () => {
assert.strictEqual(
terminalNavigationShortcutData(event({ key: "ArrowLeft", metaKey: true }), "MacIntel"),
"\u0001",
);
assert.strictEqual(
terminalNavigationShortcutData(event({ key: "ArrowRight", metaKey: true }), "MacIntel"),
"\u0005",
);
});
it("maps Ctrl+Arrow on non-macOS to word movement", () => {
assert.strictEqual(
terminalNavigationShortcutData(event({ key: "ArrowLeft", ctrlKey: true }), "Win32"),
"\u001bb",
);
assert.strictEqual(
terminalNavigationShortcutData(event({ key: "ArrowRight", ctrlKey: true }), "Linux"),
"\u001bf",
);
});
it("rejects unsupported combinations", () => {
assert.isNull(
terminalNavigationShortcutData(
event({ key: "ArrowLeft", shiftKey: true, altKey: true }),
"MacIntel",
),
);
assert.isNull(
terminalNavigationShortcutData(event({ key: "ArrowLeft", metaKey: true }), "Linux"),
);
assert.isNull(terminalNavigationShortcutData(event({ key: "a", altKey: true }), "MacIntel"));
});
it("ignores non-keydown events", () => {
assert.isNull(
terminalNavigationShortcutData(
event({ type: "keyup", key: "ArrowLeft", altKey: true }),
"MacIntel",
),
);
});
});
describe("plus key parsing", () => {
+65
View File
@@ -7,6 +7,7 @@ import {
import { isMacPlatform } from "./lib/utils";
export interface ShortcutEventLike {
type?: string;
key: string;
metaKey: boolean;
ctrlKey: boolean;
@@ -25,6 +26,11 @@ interface ShortcutMatchOptions {
context?: Partial<ShortcutMatchContext>;
}
const TERMINAL_WORD_BACKWARD = "\u001bb";
const TERMINAL_WORD_FORWARD = "\u001bf";
const TERMINAL_LINE_START = "\u0001";
const TERMINAL_LINE_END = "\u0005";
function normalizeEventKey(key: string): string {
const normalized = key.toLowerCase();
if (normalized === "esc") return "escape";
@@ -184,6 +190,14 @@ export function isTerminalNewShortcut(
return matchesCommandShortcut(event, keybindings, "terminal.new", options);
}
export function isTerminalCloseShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
options?: ShortcutMatchOptions,
): boolean {
return matchesCommandShortcut(event, keybindings, "terminal.close", options);
}
export function isChatNewShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
@@ -192,6 +206,14 @@ export function isChatNewShortcut(
return matchesCommandShortcut(event, keybindings, "chat.new", options);
}
export function isChatNewLocalShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
options?: ShortcutMatchOptions,
): boolean {
return matchesCommandShortcut(event, keybindings, "chat.newLocal", options);
}
export function isOpenFavoriteEditorShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
@@ -204,6 +226,10 @@ export function isTerminalClearShortcut(
event: ShortcutEventLike,
platform = navigator.platform,
): boolean {
if (event.type !== undefined && event.type !== "keydown") {
return false;
}
const key = event.key.toLowerCase();
if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
@@ -219,3 +245,42 @@ export function isTerminalClearShortcut(
!event.shiftKey
);
}
export function terminalNavigationShortcutData(
event: ShortcutEventLike,
platform = navigator.platform,
): string | null {
if (event.type !== undefined && event.type !== "keydown") {
return null;
}
if (event.shiftKey) return null;
const key = normalizeEventKey(event.key);
if (key !== "arrowleft" && key !== "arrowright") {
return null;
}
const moveWord = key === "arrowleft" ? TERMINAL_WORD_BACKWARD : TERMINAL_WORD_FORWARD;
const moveLine = key === "arrowleft" ? TERMINAL_LINE_START : TERMINAL_LINE_END;
if (isMacPlatform(platform)) {
if (event.altKey && !event.metaKey && !event.ctrlKey) {
return moveWord;
}
if (event.metaKey && !event.altKey && !event.ctrlKey) {
return moveLine;
}
return null;
}
if (event.ctrlKey && !event.metaKey && !event.altKey) {
return moveWord;
}
if (event.altKey && !event.metaKey && !event.ctrlKey) {
return moveWord;
}
return null;
}
+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"
},
@@ -14,6 +14,18 @@ describe("keybindings contracts", () => {
command: "terminal.toggle",
});
assert.strictEqual(parsed.command, "terminal.toggle");
const parsedClose = keybindingRuleSchema.parse({
key: "mod+w",
command: "terminal.close",
});
assert.strictEqual(parsedClose.command, "terminal.close");
const parsedLocal = keybindingRuleSchema.parse({
key: "mod+shift+n",
command: "chat.newLocal",
});
assert.strictEqual(parsedLocal.command, "chat.newLocal");
});
it("rejects invalid command values", () => {
+19 -13
View File
@@ -4,7 +4,9 @@ export const keybindingCommandSchema = z.enum([
"terminal.toggle",
"terminal.split",
"terminal.new",
"terminal.close",
"chat.new",
"chat.newLocal",
"editor.openFavorite",
]);
@@ -19,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 }
@@ -57,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": {