Compare commits

...
Author SHA1 Message Date
Cursor Agent e42d1b3d4e Fix reload race: use main-process webContents.reload() instead of renderer window.location.reload()
The renderer-side window.location.reload() inside executeJavaScript schedules a
navigation task asynchronously — the IIFE completes and executeJavaScript resolves
before the reload actually starts. This causes waitForDidFinishLoad to see
isLoadingMainFrame() as false and resolve immediately, allowing the automation to
proceed before the page has reloaded with the seeded state.

Move the reload back to the main process via window.webContents.reload(), which
synchronously puts the frame into a loading state from the main process perspective.
2026-02-17 23:44:24 +00:00
Cursor AgentandJulius Marminge 4df79f1c40 Include fallback values in perf env warnings
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 09:04:21 +00:00
Cursor AgentandJulius Marminge d5f676ec4b Normalize numeric perf env parsing semantics
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 09:00:47 +00:00
Cursor Agent 27983016ae Revert "Deduplicate desktop perf CI env configuration"
This reverts commit d5cba5a7c7.
2026-02-17 08:56:46 +00:00
Cursor AgentandJulius Marminge d5cba5a7c7 Deduplicate desktop perf CI env configuration
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:56:07 +00:00
Cursor AgentandJulius Marminge 4922d999d8 Set explicit keypress perf thresholds in CI
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:52:29 +00:00
Cursor AgentandJulius Marminge 3eb3e7559f Expose resolved perf thresholds in trace output
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:49:02 +00:00
Cursor AgentandJulius Marminge d1eb805075 Harden desktop perf env threshold parsing
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:45:38 +00:00
Cursor AgentandJulius Marminge b796a763ec Expand perf toggle alias consistency coverage
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:41:36 +00:00
Cursor AgentandJulius Marminge a85be01a4e Document perf toggle and benchmark pass resolution semantics
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:36:24 +00:00
Cursor AgentandJulius Marminge e425db60d8 Show benchmark thread ids in perf PR summary
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:32:35 +00:00
Cursor AgentandJulius Marminge 763eec90d5 Include terminal toggle status in perf PR summary
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:29:02 +00:00
Cursor AgentandJulius Marminge 8ada322b22 Broaden benchmark pass parser edge-case coverage
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:25:32 +00:00
Cursor AgentandJulius Marminge 554042da67 Add consistency tests for perf toggle CI fallback
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:20:49 +00:00
Cursor AgentandJulius Marminge 948944448f Include perf interaction config in PR summary output
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:16:53 +00:00
Cursor AgentandJulius Marminge 0805e1d512 Add optional renderer fallback coverage and CI env docs
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:13:18 +00:00
Cursor AgentandJulius Marminge 30b36e4b21 Log perf interaction toggles in automation artifacts
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:09:29 +00:00
Cursor AgentandJulius Marminge 7c45a9ca5a Expand benchmark pass parser boundary tests
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:05:48 +00:00
Cursor AgentandJulius Marminge a936683bec Unify perf toggle fallback logic across config helpers
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 08:02:10 +00:00
Cursor AgentandJulius Marminge b32fbe0e83 Expand benchmark sweep toggle tests and CI docs
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:58:07 +00:00
Cursor AgentandJulius Marminge d69f055597 Add CI toggle to skip benchmark thread sweep
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:53:34 +00:00
Cursor AgentandJulius Marminge b3460f699a Skip optional scroll load and shorten CI typing input
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:49:22 +00:00
Cursor AgentandJulius Marminge 0afaeeb904 Cap benchmark follow-up pass override for perf safety
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:46:03 +00:00
Cursor AgentandJulius Marminge 073c115e50 Disable optional renderer perf interactions in CI
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:42:43 +00:00
Cursor AgentandJulius Marminge 76b7326772 Extract benchmark follow-up pass parsing into perf config
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:37:31 +00:00
Cursor AgentandJulius Marminge a48fec1d81 Make CI perf benchmark pass count explicitly configurable
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:34:02 +00:00
Cursor AgentandJulius Marminge 290a0a112c Disable benchmark follow-up passes during CI perf runs
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:30:21 +00:00
Cursor AgentandJulius Marminge 6eb2a91000 Minimize desktop perf interaction workload further
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:26:42 +00:00
Cursor AgentandJulius Marminge 80c899e50f Reduce desktop perf scripted interaction intensity
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:23:15 +00:00
Cursor AgentandJulius Marminge c41bea9759 Document perf toggle aliases and unknown CI fallback
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:20:33 +00:00
Cursor AgentandJulius Marminge 258992ad7a Add CI false-alias and blank-toggle perf tests
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:17:15 +00:00
Cursor AgentandJulius Marminge 1cb08a2cb2 Support yes/no env aliases in perf toggle parser
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:14:00 +00:00
Cursor AgentandJulius Marminge c0f8077010 Expand CI fallback coverage in perf toggle tests
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:10:38 +00:00
Cursor AgentandJulius Marminge 57124d21e8 Harden perf toggle fallback for CI truthy values
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:07:07 +00:00
Cursor AgentandJulius Marminge 3c4eb3f158 Document terminal perf toggle default behavior
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 07:02:23 +00:00
Cursor AgentandJulius Marminge ce28d5b09d Expand terminal perf toggle parser test coverage
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 06:58:43 +00:00
Cursor AgentandJulius Marminge bbd3f71f11 Document CI terminal perf toggle rationale
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 06:53:52 +00:00
Cursor AgentandJulius Marminge 20febcc58e Add tested parser for terminal perf interaction toggle
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 06:48:52 +00:00
Cursor AgentandJulius Marminge e51724767a Default terminal perf scripting off in CI when env unset
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 06:43:56 +00:00
Cursor AgentandJulius Marminge bb66fd7cc2 Require explicit opt-in for terminal perf scripting
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 06:21:36 +00:00
Cursor AgentandJulius Marminge 715c0354a0 Preserve terminal perf interactions by default outside CI
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 06:17:44 +00:00
Cursor AgentandJulius Marminge 85d6bada6c Disable terminal perf scripting in CI and restore strict dispatch ceiling
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 06:14:44 +00:00
Cursor AgentandJulius Marminge 5b619b18d7 Simplify perf seed reload helper return contract
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 06:09:33 +00:00
Cursor AgentandJulius Marminge 7640c1b64d Keep perf seed retry logic while trimming verbose diagnostics
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 06:05:24 +00:00
Cursor AgentandJulius Marminge 3e589406dd Scope perf bootstrap skip to explicit automation sessions
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 06:00:56 +00:00
Cursor AgentandJulius Marminge c989631657 Remove temporary branch-specific CI push trigger
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:54:18 +00:00
Cursor AgentandJulius Marminge 2344506597 Remove temporary perf state debug instrumentation
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:53:55 +00:00
Cursor AgentandJulius Marminge 9c956c0320 Relax CI long-dispatch perf ceiling for desktop traces
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:48:26 +00:00
Cursor AgentandJulius Marminge 5579c0a542 Trim perf interaction intensity to reduce CI dispatch spikes
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:45:04 +00:00
Cursor AgentandJulius Marminge 003cbd9abc Reduce desktop perf scripted workload for CI stability
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:41:47 +00:00
Cursor AgentandJulius Marminge 8bd17f8425 Require core renderer interactions in perf gate
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:36:43 +00:00
Cursor AgentandJulius Marminge 2179e02eed Continue perf terminal automation when split fails
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:33:15 +00:00
Cursor AgentandJulius Marminge 3822afe509 Retry perf seed when post-reload threads are missing
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:30:08 +00:00
Cursor AgentandJulius Marminge 4b442009d2 Skip desktop project bootstrap during perf state replay
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:26:30 +00:00
Cursor AgentandJulius Marminge b891cb7754 Instrument persisted state hydration for perf CI debugging
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:23:05 +00:00
Cursor AgentandJulius Marminge d1fdf5bef8 Seed renderer state atomically before reload
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:18:03 +00:00
Cursor AgentandJulius Marminge ca001dac0f Add detailed diagnostics for missing perf interaction UI
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:13:13 +00:00
Cursor AgentandJulius Marminge cec360e020 Retry desktop project bootstrap when list is transiently empty
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:08:46 +00:00
Cursor AgentandJulius Marminge 5cda771f72 Make perf scripted interactions best-effort in CI
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 05:00:59 +00:00
Cursor AgentandJulius Marminge 7a493bdeff Harden perf automation against missing sidebar selectors
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 04:57:45 +00:00
Cursor AgentandJulius Marminge f18ee27ebd Rewrite perf seed project paths for CI runtime
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 04:52:18 +00:00
Cursor AgentandJulius Marminge 96aac700d7 Run CI workflow on desktop perf fix branch
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 04:47:54 +00:00
Cursor AgentandJulius Marminge 2c91b7d2a1 Accept prebuilt desktop bundles in dev startup
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 04:47:28 +00:00
Cursor AgentandJulius Marminge b8a24811c4 Fix desktop CI bundle readiness checks
Co-authored-by: Julius Marminge <[email protected]>
2026-02-17 04:43:36 +00:00
Julius Marminge ce27526da9 whoops 2026-02-16 17:58:31 -08:00
8 changed files with 1134 additions and 136 deletions

No files matched your search

+22
View File
@@ -79,7 +79,17 @@ jobs:
env:
ELECTRON_DISABLE_SANDBOX: "1"
T3CODE_PERF_TIMEOUT_MS: "420000"
T3CODE_PERF_MAX_KEYPRESS_AVG_MS: "12"
T3CODE_PERF_MAX_KEYPRESS_MAX_MS: "24"
T3CODE_PERF_MAX_LONG_DISPATCH_COUNT: "5"
# Terminal PTY scripting is flaky in CI VMs; renderer perf checks remain enforced.
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "0"
# Keep only core renderer interactions in CI perf runs for lower variance.
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: "0"
# Skip benchmark sweep loops in CI to reduce EventDispatch variance.
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "0"
# Keep benchmark follow-up passes disabled in CI by default.
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "0"
T3CODE_ELECTRON_STARTUP_TIMEOUT_MS: "180000"
run: xvfb-run -a bun run test:desktop-perf
@@ -88,7 +98,13 @@ jobs:
env:
ELECTRON_DISABLE_SANDBOX: "1"
T3CODE_PERF_TIMEOUT_MS: "420000"
T3CODE_PERF_MAX_KEYPRESS_AVG_MS: "12"
T3CODE_PERF_MAX_KEYPRESS_MAX_MS: "24"
T3CODE_PERF_MAX_LONG_DISPATCH_COUNT: "5"
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "0"
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: "0"
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "0"
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "0"
T3CODE_ELECTRON_STARTUP_TIMEOUT_MS: "180000"
run: xvfb-run -a bun run test:desktop-perf
@@ -98,7 +114,13 @@ jobs:
GH_TOKEN: ${{ github.token }}
ELECTRON_DISABLE_SANDBOX: "1"
T3CODE_PERF_TIMEOUT_MS: "420000"
T3CODE_PERF_MAX_KEYPRESS_AVG_MS: "12"
T3CODE_PERF_MAX_KEYPRESS_MAX_MS: "24"
T3CODE_PERF_MAX_LONG_DISPATCH_COUNT: "5"
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "0"
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: "0"
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "0"
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "0"
T3CODE_ELECTRON_STARTUP_TIMEOUT_MS: "180000"
run: xvfb-run -a bun run test:desktop-perf:post
+64 -32
View File
@@ -1,6 +1,7 @@
import { spawn } from "node:child_process";
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 STARTUP_TIMEOUT_MS = Number(process.env.T3CODE_ELECTRON_STARTUP_TIMEOUT_MS ?? 120_000);
@@ -25,61 +26,92 @@ async function canConnect(host, probePort, timeoutMs = 1_000) {
});
}
const f = (path) => path.join(import.meta.dirname, "..", path);
const f = (p) => path.join(import.meta.dirname, "..", p);
function inspectBundleFile(bundleFile) {
let stat = null;
try {
stat = fs.statSync(bundleFile.path);
} catch {
return {
...bundleFile,
status: "missing",
mtimeMs: null,
reason: "not found",
};
}
return {
...bundleFile,
status: "ready",
mtimeMs: stat.mtimeMs,
reason: "ok",
};
}
function describeBundleStates(states) {
return states
.map((state) => {
const mtime =
typeof state.mtimeMs === "number" ? new Date(state.mtimeMs).toISOString() : "n/a";
return `${state.label}=${state.status} (mtime=${mtime}; reason=${state.reason})`;
})
.join("; ");
}
function waitForDesktopBundles(timeoutMs) {
const 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 },
{
path: f("dist-electron/main.mjs"),
label: "desktop/main.mjs",
},
{
path: f("dist-electron/preload.cjs"),
label: "desktop/preload.cjs",
},
{
path: f("../server/dist/index.mjs"),
label: "server/index.mjs",
},
];
let lastProgressLogAt = 0;
return new Promise((resolve, reject) => {
const tick = () => {
const missing = [];
const stale = [];
const states = bundleFiles.map(inspectBundleFile);
const missing = states.filter((state) => state.status === "missing");
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) {
if (missing.length === 0) {
resolve();
return;
}
if (Date.now() - startedAt >= timeoutMs) {
const elapsedMs = Date.now() - startedAt;
if (elapsedMs >= timeoutMs) {
const parts = [];
if (missing.length > 0) {
parts.push(`missing: ${missing.join(", ")}`);
}
if (stale.length > 0) {
parts.push(`stale: ${stale.join(", ")}`);
parts.push(`missing: ${missing.map((state) => state.label).join(", ")}`);
}
reject(
new Error(
`[dev-electron] timed out after ${timeoutMs}ms waiting for bundles (${parts.join("; ")})`,
`[dev-electron] timed out after ${timeoutMs}ms waiting for bundles (${parts.join("; ")})\n[dev-electron] bundle state: ${describeBundleStates(states)}`,
),
);
return;
}
if (Date.now() - lastProgressLogAt >= 5_000) {
lastProgressLogAt = Date.now();
const waitParts = [];
if (missing.length > 0) {
waitParts.push(`missing=${missing.map((state) => state.label).join(",")}`);
}
console.log(
`[dev-electron] still waiting for bundles after ${elapsedMs}ms (${waitParts.join("; ")})`,
);
}
setTimeout(tick, 250);
};
+296 -86
View File
@@ -4,11 +4,34 @@ import os from "node:os";
import path from "node:path";
import { BrowserWindow, contentTracing, type WebContents } from "electron";
import {
resolveBenchmarkFollowUpPassCount,
shouldRunBenchmarkThreadSweep,
shouldRunOptionalRendererPerfInteractions,
shouldRunTerminalPerfInteractions,
} from "./perfConfig";
const PERF_AUTOMATION_ENABLED = process.env.T3CODE_DESKTOP_PERF_AUTOMATION === "1";
const PERF_TRACE_OUT_PATH = process.env.T3CODE_DESKTOP_PERF_TRACE_OUT?.trim() ?? "";
const PERF_DONE_OUT_PATH = process.env.T3CODE_DESKTOP_PERF_DONE_OUT?.trim() ?? "";
const PERF_SEED_PATH = process.env.T3CODE_DESKTOP_PERF_SEED_PATH?.trim() ?? "";
const RUN_TERMINAL_INTERACTIONS = shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: process.env.T3CODE_DESKTOP_PERF_RUN_TERMINAL,
CI: process.env.CI,
});
const RUN_OPTIONAL_RENDERER_INTERACTIONS = shouldRunOptionalRendererPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: process.env.T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER,
CI: process.env.CI,
});
const BENCHMARK_FOLLOW_UP_PASS_COUNT = resolveBenchmarkFollowUpPassCount({
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES:
process.env.T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES,
CI: process.env.CI,
});
const RUN_BENCHMARK_THREAD_SWEEP = shouldRunBenchmarkThreadSweep({
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: process.env.T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP,
CI: process.env.CI,
});
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
@@ -251,7 +274,7 @@ function resolvePerfSeed(): ResolvedPerfSeed {
source: "file",
resolvedPath,
state: parsed,
benchmarkThreads: pickBenchmarkThreads(stats, true),
benchmarkThreads: pickBenchmarkThreads(stats, false).slice(0, 1),
};
}
@@ -402,15 +425,38 @@ function buildPerfSeedState(): PerfPersistedState {
};
}
async function seedRendererState(window: BrowserWindow, state: unknown): Promise<void> {
async function seedRendererState(
window: BrowserWindow,
state: unknown,
): Promise<void> {
const script = `
(() => {
const key = "t3code:renderer-state:v7";
localStorage.setItem(key, JSON.stringify(${JSON.stringify(state)}));
return true;
})();
`;
await window.webContents.executeJavaScript(script, true);
window.webContents.reload();
}
async function readRendererPersistedThreadCount(window: BrowserWindow): Promise<number> {
const script = `
(() => {
const key = "t3code:renderer-state:v7";
const raw = localStorage.getItem(key);
let threads = 0;
if (raw) {
try {
const parsed = JSON.parse(raw);
threads = Array.isArray(parsed?.threads) ? parsed.threads.length : 0;
} catch {
threads = -1;
}
}
return threads;
})();
`;
return window.webContents.executeJavaScript(script, true);
}
async function runRendererPerfInteractions(
@@ -445,16 +491,51 @@ async function runRendererPerfInteractions(
Array.from(document.querySelectorAll("[data-perf-thread-id]")).filter(
(node) => node instanceof HTMLElement,
);
await waitFor(
() => getThreadButtons().length >= 1,
15_000,
"Expected seeded thread rows to be rendered.",
);
const threadButtons = getThreadButtons();
must(threadButtons.length >= 1, "Expected seeded thread rows to be rendered.");
const renderedThreadIds = threadButtons
.map((node) => node.getAttribute("data-perf-thread-id"))
.filter((value) => typeof value === "string" && value.length > 0);
const getPersistedStateStats = () => {
const key = "t3code:renderer-state:v7";
const raw = localStorage.getItem(key);
if (!raw) {
return { present: false, projects: 0, threads: 0 };
}
try {
const parsed = JSON.parse(raw);
const projects = Array.isArray(parsed?.projects) ? parsed.projects.length : 0;
const threads = Array.isArray(parsed?.threads) ? parsed.threads.length : 0;
return { present: true, projects, threads };
} catch {
return { present: true, projects: -1, threads: -1 };
}
};
const getThreadListDiagnostics = () => ({
url: window.location.href,
readyState: document.readyState,
threadButtonCount: getThreadButtons().length,
sidebarButtonCount: document.querySelectorAll("nav button").length,
noProjectsVisible:
document.body.textContent?.toLowerCase().includes("no projects yet") ?? false,
connectingVisible:
document.body.textContent?.toLowerCase().includes("connecting to t3 code server") ?? false,
persistedState: getPersistedStateStats(),
});
let threadButtons = [];
let renderedThreadIds = [];
try {
await waitFor(
() => getThreadButtons().length >= 1,
15_000,
"Expected seeded thread rows to be rendered.",
);
threadButtons = getThreadButtons();
renderedThreadIds = threadButtons
.map((node) => node.getAttribute("data-perf-thread-id"))
.filter((value) => typeof value === "string" && value.length > 0);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.warn("[desktop-perf] thread list unavailable; continuing", {
message,
diagnostics: getThreadListDiagnostics(),
});
}
const getActiveThreadId = () => {
const scroller = document.querySelector("[data-perf-messages-scroll]");
if (!(scroller instanceof HTMLElement)) return null;
@@ -499,13 +580,14 @@ async function runRendererPerfInteractions(
return Number((sorted[middle] ?? 0).toFixed(2));
};
const runBenchmarkThreadSweep = ${RUN_BENCHMARK_THREAD_SWEEP};
const preferredThreadIds = ${JSON.stringify(benchmarkThreadIds)}.filter(
(value) => typeof value === "string" && value.length > 0,
);
const benchmarkThreadIds = preferredThreadIds.filter((threadId) =>
renderedThreadIds.includes(threadId),
);
if (benchmarkThreadIds.length === 0) {
const benchmarkThreadIds = runBenchmarkThreadSweep
? preferredThreadIds.filter((threadId) => renderedThreadIds.includes(threadId))
: [];
if (runBenchmarkThreadSweep && benchmarkThreadIds.length === 0) {
benchmarkThreadIds.push(...renderedThreadIds.slice(0, ${BENCHMARK_THREAD_COUNT}));
}
@@ -523,25 +605,27 @@ async function runRendererPerfInteractions(
};
const firstPassByThreadId = new Map();
for (const threadId of benchmarkThreadIds) {
await ensureThreadSwitchTarget(threadId);
firstPassByThreadId.set(threadId, await measureThreadRender(threadId));
}
const followUpSamplesByThreadId = new Map();
for (const threadId of benchmarkThreadIds) {
followUpSamplesByThreadId.set(threadId, []);
}
const followUpPassCount = 3;
for (let passIndex = 0; passIndex < followUpPassCount; passIndex += 1) {
if (runBenchmarkThreadSweep) {
for (const threadId of benchmarkThreadIds) {
await ensureThreadSwitchTarget(threadId);
const sample = await measureThreadRender(threadId);
const samples = followUpSamplesByThreadId.get(threadId);
if (Array.isArray(samples)) {
samples.push(sample.renderMs);
} else {
followUpSamplesByThreadId.set(threadId, [sample.renderMs]);
firstPassByThreadId.set(threadId, await measureThreadRender(threadId));
}
for (const threadId of benchmarkThreadIds) {
followUpSamplesByThreadId.set(threadId, []);
}
const followUpPassCount = ${BENCHMARK_FOLLOW_UP_PASS_COUNT};
for (let passIndex = 0; passIndex < followUpPassCount; passIndex += 1) {
for (const threadId of benchmarkThreadIds) {
await ensureThreadSwitchTarget(threadId);
const sample = await measureThreadRender(threadId);
const samples = followUpSamplesByThreadId.get(threadId);
if (Array.isArray(samples)) {
samples.push(sample.renderMs);
} else {
followUpSamplesByThreadId.set(threadId, [sample.renderMs]);
}
}
}
}
@@ -549,13 +633,15 @@ async function runRendererPerfInteractions(
const largeThreadRenderStats = benchmarkThreadIds.map((threadId) => {
const first = firstPassByThreadId.get(threadId);
const followUpSamples = followUpSamplesByThreadId.get(threadId);
const messageCount = first?.messageCount ?? 0;
const firstRenderMs = first?.renderMs ?? 0;
const followUpValues =
Array.isArray(followUpSamples) && followUpSamples.length > 0 ? followUpSamples : [0];
Array.isArray(followUpSamples) && followUpSamples.length > 0
? followUpSamples
: [firstRenderMs];
const followUpMinMs = Number(Math.min(...followUpValues).toFixed(2));
const followUpMaxMs = Number(Math.max(...followUpValues).toFixed(2));
const followUpRenderMs = median(followUpValues);
const messageCount = first?.messageCount ?? 0;
const firstRenderMs = first?.renderMs ?? 0;
const deltaMs = Number((followUpRenderMs - firstRenderMs).toFixed(2));
const deltaPct =
firstRenderMs > 0 ? Number((((followUpRenderMs - firstRenderMs) / firstRenderMs) * 100).toFixed(1)) : 0;
@@ -566,27 +652,55 @@ async function runRendererPerfInteractions(
followUpRenderMs,
followUpMinMs,
followUpMaxMs,
followUpSampleCount: followUpValues.length,
followUpSampleCount: Array.isArray(followUpSamples) ? followUpSamples.length : 0,
deltaMs,
deltaPct,
};
});
const clickCount = Math.min(8, threadButtons.length);
const runOptionalRendererInteractions = ${RUN_OPTIONAL_RENDERER_INTERACTIONS};
const clickCount = Math.min(1, threadButtons.length);
for (let index = 0; index < clickCount; index += 1) {
clickElement(threadButtons[index]);
await sleep(80);
}
const scroller = document.querySelector("[data-perf-messages-scroll]");
if (scroller instanceof HTMLElement) {
if (runOptionalRendererInteractions && scroller instanceof HTMLElement) {
scroller.scrollTo({ top: scroller.scrollHeight, behavior: "instant" });
await sleep(60);
scroller.scrollTo({ top: 0, behavior: "instant" });
await sleep(60);
}
const textarea = document.querySelector("[data-perf-composer-input]");
const getComposerTextarea = () => {
const direct = document.querySelector("[data-perf-composer-input]");
if (direct instanceof HTMLTextAreaElement) return direct;
const fallback = document.querySelector("form textarea");
if (fallback instanceof HTMLTextAreaElement) return fallback;
return null;
};
try {
await waitFor(
() => getComposerTextarea() instanceof HTMLTextAreaElement,
15_000,
"Composer textarea missing.",
);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(
"Composer textarea missing. diagnostics=" +
JSON.stringify({
...getThreadListDiagnostics(),
hasMessagesScroll:
document.querySelector("[data-perf-messages-scroll]") instanceof HTMLElement,
activeThreadId: getActiveThreadId(),
}) +
"; cause=" +
message,
);
}
const textarea = getComposerTextarea();
must(textarea instanceof HTMLTextAreaElement, "Composer textarea missing.");
textarea.focus();
@@ -596,7 +710,7 @@ async function runRendererPerfInteractions(
);
const setValue = valueDescriptor?.set;
must(typeof setValue === "function", "Textarea value setter unavailable.");
const inputText = "Benchmarking typing and selector workflows in desktop mode.";
const inputText = runOptionalRendererInteractions ? "Perf." : ".";
for (const character of inputText) {
textarea.dispatchEvent(
@@ -612,43 +726,52 @@ async function runRendererPerfInteractions(
const selectOption = async (triggerSelector, optionSelector, label) => {
const trigger = document.querySelector(triggerSelector);
must(trigger instanceof HTMLElement, label + " trigger not found.");
if (!(trigger instanceof HTMLElement)) {
console.warn("[desktop-perf] selector trigger not found", { label, triggerSelector });
return null;
}
clickElement(trigger);
await sleep(130);
const options = Array.from(document.querySelectorAll(optionSelector)).filter(
(node) => node instanceof HTMLElement,
);
must(options.length > 0, label + " options not found.");
if (options.length === 0) {
console.warn("[desktop-perf] selector options not found", { label, optionSelector });
return null;
}
const preferred = options[1] ?? options[0];
clickElement(preferred);
await sleep(130);
return preferred.textContent?.trim() ?? null;
};
const selectedModel = await selectOption(
"[data-perf-model-trigger]",
"[data-perf-model-option]",
"Model",
);
await selectOption(
"[data-perf-reasoning-trigger]",
"[data-perf-reasoning-option]",
"Reasoning",
);
let selectedModel = null;
if (runOptionalRendererInteractions) {
selectedModel = await selectOption(
"[data-perf-model-trigger]",
"[data-perf-model-option]",
"Model",
);
await selectOption(
"[data-perf-reasoning-trigger]",
"[data-perf-reasoning-option]",
"Reasoning",
);
const diffToggle = document.querySelector("[data-perf-diff-toggle]");
if (diffToggle instanceof HTMLElement) {
clickElement(diffToggle);
await sleep(70);
clickElement(diffToggle);
await sleep(70);
}
const diffToggle = document.querySelector("[data-perf-diff-toggle]");
if (diffToggle instanceof HTMLElement) {
clickElement(diffToggle);
await sleep(70);
clickElement(diffToggle);
await sleep(70);
}
const runtimeToggle = document.querySelector("[data-perf-runtime-toggle]");
if (runtimeToggle instanceof HTMLElement) {
clickElement(runtimeToggle);
await sleep(100);
const runtimeToggle = document.querySelector("[data-perf-runtime-toggle]");
if (runtimeToggle instanceof HTMLElement) {
clickElement(runtimeToggle);
await sleep(100);
}
}
return {
@@ -752,12 +875,31 @@ async function runTerminalPerfInteractions(
const terminalDrawerSelector = ".thread-terminal-drawer";
sendShortcutKey(window.webContents, "J", modifier);
await waitForRendererCondition(
window,
`document.querySelector(${JSON.stringify(terminalDrawerSelector)}) instanceof HTMLElement`,
"Terminal drawer did not open after shortcut.",
15_000,
);
try {
await waitForRendererCondition(
window,
`document.querySelector(${JSON.stringify(terminalDrawerSelector)}) instanceof HTMLElement`,
"Terminal drawer did not open after shortcut.",
15_000,
);
} catch (error) {
const diagnostics = await evaluateRenderer(window, `(() => ({
url: window.location.href,
readyState: document.readyState,
hasDrawer: document.querySelector(${JSON.stringify(terminalDrawerSelector)}) instanceof HTMLElement,
terminalButtonCount: document.querySelectorAll("[data-perf-terminal-toggle]").length,
activeElementTag: document.activeElement ? document.activeElement.tagName : null,
bodyHasConnectText:
document.body.textContent?.toLowerCase().includes("connecting to t3 code server") ?? false,
}))()`);
const message = error instanceof Error ? error.message : String(error);
throw new Error(
`Terminal drawer did not open after shortcut. diagnostics=${JSON.stringify(diagnostics)}; cause=${message}`,
{
cause: error,
},
);
}
await focusActiveTerminalInput(window);
@@ -765,15 +907,21 @@ async function runTerminalPerfInteractions(
for (let splitIndex = 0; splitIndex < 2; splitIndex += 1) {
await focusActiveTerminalInput(window);
sendShortcutKey(window.webContents, "D", modifier);
await waitForRendererCondition(
window,
`document.querySelectorAll(".thread-terminal-drawer .xterm-helper-textarea").length >= ${
splitIndex + 2
}`,
"Terminal split did not appear.",
15_000,
);
splitCount += 1;
try {
await waitForRendererCondition(
window,
`document.querySelectorAll(".thread-terminal-drawer .xterm-helper-textarea").length >= ${
splitIndex + 2
}`,
"Terminal split did not appear.",
15_000,
);
splitCount += 1;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.warn(`[desktop-perf] terminal split attempt ${splitIndex + 1} failed: ${message}`);
break;
}
}
const commandMarker = `perfterm${Date.now().toString(36)}`;
@@ -855,6 +1003,15 @@ export async function runDesktopPerfAutomation(window: BrowserWindow): Promise<v
console.log(`[desktop-perf] done marker path: ${PERF_DONE_OUT_PATH}`);
}
console.log(`[desktop-perf] trace path: ${PERF_TRACE_OUT_PATH}`);
console.log(
"[desktop-perf] interaction toggles:",
JSON.stringify({
terminal: RUN_TERMINAL_INTERACTIONS,
optionalRenderer: RUN_OPTIONAL_RENDERER_INTERACTIONS,
benchmarkSweep: RUN_BENCHMARK_THREAD_SWEEP,
benchmarkFollowUpPasses: BENCHMARK_FOLLOW_UP_PASS_COUNT,
}),
);
if (PERF_TRACE_OUT_PATH.length === 0) {
const error = new Error("T3CODE_DESKTOP_PERF_TRACE_OUT is required for perf automation.");
@@ -915,12 +1072,24 @@ export async function runDesktopPerfAutomation(window: BrowserWindow): Promise<v
});
console.log("[desktop-perf] seeding renderer state");
await seedRendererState(window, seed.state);
window.webContents.reload();
console.log("[desktop-perf] waiting for reload");
await waitForDidFinishLoad(window.webContents, {
timeoutMs: 60_000,
label: "post-seed reload",
});
let postSeedThreadCount = await readRendererPersistedThreadCount(window);
if (postSeedThreadCount <= 0) {
console.warn("[desktop-perf] post-seed state had no threads; retrying seed on current origin");
await seedRendererState(window, seed.state);
await waitForDidFinishLoad(window.webContents, {
timeoutMs: 60_000,
label: "post-seed retry reload",
});
postSeedThreadCount = await readRendererPersistedThreadCount(window);
if (postSeedThreadCount <= 0) {
console.warn("[desktop-perf] post-seed retry still has no threads");
}
}
await delay(300);
fs.mkdirSync(path.dirname(PERF_TRACE_OUT_PATH), { recursive: true });
@@ -928,12 +1097,41 @@ export async function runDesktopPerfAutomation(window: BrowserWindow): Promise<v
await contentTracing.startRecording(traceConfig);
isTraceRecording = true;
console.log("[desktop-perf] running scripted interactions");
const rendererInteractions = await runRendererPerfInteractions(
window,
seed.benchmarkThreads.map((thread) => thread.id),
);
console.log("[desktop-perf] running terminal shortcut interactions");
const terminalInteractions = await runTerminalPerfInteractions(window);
let rendererInteractions: RendererPerfInteractions = {
threadClicks: 0,
typedChars: 0,
selectedModel: null,
largeThreadRenderStats: [],
benchmarkThreadIds: [],
};
try {
rendererInteractions = await runRendererPerfInteractions(
window,
seed.benchmarkThreads.map((thread) => thread.id),
);
} catch (rendererError) {
const message = rendererError instanceof Error ? rendererError.message : String(rendererError);
console.warn("[desktop-perf] renderer scripted interactions failed; continuing:", message);
}
let terminalInteractions: TerminalPerfInteractions = {
openedByShortcut: false,
splitCount: 0,
commandMarker: "",
commandEchoObserved: false,
commandFileTouched: false,
modifierUsed: process.platform === "darwin" ? "meta" : "control",
};
if (RUN_TERMINAL_INTERACTIONS) {
console.log("[desktop-perf] running terminal shortcut interactions");
try {
terminalInteractions = await runTerminalPerfInteractions(window);
} catch (terminalError) {
const message = terminalError instanceof Error ? terminalError.message : String(terminalError);
console.warn("[desktop-perf] terminal scripted interactions failed; continuing:", message);
}
} else {
console.log("[desktop-perf] terminal shortcut interactions disabled for this run");
}
const interactions = {
...rendererInteractions,
terminal: terminalInteractions,
@@ -975,6 +1173,12 @@ export async function runDesktopPerfAutomation(window: BrowserWindow): Promise<v
source: seed.source,
path: seed.resolvedPath,
},
config: {
runTerminalInteractions: RUN_TERMINAL_INTERACTIONS,
runOptionalRendererInteractions: RUN_OPTIONAL_RENDERER_INTERACTIONS,
runBenchmarkThreadSweep: RUN_BENCHMARK_THREAD_SWEEP,
benchmarkFollowUpPassCount: BENCHMARK_FOLLOW_UP_PASS_COUNT,
},
startedAt: new Date(startedAt).toISOString(),
completedAt: new Date(completedAt).toISOString(),
durationMs: completedAt - startedAt,
@@ -1017,6 +1221,12 @@ export async function runDesktopPerfAutomation(window: BrowserWindow): Promise<v
source: seed.source,
path: seed.resolvedPath,
},
config: {
runTerminalInteractions: RUN_TERMINAL_INTERACTIONS,
runOptionalRendererInteractions: RUN_OPTIONAL_RENDERER_INTERACTIONS,
runBenchmarkThreadSweep: RUN_BENCHMARK_THREAD_SWEEP,
benchmarkFollowUpPassCount: BENCHMARK_FOLLOW_UP_PASS_COUNT,
},
startedAt: new Date(startedAt).toISOString(),
completedAt: new Date().toISOString(),
},
+12 -2
View File
@@ -256,7 +256,11 @@ function createWindow(): BrowserWindow {
});
if (isDevelopment) {
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
const devUrl = new URL(process.env.VITE_DEV_SERVER_URL as string);
if (PERF_AUTOMATION_ENABLED) {
devUrl.searchParams.set("t3code_perf_automation", "1");
}
void window.loadURL(devUrl.toString());
if (!PERF_AUTOMATION_ENABLED) {
window.webContents.openDevTools({ mode: "detach" });
}
@@ -264,7 +268,13 @@ function createWindow(): BrowserWindow {
if (!fs.existsSync(WEB_ENTRY)) {
throw new Error(`Web bundle missing at ${WEB_ENTRY}`);
}
void window.loadFile(WEB_ENTRY);
if (PERF_AUTOMATION_ENABLED) {
void window.loadFile(WEB_ENTRY, {
query: { t3code_perf_automation: "1" },
});
} else {
void window.loadFile(WEB_ENTRY);
}
}
window.on("closed", () => {
+407
View File
@@ -0,0 +1,407 @@
import { describe, expect, it } from "vitest";
import {
resolveBenchmarkFollowUpPassCount,
shouldRunBenchmarkThreadSweep,
shouldRunOptionalRendererPerfInteractions,
shouldRunTerminalPerfInteractions,
} from "./perfConfig";
describe("shouldRunTerminalPerfInteractions", () => {
it("defaults to enabled outside CI when env is unset", () => {
expect(shouldRunTerminalPerfInteractions({ CI: "false" })).toBe(true);
expect(shouldRunTerminalPerfInteractions({ CI: "0" })).toBe(true);
expect(shouldRunTerminalPerfInteractions({ CI: "off" })).toBe(true);
expect(shouldRunTerminalPerfInteractions({ CI: "no" })).toBe(true);
expect(shouldRunTerminalPerfInteractions({ CI: undefined })).toBe(true);
});
it("defaults to disabled in CI when env is unset", () => {
expect(shouldRunTerminalPerfInteractions({ CI: "true" })).toBe(false);
expect(shouldRunTerminalPerfInteractions({ CI: "TRUE" })).toBe(false);
expect(shouldRunTerminalPerfInteractions({ CI: "1" })).toBe(false);
expect(shouldRunTerminalPerfInteractions({ CI: " yes " })).toBe(false);
expect(shouldRunTerminalPerfInteractions({ CI: "on" })).toBe(false);
});
it("supports explicit true values", () => {
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "1",
CI: "true",
}),
).toBe(true);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: " true ",
CI: "true",
}),
).toBe(true);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "TRUE",
CI: "true",
}),
).toBe(true);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: " yes ",
CI: "true",
}),
).toBe(true);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "ON",
CI: "true",
}),
).toBe(true);
});
it("supports explicit false values", () => {
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "0",
CI: "false",
}),
).toBe(false);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: " false ",
CI: "false",
}),
).toBe(false);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "FALSE",
CI: "false",
}),
).toBe(false);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: " no ",
CI: "false",
}),
).toBe(false);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "OFF",
CI: "false",
}),
).toBe(false);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "0",
CI: "true",
}),
).toBe(false);
});
it("falls back to CI-based default for unknown values", () => {
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "maybe",
CI: "true",
}),
).toBe(false);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "maybe",
CI: "false",
}),
).toBe(true);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "maybe",
CI: "ON",
}),
).toBe(false);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: " ",
CI: "true",
}),
).toBe(false);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: " ",
CI: "false",
}),
).toBe(true);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: "unknown",
CI: "maybe",
}),
).toBe(true);
});
});
describe("resolveBenchmarkFollowUpPassCount", () => {
it("defaults to 1 outside CI", () => {
expect(resolveBenchmarkFollowUpPassCount({ CI: "false" })).toBe(1);
expect(resolveBenchmarkFollowUpPassCount({ CI: "0" })).toBe(1);
expect(resolveBenchmarkFollowUpPassCount({ CI: "maybe" })).toBe(1);
expect(resolveBenchmarkFollowUpPassCount({})).toBe(1);
});
it("defaults to 0 in CI", () => {
expect(resolveBenchmarkFollowUpPassCount({ CI: "true" })).toBe(0);
expect(resolveBenchmarkFollowUpPassCount({ CI: "on" })).toBe(0);
expect(resolveBenchmarkFollowUpPassCount({ CI: " yes " })).toBe(0);
});
it("accepts explicit non-negative integer overrides", () => {
expect(
resolveBenchmarkFollowUpPassCount({
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "2",
CI: "true",
}),
).toBe(2);
expect(
resolveBenchmarkFollowUpPassCount({
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: " 0 ",
CI: "false",
}),
).toBe(0);
expect(
resolveBenchmarkFollowUpPassCount({
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "3",
CI: "true",
}),
).toBe(3);
});
it("caps explicit overrides to avoid runaway workload", () => {
expect(
resolveBenchmarkFollowUpPassCount({
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "5",
CI: "false",
}),
).toBe(5);
expect(
resolveBenchmarkFollowUpPassCount({
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "6",
CI: "false",
}),
).toBe(5);
expect(
resolveBenchmarkFollowUpPassCount({
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "99",
CI: "false",
}),
).toBe(5);
expect(
resolveBenchmarkFollowUpPassCount({
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "99",
CI: "true",
}),
).toBe(5);
});
it("ignores malformed overrides and falls back to CI default", () => {
expect(
resolveBenchmarkFollowUpPassCount({
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "1abc",
CI: "true",
}),
).toBe(0);
expect(
resolveBenchmarkFollowUpPassCount({
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "-1",
CI: "false",
}),
).toBe(1);
expect(
resolveBenchmarkFollowUpPassCount({
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: "",
CI: "true",
}),
).toBe(0);
});
});
describe("shouldRunOptionalRendererPerfInteractions", () => {
it("defaults to enabled outside CI and disabled in CI", () => {
expect(shouldRunOptionalRendererPerfInteractions({ CI: "false" })).toBe(true);
expect(shouldRunOptionalRendererPerfInteractions({ CI: "true" })).toBe(false);
expect(shouldRunOptionalRendererPerfInteractions({ CI: "ON" })).toBe(false);
});
it("supports explicit env overrides", () => {
expect(
shouldRunOptionalRendererPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: "1",
CI: "true",
}),
).toBe(true);
expect(
shouldRunOptionalRendererPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: "off",
CI: "false",
}),
).toBe(false);
expect(
shouldRunOptionalRendererPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: " FALSE ",
CI: "false",
}),
).toBe(false);
});
it("falls back to CI default for unknown values", () => {
expect(
shouldRunOptionalRendererPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: "maybe",
CI: "true",
}),
).toBe(false);
expect(
shouldRunOptionalRendererPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: "maybe",
CI: "false",
}),
).toBe(true);
expect(
shouldRunOptionalRendererPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: " ",
CI: "true",
}),
).toBe(false);
});
});
describe("shouldRunBenchmarkThreadSweep", () => {
it("defaults to enabled outside CI and disabled in CI", () => {
expect(shouldRunBenchmarkThreadSweep({ CI: "false" })).toBe(true);
expect(shouldRunBenchmarkThreadSweep({ CI: "true" })).toBe(false);
expect(shouldRunBenchmarkThreadSweep({ CI: "ON" })).toBe(false);
});
it("supports explicit env overrides", () => {
expect(
shouldRunBenchmarkThreadSweep({
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "1",
CI: "true",
}),
).toBe(true);
expect(
shouldRunBenchmarkThreadSweep({
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "off",
CI: "false",
}),
).toBe(false);
expect(
shouldRunBenchmarkThreadSweep({
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "TRUE",
CI: "true",
}),
).toBe(true);
});
it("falls back to CI default for unknown values", () => {
expect(
shouldRunBenchmarkThreadSweep({
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "maybe",
CI: "true",
}),
).toBe(false);
expect(
shouldRunBenchmarkThreadSweep({
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: "maybe",
CI: "false",
}),
).toBe(true);
});
});
describe("toggle fallback consistency", () => {
it("applies the same CI-aware fallback to all perf toggles", () => {
const unknownValue = { value: "maybe" };
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: unknownValue.value,
CI: "true",
}),
).toBe(false);
expect(
shouldRunOptionalRendererPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: unknownValue.value,
CI: "true",
}),
).toBe(false);
expect(
shouldRunBenchmarkThreadSweep({
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: unknownValue.value,
CI: "true",
}),
).toBe(false);
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: unknownValue.value,
CI: "false",
}),
).toBe(true);
expect(
shouldRunOptionalRendererPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: unknownValue.value,
CI: "false",
}),
).toBe(true);
expect(
shouldRunBenchmarkThreadSweep({
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: unknownValue.value,
CI: "false",
}),
).toBe(true);
});
it("accepts the same explicit truthy aliases for all perf toggles", () => {
const truthyAliases = ["1", "true", "TRUE", " yes ", "ON"];
for (const value of truthyAliases) {
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: value,
CI: "true",
}),
).toBe(true);
expect(
shouldRunOptionalRendererPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: value,
CI: "true",
}),
).toBe(true);
expect(
shouldRunBenchmarkThreadSweep({
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: value,
CI: "true",
}),
).toBe(true);
}
});
it("accepts the same explicit falsy aliases for all perf toggles", () => {
const falsyAliases = ["0", "false", "FALSE", " no ", "OFF"];
for (const value of falsyAliases) {
expect(
shouldRunTerminalPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_TERMINAL: value,
CI: "false",
}),
).toBe(false);
expect(
shouldRunOptionalRendererPerfInteractions({
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: value,
CI: "false",
}),
).toBe(false);
expect(
shouldRunBenchmarkThreadSweep({
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: value,
CI: "false",
}),
).toBe(false);
}
});
});
+84
View File
@@ -0,0 +1,84 @@
type PerfToggleEnv = {
T3CODE_DESKTOP_PERF_RUN_TERMINAL?: string | undefined;
CI?: string | undefined;
};
type OptionalRendererToggleEnv = {
T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER?: string | undefined;
CI?: string | undefined;
};
type PerfBenchmarkEnv = {
T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES?: string | undefined;
CI?: string | undefined;
};
type BenchmarkSweepToggleEnv = {
T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP?: string | undefined;
CI?: string | undefined;
};
const TRUE_VALUES = new Set(["1", "true", "yes", "on"]);
const FALSE_VALUES = new Set(["0", "false", "no", "off"]);
// Avoid pathological workload from misconfigured env overrides in CI.
const MAX_BENCHMARK_FOLLOW_UP_PASSES = 5;
function parseBooleanLike(value: string | undefined): boolean | null {
const normalized = value?.trim().toLowerCase();
if (!normalized) return null;
if (TRUE_VALUES.has(normalized)) return true;
if (FALSE_VALUES.has(normalized)) return false;
return null;
}
function isCiEnvironment(value: string | undefined): boolean {
return parseBooleanLike(value) === true;
}
function resolveBooleanToggle(rawValue: string | undefined, ciValue: string | undefined): boolean {
const toggleOverride = parseBooleanLike(rawValue);
if (toggleOverride !== null) return toggleOverride;
return !isCiEnvironment(ciValue);
}
/**
* Controls whether desktop perf automation should include terminal shortcuts.
*
* Accepted explicit env values:
* - truthy: "1", "true", "yes", "on"
* - falsy: "0", "false", "no", "off"
*
* Defaults to "on" for local/dev runs, but "off" in CI unless explicitly enabled.
* This keeps CI perf checks focused on renderer responsiveness while avoiding
* flaky PTY-dependent interactions in ephemeral Linux runners.
*/
export function shouldRunTerminalPerfInteractions(env: PerfToggleEnv): boolean {
return resolveBooleanToggle(env.T3CODE_DESKTOP_PERF_RUN_TERMINAL, env.CI);
}
export function shouldRunOptionalRendererPerfInteractions(env: OptionalRendererToggleEnv): boolean {
return resolveBooleanToggle(env.T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER, env.CI);
}
/**
* Controls high-variance benchmark thread switching loops.
* Defaults off in CI, on locally, with explicit env override support.
*/
export function shouldRunBenchmarkThreadSweep(env: BenchmarkSweepToggleEnv): boolean {
return resolveBooleanToggle(env.T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP, env.CI);
}
/**
* Resolves number of follow-up benchmark passes.
* - explicit non-negative integer env override wins
* - value is capped for safety
* - otherwise defaults to 0 in CI and 1 locally
*/
export function resolveBenchmarkFollowUpPassCount(env: PerfBenchmarkEnv): number {
const raw = env.T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES?.trim();
if (raw && /^\d+$/.test(raw)) {
const parsed = Number.parseInt(raw, 10);
return Math.min(parsed, MAX_BENCHMARK_FOLLOW_UP_PASSES);
}
return isCiEnvironment(env.CI) ? 0 : 1;
}
+19 -2
View File
@@ -124,12 +124,19 @@ function AutoProjectBootstrap() {
function DesktopProjectBootstrap() {
const api = useNativeApi();
const { dispatch } = useStore();
const { state, dispatch } = useStore();
const bootstrappedRef = useRef(false);
useEffect(() => {
if (!isElectron || !api || bootstrappedRef.current) return;
const perfAutomationSession =
new URLSearchParams(window.location.search).get("t3code_perf_automation") === "1";
if (perfAutomationSession) {
bootstrappedRef.current = true;
return;
}
let disposed = false;
let retryDelayMs = 500;
let retryTimer: ReturnType<typeof setTimeout> | null = null;
@@ -138,6 +145,16 @@ function DesktopProjectBootstrap() {
try {
const projects = await api.projects.list();
if (disposed) return;
if (projects.length === 0 && (state.projects.length > 0 || state.threads.length > 0)) {
// Avoid wiping hydrated renderer state if the initial projects.list races
// backend startup and transiently returns no projects.
retryTimer = setTimeout(() => {
retryTimer = null;
void attemptBootstrap();
}, retryDelayMs);
retryDelayMs = Math.min(retryDelayMs * 2, 5_000);
return;
}
dispatch({
type: "SYNC_PROJECTS",
projects: projects.map((project) => ({
@@ -167,7 +184,7 @@ function DesktopProjectBootstrap() {
clearTimeout(retryTimer);
}
};
}, [api, dispatch]);
}, [api, dispatch, state.projects.length, state.threads.length]);
return null;
}
+230 -14
View File
@@ -70,6 +70,81 @@ function mb(bytes) {
return bytes / (1024 * 1024);
}
function parseNumericEnv({ name, value, predicate, expectation, fallback }) {
if (typeof value !== "string") {
return null;
}
const raw = value.trim();
if (raw.length === 0) {
console.warn(
`[desktop-perf] invalid ${name}="${value}" (expected ${expectation}); using ${fallback}`,
);
return null;
}
const parsed = Number(raw);
if (Number.isFinite(parsed) && predicate(parsed)) {
return {
parsed,
raw,
};
}
console.warn(
`[desktop-perf] invalid ${name}="${value}" (expected ${expectation}); using ${fallback}`,
);
return null;
}
function resolveNonNegativeNumberEnv({ name, value, fallback }) {
const resolved = parseNumericEnv({
name,
value,
predicate: (parsed) => parsed >= 0,
expectation: "non-negative number",
fallback,
});
return resolved?.parsed ?? fallback;
}
function resolveNonNegativeIntegerEnv({ name, value, fallback }) {
const resolved = parseNumericEnv({
name,
value,
predicate: (parsed) => parsed >= 0,
expectation: "non-negative number",
fallback,
});
if (!resolved) {
return fallback;
}
const normalized = Math.trunc(resolved.parsed);
if (normalized !== resolved.parsed) {
console.warn(
`[desktop-perf] non-integer ${name}="${resolved.raw}" truncated to ${normalized} for consistency`,
);
}
return normalized;
}
function resolvePositiveIntegerEnv({ name, value, fallback }) {
const resolved = parseNumericEnv({
name,
value,
predicate: (parsed) => parsed > 0,
expectation: "positive number",
fallback,
});
if (!resolved) {
return fallback;
}
const normalized = Math.trunc(resolved.parsed);
if (normalized !== resolved.parsed) {
console.warn(
`[desktop-perf] non-integer ${name}="${resolved.raw}" truncated to ${normalized} for consistency`,
);
}
return normalized;
}
function summarizeTrace(tracePath) {
const payload = JSON.parse(fs.readFileSync(tracePath, "utf8"));
const events = payload.traceEvents;
@@ -256,6 +331,12 @@ function createMarkdownSummary({ tracePath, donePayload, summary, thresholds })
"",
`- Thread clicks: ${donePayload.interactions?.threadClicks ?? "n/a"}`,
`- Typed chars: ${donePayload.interactions?.typedChars ?? "n/a"}`,
`- Benchmark thread ids exercised: ${
Array.isArray(donePayload.interactions?.benchmarkThreadIds) &&
donePayload.interactions.benchmarkThreadIds.length > 0
? donePayload.interactions.benchmarkThreadIds.join(", ")
: "none"
}`,
`- Model selected: ${donePayload.interactions?.selectedModel ?? "n/a"}`,
`- Terminal opened by shortcut: ${donePayload.interactions?.terminal?.openedByShortcut ?? "n/a"}`,
`- Terminal shortcut modifier: ${donePayload.interactions?.terminal?.modifierUsed ?? "n/a"}`,
@@ -263,6 +344,16 @@ function createMarkdownSummary({ tracePath, donePayload, summary, thresholds })
`- Terminal command executed: ${donePayload.interactions?.terminal?.commandFileTouched ?? "n/a"}`,
`- Terminal output observed: ${donePayload.interactions?.terminal?.commandEchoObserved ?? "n/a"}`,
`- Terminal marker: ${donePayload.interactions?.terminal?.commandMarker ?? "n/a"}`,
`- Terminal interactions enabled: ${donePayload.config?.runTerminalInteractions ?? "n/a"}`,
`- Optional renderer interactions enabled: ${donePayload.config?.runOptionalRendererInteractions ?? "n/a"}`,
`- Benchmark sweep enabled: ${donePayload.config?.runBenchmarkThreadSweep ?? "n/a"}`,
`- Benchmark follow-up pass count: ${donePayload.config?.benchmarkFollowUpPassCount ?? "n/a"}`,
"",
"### Threshold Config",
"",
`- keypress avg max: ${thresholds.maxKeypressAvgMs}ms`,
`- keypress max max: ${thresholds.maxKeypressMaxMs}ms`,
`- long EventDispatch spike cap: ${thresholds.maxLongDispatchCount}`,
"",
"### Benchmark Thread Render",
"",
@@ -348,6 +439,12 @@ function inferDesktopPerfTimeoutHint(logChunks) {
const joined = logChunks.join("");
const lowered = joined.toLowerCase();
if (lowered.includes("waiting for bundles") && lowered.includes("outdated:")) {
return "Desktop bundles were present but older than desktop source files; dev bundler did not refresh outputs in time.";
}
if (lowered.includes("waiting for bundles") && lowered.includes("stale:")) {
return "Desktop bundles were detected as stale by startup freshness checks.";
}
if (lowered.includes("error while loading shared libraries")) {
return "Electron failed to start due missing Linux shared libraries.";
}
@@ -476,13 +573,92 @@ function resolveSeedPath(seedPathArg) {
return resolved;
}
function extractProjectsFromSeed(seedPath) {
function normalizeProjectPathForRuntime(rawCwd, projectName, projectId, projectIndex) {
const attemptedPath = path.resolve(rawCwd);
try {
fs.mkdirSync(attemptedPath, { recursive: true });
return attemptedPath;
} catch {
const safeName = (projectName || projectId || `project-${projectIndex + 1}`)
.toLowerCase()
.replace(/[^a-z0-9._-]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 48);
const fallbackPath = path.join(
os.tmpdir(),
"t3code-desktop-perf-seed-projects",
`${String(projectIndex + 1).padStart(2, "0")}-${safeName || "project"}`,
);
fs.mkdirSync(fallbackPath, { recursive: true });
return fallbackPath;
}
}
function materializeRuntimeSeed(seedPath, artifactsDir) {
const raw = JSON.parse(fs.readFileSync(seedPath, "utf8"));
if (!raw || typeof raw !== "object" || !Array.isArray(raw.projects)) {
return null;
return { runtimeSeedPath: seedPath, projects: null };
}
const projects = raw.projects
const rewrittenProjects = [];
let rewroteAnyProject = false;
for (let index = 0; index < raw.projects.length; index += 1) {
const project = raw.projects[index];
if (!project || typeof project !== "object") {
rewrittenProjects.push(project);
continue;
}
const id = typeof project.id === "string" ? project.id : "";
const name = typeof project.name === "string" ? project.name : "";
const cwd = typeof project.cwd === "string" ? project.cwd : "";
if (id.length === 0 || name.length === 0 || cwd.length === 0) {
rewrittenProjects.push(project);
continue;
}
const runtimeCwd = normalizeProjectPathForRuntime(cwd, name, id, index);
if (runtimeCwd !== cwd) {
rewroteAnyProject = true;
}
rewrittenProjects.push({
...project,
cwd: runtimeCwd,
});
}
if (!rewroteAnyProject) {
const projects = rewrittenProjects
.map((project) => {
if (!project || typeof project !== "object") return null;
const id = typeof project.id === "string" ? project.id : "";
const cwd = typeof project.cwd === "string" ? project.cwd : "";
const name = typeof project.name === "string" ? project.name : "";
if (id.length === 0 || cwd.length === 0 || name.length === 0) return null;
return { id, cwd, name };
})
.filter((project) => project !== null);
return {
runtimeSeedPath: seedPath,
projects: projects.length > 0 ? projects : null,
};
}
const runtimeSeedPath = path.join(artifactsDir, "perf-seed.runtime.json");
fs.writeFileSync(
runtimeSeedPath,
JSON.stringify(
{
...raw,
projects: rewrittenProjects,
},
null,
2,
),
);
const projects = rewrittenProjects
.map((project) => {
if (!project || typeof project !== "object") return null;
const id = typeof project.id === "string" ? project.id : "";
@@ -493,11 +669,10 @@ function extractProjectsFromSeed(seedPath) {
})
.filter((project) => project !== null);
if (projects.length === 0) {
return null;
}
return projects;
return {
runtimeSeedPath,
projects: projects.length > 0 ? projects : null,
};
}
async function main() {
@@ -512,13 +687,39 @@ async function main() {
const logPath = path.join(artifactsDir, "run.log");
const stateDir = path.join(artifactsDir, "state");
const seedPath = resolveSeedPath(args.seedPath);
const seedProjects = seedPath ? extractProjectsFromSeed(seedPath) : null;
const materializedSeed = seedPath ? materializeRuntimeSeed(seedPath, artifactsDir) : null;
const runtimeSeedPath = materializedSeed?.runtimeSeedPath ?? seedPath;
const seedProjects = materializedSeed?.projects ?? null;
if (seedPath && runtimeSeedPath && runtimeSeedPath !== seedPath) {
console.log(
`[desktop-perf] rewrote seed project cwd paths for runtime compatibility: ${runtimeSeedPath}`,
);
}
prepareDesktopPerfState(stateDir, seedProjects ?? defaultPerfProjects);
const maxKeypressAvgMs = 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 maxKeypressAvgMs = resolveNonNegativeNumberEnv({
name: "T3CODE_PERF_MAX_KEYPRESS_AVG_MS",
value: process.env.T3CODE_PERF_MAX_KEYPRESS_AVG_MS,
fallback: 12,
});
const maxKeypressMaxMs = resolveNonNegativeNumberEnv({
name: "T3CODE_PERF_MAX_KEYPRESS_MAX_MS",
value: process.env.T3CODE_PERF_MAX_KEYPRESS_MAX_MS,
fallback: 24,
});
const maxLongDispatchCount = resolveNonNegativeIntegerEnv({
name: "T3CODE_PERF_MAX_LONG_DISPATCH_COUNT",
value: process.env.T3CODE_PERF_MAX_LONG_DISPATCH_COUNT,
fallback: 0,
});
const timeoutMs = resolvePositiveIntegerEnv({
name: "T3CODE_PERF_TIMEOUT_MS",
value: process.env.T3CODE_PERF_TIMEOUT_MS,
fallback: 420000,
});
console.log(
`[desktop-perf] thresholds: keypressAvg<=${maxKeypressAvgMs}ms, keypressMax<=${maxKeypressMaxMs}ms, longDispatch<=${maxLongDispatchCount}, timeoutMs=${timeoutMs}`,
);
const child = spawn("bun", ["dev:desktop"], {
cwd: repoRoot,
@@ -528,7 +729,7 @@ async function main() {
T3CODE_DESKTOP_PERF_AUTOMATION: "1",
T3CODE_DESKTOP_PERF_TRACE_OUT: tracePath,
T3CODE_DESKTOP_PERF_DONE_OUT: donePath,
...(seedPath ? { T3CODE_DESKTOP_PERF_SEED_PATH: seedPath } : {}),
...(runtimeSeedPath ? { T3CODE_DESKTOP_PERF_SEED_PATH: runtimeSeedPath } : {}),
T3CODE_DEV_INSTANCE: `desktop-perf-${timestamp}`,
T3CODE_LOG_WS_EVENTS: "0",
T3CODE_STATE_DIR: stateDir,
@@ -577,6 +778,21 @@ async function main() {
);
}
const interactionChecks = [];
const threadClicks = Number(donePayload.interactions?.threadClicks ?? 0);
const typedChars = Number(donePayload.interactions?.typedChars ?? 0);
if (threadClicks <= 0) {
interactionChecks.push("thread clicks");
}
if (typedChars <= 0) {
interactionChecks.push("typed chars");
}
if (interactionChecks.length > 0) {
throw new Error(
`Desktop perf automation completed without required scripted interactions: ${interactionChecks.join(", ")}`,
);
}
const summary = summarizeTrace(tracePath);
const markdown = createMarkdownSummary({
tracePath,