Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
707889950d | ||
|
|
4d976b8bf7 | ||
|
|
0c50a2d8e1 | ||
|
|
f64c26e708 | ||
|
|
6d8d39a5d1 | ||
|
|
afdfe16931 |
No files matched your search
@@ -6,10 +6,6 @@ on:
|
||||
branches:
|
||||
- main
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
name: Lint, Typecheck, Test, Build
|
||||
@@ -50,62 +46,5 @@ jobs:
|
||||
|
||||
- name: Verify preload bundle output
|
||||
run: |
|
||||
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
|
||||
test -f apps/desktop/dist-electron/preload.js
|
||||
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
|
||||
@@ -2,14 +2,13 @@
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.mjs",
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
"dev": "bun run --parallel dev:bundle dev:electron",
|
||||
"dev:bundle": "tsdown --watch --no-clean",
|
||||
"dev:bundle": "tsdown --watch",
|
||||
"dev:electron": "bun run scripts/dev-electron.mjs",
|
||||
"build": "tsdown",
|
||||
"start": "electron dist-electron/main.mjs",
|
||||
"start": "electron dist-electron/main.js",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
|
||||
@@ -1,150 +1,24 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import net from "node:net";
|
||||
|
||||
import waitOn from "wait-on";
|
||||
|
||||
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5173);
|
||||
const STARTUP_TIMEOUT_MS = Number(process.env.T3CODE_ELECTRON_STARTUP_TIMEOUT_MS ?? 120_000);
|
||||
const devServerUrl = `http://localhost:${port}`;
|
||||
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
function waitForDesktopBundles(timeoutMs) {
|
||||
const FRESHNESS_GRACE_MS = 10_000;
|
||||
const startedAt = Date.now();
|
||||
const bundleFiles = [
|
||||
{ path: "dist-electron/main.mjs", requireFresh: true },
|
||||
{ path: "dist-electron/preload.cjs", requireFresh: true },
|
||||
{ path: "../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}`);
|
||||
await waitOn({
|
||||
resources: [
|
||||
`tcp:${port}`,
|
||||
"file:dist-electron/main.js",
|
||||
"file:dist-electron/preload.js",
|
||||
"file:../server/dist/index.mjs",
|
||||
],
|
||||
});
|
||||
|
||||
const command = process.platform === "win32" ? "electronmon.cmd" : "electronmon";
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
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"], {
|
||||
const child = spawn(command, ["dist-electron/main.js"], {
|
||||
stdio: "inherit",
|
||||
env: {
|
||||
...childEnv,
|
||||
@@ -155,8 +29,3 @@ const child = spawn(command, ["dist-electron/main.mjs"], {
|
||||
child.on("exit", (code) => {
|
||||
process.exit(code ?? 0);
|
||||
});
|
||||
|
||||
child.on("error", (error) => {
|
||||
console.error("[dev-electron] failed to launch electronmon:", error.message);
|
||||
process.exit(1);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,9 +1,11 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { resolve } from "node:path";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const desktopDir = resolve(import.meta.dirname, "..");
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const desktopDir = resolve(__dirname, "..");
|
||||
const electronBin = resolve(desktopDir, "node_modules/.bin/electron");
|
||||
const mainJs = resolve(desktopDir, "dist-electron/main.mjs");
|
||||
const mainJs = resolve(desktopDir, "dist-electron/main.js");
|
||||
|
||||
console.log("\nLaunching Electron smoke test...");
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -16,13 +16,11 @@ 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(import.meta.dirname, "../../..");
|
||||
const ROOT_DIR = path.resolve(__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 =
|
||||
process.env.T3CODE_STATE_DIR?.trim() || path.join(os.homedir(), ".t3", "userdata");
|
||||
const STATE_DIR = 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;
|
||||
@@ -33,32 +31,6 @@ 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();
|
||||
@@ -243,7 +215,7 @@ function createWindow(): BrowserWindow {
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
webPreferences: {
|
||||
preload: path.join(import.meta.dirname, "preload.cjs"),
|
||||
preload: path.join(__dirname, "preload.js"),
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: true,
|
||||
@@ -257,9 +229,7 @@ function createWindow(): BrowserWindow {
|
||||
|
||||
if (isDevelopment) {
|
||||
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
|
||||
if (!PERF_AUTOMATION_ENABLED) {
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
}
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
} else {
|
||||
if (!fs.existsSync(WEB_ENTRY)) {
|
||||
throw new Error(`Web bundle missing at ${WEB_ENTRY}`);
|
||||
@@ -285,9 +255,6 @@ async function bootstrap(): Promise<void> {
|
||||
registerIpcHandlers();
|
||||
startBackend();
|
||||
mainWindow = createWindow();
|
||||
if (mainWindow && PERF_AUTOMATION_ENABLED) {
|
||||
void runPerfAutomationIfEnabled(mainWindow);
|
||||
}
|
||||
}
|
||||
|
||||
app.on("before-quit", () => {
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
import { defineConfig } from "tsdown";
|
||||
|
||||
const shared = {
|
||||
format: "cjs" as const,
|
||||
outDir: "dist-electron",
|
||||
sourcemap: true,
|
||||
outExtensions: () => ({ js: ".js" }),
|
||||
};
|
||||
|
||||
export default defineConfig([
|
||||
{
|
||||
outDir: "dist-electron",
|
||||
sourcemap: true,
|
||||
...shared,
|
||||
entry: ["src/main.ts"],
|
||||
clean: true,
|
||||
noExternal: ["@t3tools/contracts"],
|
||||
format: "esm",
|
||||
},
|
||||
{
|
||||
outDir: "dist-electron",
|
||||
sourcemap: true,
|
||||
...shared,
|
||||
entry: ["src/preload.ts"],
|
||||
clean: true,
|
||||
noExternal: ["@t3tools/contracts"],
|
||||
format: "cjs",
|
||||
},
|
||||
]);
|
||||
@@ -17,12 +17,12 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/node": "^22.10.2",
|
||||
"@types/ws": "^8.5.13",
|
||||
|
||||
@@ -4,9 +4,11 @@
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const webDist = path.resolve(import.meta.dirname, "../../web/dist");
|
||||
const target = path.resolve(import.meta.dirname, "../dist/client");
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webDist = path.resolve(__dirname, "../../web/dist");
|
||||
const target = path.resolve(__dirname, "../dist/client");
|
||||
|
||||
if (!fs.existsSync(webDist)) {
|
||||
console.log(
|
||||
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
declare module "bun:sqlite" {
|
||||
export class Database {
|
||||
constructor(filename?: string);
|
||||
exec(sql: string): void;
|
||||
run(sql: string, ...params: unknown[]): unknown;
|
||||
query(sql: string): {
|
||||
get(...params: unknown[]): unknown;
|
||||
};
|
||||
close(): void;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ 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";
|
||||
@@ -71,9 +72,11 @@ 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(import.meta.dirname, "client");
|
||||
const bundledClient = path.resolve(__dirname, "client");
|
||||
try {
|
||||
const stat = fs.statSync(path.join(bundledClient, "index.html"));
|
||||
if (stat.isFile()) return bundledClient;
|
||||
@@ -82,7 +85,7 @@ function resolveStaticDir(): string | undefined {
|
||||
}
|
||||
|
||||
// Monorepo layout: apps/server/dist/index.js → apps/web/dist/
|
||||
const monorepoClient = path.resolve(import.meta.dirname, "../../web/dist");
|
||||
const monorepoClient = path.resolve(__dirname, "../../web/dist");
|
||||
try {
|
||||
const stat = fs.statSync(path.join(monorepoClient, "index.html"));
|
||||
if (stat.isFile()) return monorepoClient;
|
||||
@@ -115,6 +118,7 @@ async function main() {
|
||||
port,
|
||||
host: mode === "desktop" ? "127.0.0.1" : undefined,
|
||||
cwd,
|
||||
stateDir,
|
||||
staticDir,
|
||||
devUrl,
|
||||
projectRegistry,
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { RendererStateStore } from "./rendererStateStore";
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
}
|
||||
|
||||
describe("RendererStateStore", () => {
|
||||
it("returns null when no renderer state has been saved", async () => {
|
||||
const stateDir = makeTempDir("t3code-renderer-state-empty-");
|
||||
const store = new RendererStateStore(stateDir);
|
||||
|
||||
await expect(store.get()).resolves.toBeNull();
|
||||
|
||||
await store.close();
|
||||
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("persists and reloads renderer state from sqlite", async () => {
|
||||
const stateDir = makeTempDir("t3code-renderer-state-roundtrip-");
|
||||
const firstStore = new RendererStateStore(stateDir);
|
||||
const payload =
|
||||
'{"version":8,"projects":[],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}';
|
||||
|
||||
await firstStore.set({ stateJson: payload });
|
||||
const firstRead = await firstStore.get();
|
||||
expect(firstRead).toMatchObject({
|
||||
stateJson: payload,
|
||||
updatedAt: expect.any(String),
|
||||
});
|
||||
await firstStore.close();
|
||||
|
||||
const secondStore = new RendererStateStore(stateDir);
|
||||
const secondRead = await secondStore.get();
|
||||
expect(secondRead).toMatchObject({
|
||||
stateJson: payload,
|
||||
updatedAt: expect.any(String),
|
||||
});
|
||||
await secondStore.close();
|
||||
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,174 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
type RendererStateSetInput,
|
||||
type RendererStateSnapshot,
|
||||
rendererStateSetInputSchema,
|
||||
rendererStateSnapshotSchema,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
interface RowShape {
|
||||
stateJson: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
interface SqliteAdapter {
|
||||
getState(): RowShape | null;
|
||||
setState(stateJson: string, updatedAt: string): void;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
interface BunSqliteDatabase {
|
||||
exec(sql: string): void;
|
||||
run(sql: string, ...params: unknown[]): unknown;
|
||||
query(sql: string): {
|
||||
get(...params: unknown[]): unknown;
|
||||
};
|
||||
close(): void;
|
||||
}
|
||||
|
||||
interface BunSqliteModule {
|
||||
Database: new (filename?: string) => BunSqliteDatabase;
|
||||
}
|
||||
|
||||
function defaultStateDir(): string {
|
||||
return path.join(os.homedir(), ".t3", "userdata");
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
function parseRowShape(row: unknown): RowShape | null {
|
||||
if (!isObject(row)) return null;
|
||||
const stateJson = row.stateJson;
|
||||
const updatedAt = row.updatedAt;
|
||||
if (typeof stateJson !== "string" || typeof updatedAt !== "string") return null;
|
||||
return { stateJson, updatedAt };
|
||||
}
|
||||
|
||||
async function createNodeSqliteAdapter(dbPath: string): Promise<SqliteAdapter> {
|
||||
const module = await import("node:sqlite");
|
||||
const db = new module.DatabaseSync(dbPath);
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS renderer_state (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
state_json TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
)
|
||||
`);
|
||||
const selectStatement = db.prepare(`
|
||||
SELECT state_json AS stateJson, updated_at AS updatedAt
|
||||
FROM renderer_state
|
||||
WHERE id = 1
|
||||
`);
|
||||
const upsertStatement = db.prepare(`
|
||||
INSERT INTO renderer_state (id, state_json, updated_at)
|
||||
VALUES (1, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
state_json = excluded.state_json,
|
||||
updated_at = excluded.updated_at
|
||||
`);
|
||||
|
||||
return {
|
||||
getState() {
|
||||
return parseRowShape(selectStatement.get());
|
||||
},
|
||||
setState(stateJson: string, updatedAt: string) {
|
||||
upsertStatement.run(stateJson, updatedAt);
|
||||
},
|
||||
close() {
|
||||
db.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function createBunSqliteAdapter(dbPath: string): Promise<SqliteAdapter> {
|
||||
const loadBunSqlite = new Function(
|
||||
"return import('bun:sqlite')",
|
||||
) as () => Promise<BunSqliteModule>;
|
||||
const module = await loadBunSqlite();
|
||||
const db = new module.Database(dbPath);
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS renderer_state (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
state_json TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
)
|
||||
`);
|
||||
const selectQuery = db.query(`
|
||||
SELECT state_json AS stateJson, updated_at AS updatedAt
|
||||
FROM renderer_state
|
||||
WHERE id = 1
|
||||
`);
|
||||
const upsertSql = `
|
||||
INSERT INTO renderer_state (id, state_json, updated_at)
|
||||
VALUES (1, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
state_json = excluded.state_json,
|
||||
updated_at = excluded.updated_at
|
||||
`;
|
||||
|
||||
return {
|
||||
getState() {
|
||||
return parseRowShape(selectQuery.get());
|
||||
},
|
||||
setState(stateJson: string, updatedAt: string) {
|
||||
db.run(upsertSql, stateJson, updatedAt);
|
||||
},
|
||||
close() {
|
||||
db.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function createSqliteAdapter(dbPath: string): Promise<SqliteAdapter> {
|
||||
try {
|
||||
return await createNodeSqliteAdapter(dbPath);
|
||||
} catch {
|
||||
return createBunSqliteAdapter(dbPath);
|
||||
}
|
||||
}
|
||||
|
||||
export class RendererStateStore {
|
||||
private readonly stateDir: string;
|
||||
private readonly dbPath: string;
|
||||
private adapterPromise: Promise<SqliteAdapter> | null = null;
|
||||
|
||||
constructor(stateDir: string = defaultStateDir()) {
|
||||
this.stateDir = stateDir;
|
||||
this.dbPath = path.join(this.stateDir, "renderer-state.sqlite");
|
||||
fs.mkdirSync(this.stateDir, { recursive: true });
|
||||
}
|
||||
|
||||
async get(): Promise<RendererStateSnapshot | null> {
|
||||
const adapter = await this.getAdapter();
|
||||
const row = adapter.getState();
|
||||
if (!row) return null;
|
||||
const parsed = rendererStateSnapshotSchema.safeParse(row);
|
||||
if (!parsed.success) return null;
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
async set(raw: RendererStateSetInput): Promise<void> {
|
||||
const input = rendererStateSetInputSchema.parse(raw);
|
||||
const adapter = await this.getAdapter();
|
||||
adapter.setState(input.stateJson, new Date().toISOString());
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (!this.adapterPromise) return;
|
||||
const adapter = await this.adapterPromise;
|
||||
adapter.close();
|
||||
this.adapterPromise = null;
|
||||
}
|
||||
|
||||
private async getAdapter(): Promise<SqliteAdapter> {
|
||||
if (!this.adapterPromise) {
|
||||
this.adapterPromise = createSqliteAdapter(this.dbPath);
|
||||
}
|
||||
return this.adapterPromise;
|
||||
}
|
||||
}
|
||||
@@ -249,6 +249,7 @@ describe("WebSocket Server", () => {
|
||||
return createServer({
|
||||
port: 0,
|
||||
cwd: options.cwd ?? "/test/project",
|
||||
stateDir,
|
||||
...(options.devUrl ? { devUrl: options.devUrl } : {}),
|
||||
...(options.authToken ? { authToken: options.authToken } : {}),
|
||||
projectRegistry: new ProjectRegistry(stateDir),
|
||||
@@ -342,6 +343,71 @@ describe("WebSocket Server", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("reads and writes renderer state over websocket", async () => {
|
||||
const stateDir = makeTempDir("t3code-ws-renderer-state-");
|
||||
server = createTestServer({ cwd: "/my/workspace", stateDir });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const empty = await sendRequest(ws, WS_METHODS.serverGetRendererState);
|
||||
expect(empty.error).toBeUndefined();
|
||||
expect(empty.result).toBeNull();
|
||||
|
||||
const setResponse = await sendRequest(ws, WS_METHODS.serverSetRendererState, {
|
||||
stateJson: '{"version":8,"projects":[],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}',
|
||||
});
|
||||
expect(setResponse.error).toBeUndefined();
|
||||
|
||||
const loaded = await sendRequest(ws, WS_METHODS.serverGetRendererState);
|
||||
expect(loaded.error).toBeUndefined();
|
||||
expect(loaded.result).toMatchObject({
|
||||
stateJson:
|
||||
'{"version":8,"projects":[],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}',
|
||||
updatedAt: expect.any(String),
|
||||
});
|
||||
});
|
||||
|
||||
it("persists renderer state across server restarts", async () => {
|
||||
const stateDir = makeTempDir("t3code-ws-renderer-state-restart-");
|
||||
server = createTestServer({ cwd: "/workspace", stateDir });
|
||||
await server.start();
|
||||
const firstAddr = server.httpServer.address();
|
||||
const firstPort = typeof firstAddr === "object" && firstAddr !== null ? firstAddr.port : 0;
|
||||
|
||||
const firstWs = await connectWs(firstPort);
|
||||
connections.push(firstWs);
|
||||
await waitForMessage(firstWs);
|
||||
const setResponse = await sendRequest(firstWs, WS_METHODS.serverSetRendererState, {
|
||||
stateJson:
|
||||
'{"version":8,"projects":[{"id":"project-1","name":"project","cwd":"/workspace","model":"gpt-5.3-codex","expanded":true}],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}',
|
||||
});
|
||||
expect(setResponse.error).toBeUndefined();
|
||||
|
||||
await server.stop();
|
||||
server = createTestServer({ cwd: "/workspace", stateDir });
|
||||
await server.start();
|
||||
const secondAddr = server.httpServer.address();
|
||||
const secondPort =
|
||||
typeof secondAddr === "object" && secondAddr !== null ? secondAddr.port : 0;
|
||||
|
||||
const secondWs = await connectWs(secondPort);
|
||||
connections.push(secondWs);
|
||||
await waitForMessage(secondWs);
|
||||
|
||||
const loaded = await sendRequest(secondWs, WS_METHODS.serverGetRendererState);
|
||||
expect(loaded.error).toBeUndefined();
|
||||
expect(loaded.result).toMatchObject({
|
||||
stateJson:
|
||||
'{"version":8,"projects":[{"id":"project-1","name":"project","cwd":"/workspace","model":"gpt-5.3-codex","expanded":true}],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}',
|
||||
updatedAt: expect.any(String),
|
||||
});
|
||||
});
|
||||
|
||||
it("reads keybindings from ~/.t3/keybindings.json", async () => {
|
||||
const fakeHome = makeTempDir("t3code-home-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
} from "./git";
|
||||
import { TerminalManager } from "./terminalManager";
|
||||
import { loadResolvedKeybindingsConfig } from "./keybindings";
|
||||
import { RendererStateStore } from "./rendererStateStore";
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
@@ -52,12 +53,14 @@ export interface ServerOptions {
|
||||
port: number;
|
||||
host?: string | undefined;
|
||||
cwd: string;
|
||||
stateDir?: string | undefined;
|
||||
staticDir?: string | undefined;
|
||||
devUrl?: string | undefined;
|
||||
logWebSocketEvents?: boolean | undefined;
|
||||
projectRegistry?: ProjectRegistry | undefined;
|
||||
gitManager?: GitManager | undefined;
|
||||
terminalManager?: TerminalManager | undefined;
|
||||
rendererStateStore?: RendererStateStore | undefined;
|
||||
authToken?: string | undefined;
|
||||
}
|
||||
|
||||
@@ -74,18 +77,21 @@ export function createServer(options: ServerOptions) {
|
||||
port,
|
||||
host,
|
||||
cwd,
|
||||
stateDir,
|
||||
staticDir,
|
||||
devUrl,
|
||||
logWebSocketEvents: explicitLogWsEvents,
|
||||
projectRegistry: providedRegistry,
|
||||
gitManager: providedGitManager,
|
||||
terminalManager: providedTerminalManager,
|
||||
rendererStateStore: providedRendererStateStore,
|
||||
authToken,
|
||||
} = options;
|
||||
const providerManager = new ProviderManager();
|
||||
const terminalManager = providedTerminalManager ?? new TerminalManager();
|
||||
const projectRegistry =
|
||||
providedRegistry ?? new ProjectRegistry(path.join(os.homedir(), ".t3", "userdata"));
|
||||
const resolvedStateDir = stateDir ?? path.join(os.homedir(), ".t3", "userdata");
|
||||
const projectRegistry = providedRegistry ?? new ProjectRegistry(resolvedStateDir);
|
||||
const rendererStateStore = providedRendererStateStore ?? new RendererStateStore(resolvedStateDir);
|
||||
const gitManager = providedGitManager ?? new GitManager();
|
||||
const clients = new Set<WebSocket>();
|
||||
const logger = createLogger("ws");
|
||||
@@ -417,6 +423,13 @@ export function createServer(options: ServerOptions) {
|
||||
keybindings: keybindingsConfig,
|
||||
};
|
||||
|
||||
case WS_METHODS.serverGetRendererState:
|
||||
return rendererStateStore.get();
|
||||
|
||||
case WS_METHODS.serverSetRendererState:
|
||||
await rendererStateStore.set(request.params as never);
|
||||
return undefined;
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown method: ${request.method}`);
|
||||
}
|
||||
@@ -446,6 +459,7 @@ export function createServer(options: ServerOptions) {
|
||||
providerManager.stopAll();
|
||||
providerManager.dispose();
|
||||
terminalManager.dispose();
|
||||
await rendererStateStore.close();
|
||||
|
||||
for (const client of clients) {
|
||||
client.close();
|
||||
|
||||
@@ -6,6 +6,7 @@ export default defineConfig({
|
||||
outDir: "dist",
|
||||
sourcemap: true,
|
||||
clean: true,
|
||||
noExternal: ["@t3tools/contracts", "zod"],
|
||||
inlineOnly: false,
|
||||
banner: {
|
||||
js: "#!/usr/bin/env node\n",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"@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",
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
|
||||
const branches: GitBranch[] = [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
isDefault: true,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "feature/demo",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
describe("deriveSyncedLocalBranch", () => {
|
||||
it("syncs to git current branch in local mode", () => {
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: "thread-1",
|
||||
activeWorktreePath: null,
|
||||
envMode: "local",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBe("main");
|
||||
});
|
||||
|
||||
it("does not sync when creating a new worktree", () => {
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: "thread-1",
|
||||
activeWorktreePath: null,
|
||||
envMode: "worktree",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("does not sync when thread already targets a worktree path", () => {
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: "thread-1",
|
||||
activeWorktreePath: "/tmp/repo/worktrees/feature-demo",
|
||||
envMode: "local",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
|
||||
interface DeriveSyncedLocalBranchInput {
|
||||
activeThreadId: string | undefined;
|
||||
activeWorktreePath: string | null;
|
||||
envMode: "local" | "worktree";
|
||||
activeThreadBranch: string | null;
|
||||
queryBranches: GitBranch[] | undefined;
|
||||
}
|
||||
|
||||
export function deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
}: DeriveSyncedLocalBranchInput): string | null {
|
||||
if (!activeThreadId || activeWorktreePath || envMode !== "local") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const currentBranch = queryBranches?.find((branch) => branch.current);
|
||||
if (!currentBranch || currentBranch.name === activeThreadBranch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return currentBranch.name;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
gitCreateBranchAndCheckoutMutationOptions,
|
||||
} from "../lib/gitReactQuery";
|
||||
import { useStore } from "../store";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Combobox,
|
||||
@@ -86,17 +87,22 @@ export default function BranchToolbar({
|
||||
// Keep thread branch synced to git current branch for local threads.
|
||||
const queryBranches = branchesQuery.data?.branches;
|
||||
useEffect(() => {
|
||||
if (!activeThreadId || activeWorktreePath) return;
|
||||
const current = queryBranches?.find((branch) => branch.current);
|
||||
if (!current) return;
|
||||
if (current.name === activeThreadBranch) return;
|
||||
const syncedBranch = deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
});
|
||||
if (!activeThreadId || !syncedBranch) return;
|
||||
|
||||
dispatch({
|
||||
type: "SET_THREAD_BRANCH",
|
||||
threadId: activeThreadId,
|
||||
branch: current.name,
|
||||
branch: syncedBranch,
|
||||
worktreePath: null,
|
||||
});
|
||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, dispatch]);
|
||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isBranchMenuOpen) return;
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
type ClipboardEvent,
|
||||
type DragEvent,
|
||||
type FormEvent,
|
||||
Fragment,
|
||||
type KeyboardEvent,
|
||||
memo,
|
||||
type RefObject,
|
||||
@@ -25,7 +26,6 @@ import {
|
||||
useState,
|
||||
} from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { type VirtualItem, useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
|
||||
import { serverConfigQueryOptions } from "~/lib/serverReactQuery";
|
||||
|
||||
@@ -159,6 +159,7 @@ export default function ChatView() {
|
||||
const [nowTick, setNowTick] = useState(() => Date.now());
|
||||
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
|
||||
const messagesScrollRef = useRef<HTMLDivElement>(null);
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const shouldAutoScrollRef = useRef(true);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
|
||||
@@ -822,41 +823,48 @@ export default function ChatView() {
|
||||
}
|
||||
|
||||
setThreadError(activeThread.id, null);
|
||||
const messageAttachments: ChatImageAttachment[] = composerImagesSnapshot.map((image) => ({
|
||||
type: "image",
|
||||
id: image.id,
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
sizeBytes: image.sizeBytes,
|
||||
previewUrl: image.previewUrl,
|
||||
}));
|
||||
dispatch({
|
||||
type: "PUSH_USER_MESSAGE",
|
||||
threadId: activeThread.id,
|
||||
id: crypto.randomUUID(),
|
||||
text: trimmed,
|
||||
...(messageAttachments.length > 0 ? { attachments: messageAttachments } : {}),
|
||||
});
|
||||
const previousMessages = activeThread.messages;
|
||||
setPrompt("");
|
||||
setComposerImages([]);
|
||||
|
||||
const sessionInfo = await ensureSession(sessionCwd);
|
||||
if (!sessionInfo) return;
|
||||
|
||||
setIsSending(true);
|
||||
try {
|
||||
const turnAttachments = await Promise.all(
|
||||
composerImagesSnapshot.map(
|
||||
async (image): Promise<ProviderSendTurnAttachmentInput> => ({
|
||||
const preparedImages = await Promise.all(
|
||||
composerImagesSnapshot.map(async (image) => {
|
||||
const attachment: ProviderSendTurnAttachmentInput = {
|
||||
type: "image",
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
sizeBytes: image.sizeBytes,
|
||||
dataUrl: await readFileAsDataUrl(image.file),
|
||||
}),
|
||||
),
|
||||
};
|
||||
return { image, attachment };
|
||||
}),
|
||||
);
|
||||
const turnAttachments = preparedImages.map(({ attachment }) => attachment);
|
||||
const messageAttachments: ChatImageAttachment[] = preparedImages.map(
|
||||
({ image, attachment }) => ({
|
||||
type: "image",
|
||||
id: image.id,
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
sizeBytes: image.sizeBytes,
|
||||
previewUrl: attachment.dataUrl,
|
||||
}),
|
||||
);
|
||||
dispatch({
|
||||
type: "PUSH_USER_MESSAGE",
|
||||
threadId: activeThread.id,
|
||||
id: crypto.randomUUID(),
|
||||
text: trimmed,
|
||||
...(messageAttachments.length > 0 ? { attachments: messageAttachments } : {}),
|
||||
});
|
||||
setPrompt("");
|
||||
setComposerImages((existing) => {
|
||||
revokePreviewUrls(existing);
|
||||
return [];
|
||||
});
|
||||
|
||||
const sessionInfo = await ensureSession(sessionCwd);
|
||||
if (!sessionInfo) return;
|
||||
|
||||
const shouldBootstrap =
|
||||
previousMessages.length > 0 &&
|
||||
(sessionInfo.continuityState === "new" || sessionInfo.continuityState === "fallback_new");
|
||||
@@ -1011,16 +1019,12 @@ export default function ChatView() {
|
||||
{/* Messages */}
|
||||
<div
|
||||
ref={messagesScrollRef}
|
||||
data-perf-messages-scroll
|
||||
data-perf-active-thread-id={activeThread.id}
|
||||
data-perf-message-count={activeThread.messages.length}
|
||||
className="min-h-0 flex-1 overflow-y-auto px-5 py-4"
|
||||
onScroll={onMessagesScroll}
|
||||
>
|
||||
<MessagesTimeline
|
||||
hasMessages={activeThread.messages.length > 0}
|
||||
isWorking={isWorking}
|
||||
scrollContainerRef={messagesScrollRef}
|
||||
timelineEntries={timelineEntries}
|
||||
completionDividerBeforeEntryId={completionDividerBeforeEntryId}
|
||||
completionSummary={completionSummary}
|
||||
@@ -1029,6 +1033,7 @@ export default function ChatView() {
|
||||
expandedWorkGroups={expandedWorkGroups}
|
||||
onToggleWorkGroup={onToggleWorkGroup}
|
||||
onImageExpand={onExpandTimelineImage}
|
||||
messagesEndRef={messagesEndRef}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1082,7 +1087,6 @@ export default function ChatView() {
|
||||
)}
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
data-perf-composer-input
|
||||
className="w-full resize-none bg-transparent text-[14px] leading-relaxed text-foreground placeholder:text-muted-foreground/35 focus:outline-none"
|
||||
rows={2}
|
||||
value={prompt}
|
||||
@@ -1119,7 +1123,6 @@ export default function ChatView() {
|
||||
className="text-muted-foreground/70 hover:text-foreground/80"
|
||||
size="sm"
|
||||
type="button"
|
||||
data-perf-runtime-toggle
|
||||
disabled={isSwitchingRuntimeMode}
|
||||
onClick={() =>
|
||||
void handleRuntimeModeChange(
|
||||
@@ -1318,7 +1321,6 @@ const ChatHeader = memo(function ChatHeader({
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
data-perf-diff-toggle
|
||||
className={cn(
|
||||
"text-muted-foreground/70 hover:text-foreground/80",
|
||||
diffOpen && "bg-accent text-accent-foreground",
|
||||
@@ -1421,7 +1423,6 @@ const PendingApprovalsPanel = memo(function PendingApprovalsPanel({
|
||||
interface MessagesTimelineProps {
|
||||
hasMessages: boolean;
|
||||
isWorking: boolean;
|
||||
scrollContainerRef: RefObject<HTMLDivElement | null>;
|
||||
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
|
||||
completionDividerBeforeEntryId: string | null;
|
||||
completionSummary: string | null;
|
||||
@@ -1430,34 +1431,12 @@ interface MessagesTimelineProps {
|
||||
expandedWorkGroups: Record<string, boolean>;
|
||||
onToggleWorkGroup: (groupId: string) => void;
|
||||
onImageExpand: (image: ExpandedImagePreview) => void;
|
||||
messagesEndRef: RefObject<HTMLDivElement | null>;
|
||||
}
|
||||
|
||||
type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
|
||||
type TimelineMessage = Extract<TimelineEntry, { kind: "message" }>["message"];
|
||||
|
||||
type TimelineRow =
|
||||
| {
|
||||
kind: "work";
|
||||
id: string;
|
||||
groupedEntries: {
|
||||
id: string;
|
||||
tone: "thinking" | "tool" | "info" | "error";
|
||||
label: string;
|
||||
detail?: string | null;
|
||||
}[];
|
||||
}
|
||||
| {
|
||||
kind: "message";
|
||||
id: string;
|
||||
message: TimelineMessage;
|
||||
showCompletionDivider: boolean;
|
||||
}
|
||||
| { kind: "working"; id: string };
|
||||
|
||||
const MessagesTimeline = memo(function MessagesTimeline({
|
||||
hasMessages,
|
||||
isWorking,
|
||||
scrollContainerRef,
|
||||
timelineEntries,
|
||||
completionDividerBeforeEntryId,
|
||||
completionSummary,
|
||||
@@ -1466,67 +1445,8 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
expandedWorkGroups,
|
||||
onToggleWorkGroup,
|
||||
onImageExpand,
|
||||
messagesEndRef,
|
||||
}: MessagesTimelineProps) {
|
||||
const rows = useMemo<TimelineRow[]>(() => {
|
||||
const nextRows: TimelineRow[] = [];
|
||||
|
||||
for (let index = 0; index < timelineEntries.length; index += 1) {
|
||||
const timelineEntry = timelineEntries[index];
|
||||
if (!timelineEntry) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (timelineEntry.kind === "work") {
|
||||
const groupedEntries = [timelineEntry.entry];
|
||||
let cursor = index + 1;
|
||||
while (cursor < timelineEntries.length) {
|
||||
const nextEntry = timelineEntries[cursor];
|
||||
if (!nextEntry || nextEntry.kind !== "work") break;
|
||||
groupedEntries.push(nextEntry.entry);
|
||||
cursor += 1;
|
||||
}
|
||||
nextRows.push({
|
||||
kind: "work",
|
||||
id: timelineEntry.id,
|
||||
groupedEntries,
|
||||
});
|
||||
index = cursor - 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
nextRows.push({
|
||||
kind: "message",
|
||||
id: timelineEntry.id,
|
||||
message: timelineEntry.message,
|
||||
showCompletionDivider:
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
completionDividerBeforeEntryId === timelineEntry.id,
|
||||
});
|
||||
}
|
||||
|
||||
if (isWorking) {
|
||||
nextRows.push({ kind: "working", id: "working-indicator-row" });
|
||||
}
|
||||
|
||||
return nextRows;
|
||||
}, [timelineEntries, completionDividerBeforeEntryId, isWorking]);
|
||||
|
||||
const rowVirtualizer = useVirtualizer({
|
||||
count: rows.length,
|
||||
getScrollElement: () => scrollContainerRef.current,
|
||||
estimateSize: (index: number) => {
|
||||
const row = rows[index];
|
||||
if (!row) return 96;
|
||||
if (row.kind === "work") return 112;
|
||||
if (row.kind === "working") return 40;
|
||||
return row.message.role === "assistant" ? 180 : 150;
|
||||
},
|
||||
measureElement: (element: HTMLElement) => element.getBoundingClientRect().height,
|
||||
overscan: 8,
|
||||
});
|
||||
|
||||
const virtualRows = rowVirtualizer.getVirtualItems();
|
||||
|
||||
if (!hasMessages && !isWorking) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
@@ -1536,177 +1456,181 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative mx-auto max-w-3xl" style={{ height: `${rowVirtualizer.getTotalSize()}px` }}>
|
||||
{virtualRows.map((virtualRow: VirtualItem) => {
|
||||
const row = rows[virtualRow.index];
|
||||
if (!row) return null;
|
||||
<div className="mx-auto max-w-3xl space-y-4">
|
||||
{timelineEntries.map((timelineEntry, index) => {
|
||||
if (timelineEntry.kind === "work" && timelineEntries[index - 1]?.kind === "work") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
key={row.id}
|
||||
data-index={virtualRow.index}
|
||||
ref={rowVirtualizer.measureElement}
|
||||
className="absolute left-0 top-0 w-full"
|
||||
style={{ transform: `translateY(${virtualRow.start}px)` }}
|
||||
>
|
||||
<div className="pb-4">
|
||||
{row.kind === "work" && (() => {
|
||||
const groupId = row.id;
|
||||
const groupedEntries = row.groupedEntries;
|
||||
const isExpanded = expandedWorkGroups[groupId] ?? false;
|
||||
const hasOverflow = groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
|
||||
const visibleEntries =
|
||||
hasOverflow && !isExpanded
|
||||
? groupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES)
|
||||
: groupedEntries;
|
||||
const hiddenCount = groupedEntries.length - visibleEntries.length;
|
||||
const onlyToolEntries = groupedEntries.every((entry) => entry.tone === "tool");
|
||||
const groupLabel = onlyToolEntries
|
||||
? groupedEntries.length === 1
|
||||
? "Tool call"
|
||||
: `Tool calls (${groupedEntries.length})`
|
||||
: groupedEntries.length === 1
|
||||
? "Work event"
|
||||
: `Work log (${groupedEntries.length})`;
|
||||
const showCompletionDivider =
|
||||
timelineEntry.kind === "message" &&
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
completionDividerBeforeEntryId === timelineEntry.id;
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-border/80 bg-card/45 px-3 py-2">
|
||||
<div className="mb-1.5 flex items-center justify-between gap-3">
|
||||
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
|
||||
{groupLabel}
|
||||
if (timelineEntry.kind === "work") {
|
||||
const groupedEntries = [timelineEntry.entry];
|
||||
let cursor = index + 1;
|
||||
while (cursor < timelineEntries.length) {
|
||||
const nextEntry = timelineEntries[cursor];
|
||||
if (!nextEntry || nextEntry.kind !== "work") break;
|
||||
groupedEntries.push(nextEntry.entry);
|
||||
cursor += 1;
|
||||
}
|
||||
|
||||
const groupId = timelineEntry.id;
|
||||
const isExpanded = expandedWorkGroups[groupId] ?? false;
|
||||
const hasOverflow = groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
|
||||
const visibleEntries =
|
||||
hasOverflow && !isExpanded
|
||||
? groupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES)
|
||||
: groupedEntries;
|
||||
const hiddenCount = groupedEntries.length - visibleEntries.length;
|
||||
const onlyToolEntries = groupedEntries.every((entry) => entry.tone === "tool");
|
||||
const groupLabel = onlyToolEntries
|
||||
? groupedEntries.length === 1
|
||||
? "Tool call"
|
||||
: `Tool calls (${groupedEntries.length})`
|
||||
: groupedEntries.length === 1
|
||||
? "Work event"
|
||||
: `Work log (${groupedEntries.length})`;
|
||||
|
||||
return (
|
||||
<Fragment key={timelineEntry.id}>
|
||||
<div className="rounded-lg border border-border/80 bg-card/45 px-3 py-2">
|
||||
<div className="mb-1.5 flex items-center justify-between gap-3">
|
||||
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
|
||||
{groupLabel}
|
||||
</p>
|
||||
{hasOverflow && (
|
||||
<button
|
||||
type="button"
|
||||
className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/55 transition-colors duration-150 hover:text-muted-foreground/80"
|
||||
onClick={() => onToggleWorkGroup(groupId)}
|
||||
>
|
||||
{isExpanded ? "Show less" : `Show ${hiddenCount} more`}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
{visibleEntries.map((workEntry) => (
|
||||
<div key={`work-row:${workEntry.id}`} className="flex items-start gap-2 py-0.5">
|
||||
<span className="mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
|
||||
<p
|
||||
className={`py-[2px] text-[11px] leading-relaxed ${workToneClass(workEntry.tone)}`}
|
||||
>
|
||||
{workEntry.detail ? (
|
||||
<>
|
||||
{workEntry.label}
|
||||
<span
|
||||
className="ml-1.5 inline-block max-w-[70ch] truncate align-bottom font-mono text-[11px] opacity-60"
|
||||
title={workEntry.detail}
|
||||
>
|
||||
{workEntry.detail}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
workEntry.label
|
||||
)}
|
||||
</p>
|
||||
{hasOverflow && (
|
||||
<button
|
||||
type="button"
|
||||
className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/55 transition-colors duration-150 hover:text-muted-foreground/80"
|
||||
onClick={() => onToggleWorkGroup(groupId)}
|
||||
>
|
||||
{isExpanded ? "Show less" : `Show ${hiddenCount} more`}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
{visibleEntries.map((workEntry) => (
|
||||
<div key={`work-row:${workEntry.id}`} className="flex items-start gap-2 py-0.5">
|
||||
<span className="mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
|
||||
<p
|
||||
className={`py-[2px] text-[11px] leading-relaxed ${workToneClass(workEntry.tone)}`}
|
||||
>
|
||||
{workEntry.detail ? (
|
||||
<>
|
||||
{workEntry.label}
|
||||
<span
|
||||
className="ml-1.5 inline-block max-w-[70ch] truncate align-bottom font-mono text-[11px] opacity-60"
|
||||
title={workEntry.detail}
|
||||
>
|
||||
{workEntry.detail}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
workEntry.label
|
||||
)}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
|
||||
if (timelineEntry.message.role === "user") {
|
||||
const userImages = timelineEntry.message.attachments ?? [];
|
||||
return (
|
||||
<Fragment key={timelineEntry.id}>
|
||||
<div className="flex justify-end">
|
||||
<div className="max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
|
||||
{userImages.length > 0 && (
|
||||
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
|
||||
{userImages.map((image) => (
|
||||
<div
|
||||
key={image.id}
|
||||
className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
|
||||
>
|
||||
{image.previewUrl ? (
|
||||
<img
|
||||
src={image.previewUrl}
|
||||
alt={image.name}
|
||||
className="h-full max-h-[220px] w-full cursor-zoom-in object-cover"
|
||||
onClick={() =>
|
||||
onImageExpand({ src: image.previewUrl!, name: image.name })
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
|
||||
{image.name}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
{row.kind === "message" &&
|
||||
row.message.role === "user" &&
|
||||
(() => {
|
||||
const userImages = row.message.attachments ?? [];
|
||||
return (
|
||||
<div className="flex justify-end">
|
||||
<div className="max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
|
||||
{userImages.length > 0 && (
|
||||
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
|
||||
{userImages.map((image: NonNullable<TimelineMessage["attachments"]>[number]) => (
|
||||
<div
|
||||
key={image.id}
|
||||
className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
|
||||
>
|
||||
{image.previewUrl ? (
|
||||
<img
|
||||
src={image.previewUrl}
|
||||
alt={image.name}
|
||||
className="h-full max-h-[220px] w-full cursor-zoom-in object-cover"
|
||||
onClick={() =>
|
||||
onImageExpand({ src: image.previewUrl!, name: image.name })
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
|
||||
{image.name}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{row.message.text && (
|
||||
<pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
|
||||
{row.message.text}
|
||||
</pre>
|
||||
)}
|
||||
<p className="mt-1.5 text-right text-[10px] text-muted-foreground/30">
|
||||
{formatTimestamp(row.message.createdAt)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
{row.kind === "message" &&
|
||||
row.message.role === "assistant" &&
|
||||
(() => {
|
||||
const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)");
|
||||
return (
|
||||
<>
|
||||
{row.showCompletionDivider && (
|
||||
<div className="my-3 flex items-center gap-3">
|
||||
<span className="h-px flex-1 bg-border" />
|
||||
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
|
||||
{completionSummary ? `Response • ${completionSummary}` : "Response"}
|
||||
</span>
|
||||
<span className="h-px flex-1 bg-border" />
|
||||
</div>
|
||||
)}
|
||||
<div className="px-1 py-0.5">
|
||||
<ChatMarkdown text={messageText} />
|
||||
<p className="mt-1.5 text-[10px] text-muted-foreground/30">
|
||||
{formatMessageMeta(
|
||||
row.message.createdAt,
|
||||
row.message.streaming
|
||||
? formatElapsed(row.message.createdAt, nowIso)
|
||||
: formatElapsed(
|
||||
row.message.createdAt,
|
||||
assistantCompletionByItemId.get(row.message.id),
|
||||
),
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
|
||||
{row.kind === "working" && (
|
||||
<div className="flex items-center gap-2 py-0.5 pl-1.5">
|
||||
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
|
||||
<div className="flex items-center pt-1">
|
||||
<span className="inline-flex items-center gap-[3px]">
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{timelineEntry.message.text && (
|
||||
<pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
|
||||
{timelineEntry.message.text}
|
||||
</pre>
|
||||
)}
|
||||
<p className="mt-1.5 text-right text-[10px] text-muted-foreground/30">
|
||||
{formatTimestamp(timelineEntry.message.createdAt)}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Fragment key={timelineEntry.id}>
|
||||
{showCompletionDivider && (
|
||||
<div className="my-3 flex items-center gap-3">
|
||||
<span className="h-px flex-1 bg-border" />
|
||||
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
|
||||
{completionSummary ? `Response • ${completionSummary}` : "Response"}
|
||||
</span>
|
||||
<span className="h-px flex-1 bg-border" />
|
||||
</div>
|
||||
)}
|
||||
<div className="px-1 py-0.5">
|
||||
<ChatMarkdown
|
||||
text={
|
||||
timelineEntry.message.text ||
|
||||
(timelineEntry.message.streaming ? "" : "(empty response)")
|
||||
}
|
||||
/>
|
||||
<p className="mt-1.5 text-[10px] text-muted-foreground/30">
|
||||
{formatMessageMeta(
|
||||
timelineEntry.message.createdAt,
|
||||
timelineEntry.message.streaming
|
||||
? formatElapsed(timelineEntry.message.createdAt, nowIso)
|
||||
: formatElapsed(
|
||||
timelineEntry.message.createdAt,
|
||||
assistantCompletionByItemId.get(timelineEntry.message.id),
|
||||
),
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
{isWorking && (
|
||||
<div className="flex items-center gap-2 py-0.5 pl-1.5">
|
||||
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
|
||||
<div className="flex items-center pt-1">
|
||||
<span className="inline-flex items-center gap-[3px]">
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -1721,12 +1645,12 @@ const ModelPicker = memo(function ModelPicker(props: {
|
||||
value={props.model}
|
||||
onValueChange={(value) => (value ? props.onModelChange(value) : undefined)}
|
||||
>
|
||||
<SelectTrigger size="sm" variant="ghost" data-perf-model-trigger>
|
||||
<SelectTrigger size="sm" variant="ghost">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectPopup alignItemWithTrigger={false}>
|
||||
{MODEL_OPTIONS.map(({ slug, name }) => (
|
||||
<SelectItem key={slug} value={slug} data-perf-model-option={slug}>
|
||||
<SelectItem key={slug} value={slug}>
|
||||
{name}
|
||||
</SelectItem>
|
||||
))}
|
||||
@@ -1744,12 +1668,12 @@ const ReasoningEffortPicker = memo(function ReasoningEffortPicker(props: {
|
||||
value={props.effort}
|
||||
onValueChange={(value) => (value ? props.onEffortChange(value) : undefined)}
|
||||
>
|
||||
<SelectTrigger variant="ghost" size="sm" data-perf-reasoning-trigger>
|
||||
<SelectTrigger variant="ghost" size="sm">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectPopup alignItemWithTrigger={false}>
|
||||
{REASONING_OPTIONS.map((effort) => (
|
||||
<SelectItem key={effort} value={effort} data-perf-reasoning-option={effort}>
|
||||
<SelectItem key={effort} value={effort}>
|
||||
{effort}
|
||||
{effort === DEFAULT_REASONING ? " (default)" : ""}
|
||||
</SelectItem>
|
||||
|
||||
@@ -505,7 +505,6 @@ 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"
|
||||
|
||||
@@ -257,10 +257,65 @@ describe("hydratePersistedState", () => {
|
||||
]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||
});
|
||||
|
||||
it("hydrates persisted image preview data urls", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 8,
|
||||
runtimeMode: "full-access",
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "t-1",
|
||||
codexThreadId: null,
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: true,
|
||||
terminalHeight: 360,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
messages: [
|
||||
{
|
||||
id: "m-1",
|
||||
role: "user",
|
||||
text: "Here",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "img-1",
|
||||
name: "diagram.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 4_096,
|
||||
previewUrl: "data:image/png;base64,AAAA",
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-1",
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated?.threads[0]?.messages[0]?.attachments?.[0]?.previewUrl).toBe(
|
||||
"data:image/png;base64,AAAA",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("toPersistedState", () => {
|
||||
it("writes v7 payload and strips non-persisted thread fields", () => {
|
||||
it("writes v8 payload and strips non-persisted thread fields", () => {
|
||||
const thread: Thread = {
|
||||
id: "t-1",
|
||||
codexThreadId: "thr_1",
|
||||
@@ -320,7 +375,7 @@ describe("toPersistedState", () => {
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
expect(persisted.version).toBe(7);
|
||||
expect(persisted.version).toBe(8);
|
||||
expect(persisted.runtimeMode).toBe("full-access");
|
||||
expect(persisted.threads[0]).toEqual({
|
||||
id: "t-1",
|
||||
@@ -367,4 +422,69 @@ describe("toPersistedState", () => {
|
||||
expect("error" in persistedThread).toBe(false);
|
||||
expect("session" in persistedThread).toBe(false);
|
||||
});
|
||||
|
||||
it("persists preview data urls for image attachments", () => {
|
||||
const thread: Thread = {
|
||||
id: "t-1",
|
||||
codexThreadId: null,
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
session: null,
|
||||
messages: [
|
||||
{
|
||||
id: "m-1",
|
||||
role: "user",
|
||||
text: "Image",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "img-1",
|
||||
name: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 1_024,
|
||||
previewUrl: "data:image/png;base64,AAAA",
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
events: [],
|
||||
error: null,
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
};
|
||||
|
||||
const persisted = toPersistedState({
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
},
|
||||
],
|
||||
threads: [thread],
|
||||
activeThreadId: "t-1",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
expect(persisted.threads[0]?.messages[0]?.attachments?.[0]).toMatchObject({
|
||||
type: "image",
|
||||
id: "img-1",
|
||||
previewUrl: "data:image/png;base64,AAAA",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -33,6 +33,7 @@ const persistedMessageSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
mimeType: z.string().min(1),
|
||||
sizeBytes: z.number().int().min(1),
|
||||
previewUrl: z.string().min(1).optional(),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
@@ -103,12 +104,18 @@ export const persistedStateV7Schema = persistedStateBodySchema.extend({
|
||||
version: z.literal(7).optional(),
|
||||
});
|
||||
|
||||
export const persistedStateV8Schema = persistedStateBodySchema.extend({
|
||||
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
|
||||
version: z.literal(8).optional(),
|
||||
});
|
||||
|
||||
export const persistedStateV5Schema = persistedStateBodySchema.extend({
|
||||
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
|
||||
version: z.literal(5).optional(),
|
||||
});
|
||||
|
||||
const persistedStateSchema = z.union([
|
||||
persistedStateV8Schema,
|
||||
persistedStateV7Schema,
|
||||
persistedStateV6Schema,
|
||||
persistedStateV5Schema,
|
||||
@@ -252,7 +259,14 @@ function hydrateThread(
|
||||
activeTerminalGroupId,
|
||||
session: null,
|
||||
messages: thread.messages.map((message) => {
|
||||
const hydratedAttachments = message.attachments?.map((attachment) => ({ ...attachment }));
|
||||
const hydratedAttachments = message.attachments?.map((attachment) => ({
|
||||
type: attachment.type,
|
||||
id: attachment.id,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
...(attachment.previewUrl ? { previewUrl: attachment.previewUrl } : {}),
|
||||
}));
|
||||
return {
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
@@ -312,9 +326,9 @@ export function hydratePersistedState(
|
||||
|
||||
export function toPersistedState(
|
||||
state: PersistedStoreSnapshot,
|
||||
): z.infer<typeof persistedStateV7Schema> {
|
||||
): z.infer<typeof persistedStateV8Schema> {
|
||||
return {
|
||||
version: 7,
|
||||
version: 8,
|
||||
projects: state.projects,
|
||||
threads: state.threads.map((thread) => ({
|
||||
id: thread.id,
|
||||
@@ -340,6 +354,9 @@ export function toPersistedState(
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
...(attachment.previewUrl && /^data:image\//i.test(attachment.previewUrl)
|
||||
? { previewUrl: attachment.previewUrl }
|
||||
: {}),
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
|
||||
+106
-19
@@ -5,13 +5,19 @@ import {
|
||||
createElement,
|
||||
useContext,
|
||||
useEffect,
|
||||
useRef,
|
||||
useReducer,
|
||||
useState,
|
||||
} from "react";
|
||||
|
||||
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
|
||||
import { resolveModelSlug } from "./model-logic";
|
||||
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
||||
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
|
||||
import {
|
||||
type PersistedStoreSnapshot,
|
||||
hydratePersistedState,
|
||||
toPersistedState,
|
||||
} from "./persistenceSchema";
|
||||
import { applyEventToMessages, asObject, asString, evolveSession, readNativeApi } from "./session-logic";
|
||||
import {
|
||||
type ChatAttachment,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
@@ -25,6 +31,7 @@ import {
|
||||
// ── Actions ──────────────────────────────────────────────────────────
|
||||
|
||||
type Action =
|
||||
| { type: "HYDRATE_PERSISTED_STATE"; snapshot: PersistedStoreSnapshot }
|
||||
| { type: "ADD_PROJECT"; project: Project }
|
||||
| { type: "SYNC_PROJECTS"; projects: Project[] }
|
||||
| { type: "TOGGLE_PROJECT"; projectId: string }
|
||||
@@ -75,8 +82,10 @@ export interface AppState {
|
||||
diffOpen: boolean;
|
||||
}
|
||||
|
||||
const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
|
||||
const LEGACY_PERSISTED_STATE_PRIMARY_KEY = "t3code:renderer-state:v8";
|
||||
const LEGACY_PERSISTED_STATE_KEYS = [
|
||||
LEGACY_PERSISTED_STATE_PRIMARY_KEY,
|
||||
"t3code:renderer-state:v7",
|
||||
"t3code:renderer-state:v6",
|
||||
"t3code:renderer-state:v5",
|
||||
"t3code:renderer-state:v4",
|
||||
@@ -97,35 +106,30 @@ const initialState: AppState = {
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
function readPersistedState(): AppState {
|
||||
if (typeof window === "undefined") return initialState;
|
||||
function readLegacyPersistedStateFromLocalStorage(): PersistedStoreSnapshot | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
|
||||
try {
|
||||
const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
|
||||
const rawCurrent = window.localStorage.getItem(LEGACY_PERSISTED_STATE_PRIMARY_KEY);
|
||||
const legacyValues = LEGACY_PERSISTED_STATE_KEYS.map((key) => window.localStorage.getItem(key));
|
||||
const rawLegacy = legacyValues.find((value) => value !== null) ?? null;
|
||||
const raw = rawCurrent ?? rawLegacy;
|
||||
if (!raw) return initialState;
|
||||
if (!raw) return null;
|
||||
const rawCodethingV1 = window.localStorage.getItem("codething:renderer-state:v1");
|
||||
const hydrated = hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
|
||||
if (!hydrated) return initialState;
|
||||
|
||||
return { ...hydrated, diffOpen: false };
|
||||
return hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
|
||||
} catch {
|
||||
return initialState;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function persistState(state: AppState): void {
|
||||
function clearLegacyPersistedStateFromLocalStorage(): void {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
try {
|
||||
window.localStorage.setItem(PERSISTED_STATE_KEY, JSON.stringify(toPersistedState(state)));
|
||||
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
|
||||
window.localStorage.removeItem(legacyKey);
|
||||
}
|
||||
} catch {
|
||||
// Ignore quota/storage errors to avoid breaking chat UX.
|
||||
// Ignore storage errors.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -409,6 +413,16 @@ function updateTurnFields(thread: Thread, event: ProviderEvent): Partial<Thread>
|
||||
|
||||
export function reducer(state: AppState, action: Action): AppState {
|
||||
switch (action.type) {
|
||||
case "HYDRATE_PERSISTED_STATE":
|
||||
return {
|
||||
...state,
|
||||
projects: action.snapshot.projects,
|
||||
threads: action.snapshot.threads,
|
||||
activeThreadId: action.snapshot.activeThreadId,
|
||||
runtimeMode: action.snapshot.runtimeMode,
|
||||
diffOpen: false,
|
||||
};
|
||||
|
||||
case "ADD_PROJECT":
|
||||
if (state.projects.some((project) => project.cwd === action.project.cwd)) {
|
||||
return state;
|
||||
@@ -842,11 +856,84 @@ const StoreContext = createContext<{
|
||||
}>({ state: initialState, dispatch: () => {} });
|
||||
|
||||
export function StoreProvider({ children }: { children: ReactNode }) {
|
||||
const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
|
||||
const [state, dispatch] = useReducer(reducer, initialState);
|
||||
const [persistenceReady, setPersistenceReady] = useState(false);
|
||||
const lastPersistedStateJsonRef = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
persistState(state);
|
||||
}, [state]);
|
||||
let disposed = false;
|
||||
const api = readNativeApi();
|
||||
if (!api) {
|
||||
setPersistenceReady(true);
|
||||
return;
|
||||
}
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const serverSnapshot = await api.server.getRendererState();
|
||||
if (disposed) return;
|
||||
|
||||
const hydratedFromServer = serverSnapshot
|
||||
? hydratePersistedState(serverSnapshot.stateJson, false)
|
||||
: null;
|
||||
if (hydratedFromServer) {
|
||||
lastPersistedStateJsonRef.current = serverSnapshot?.stateJson ?? null;
|
||||
dispatch({ type: "HYDRATE_PERSISTED_STATE", snapshot: hydratedFromServer });
|
||||
clearLegacyPersistedStateFromLocalStorage();
|
||||
return;
|
||||
}
|
||||
|
||||
const hydratedLegacy = readLegacyPersistedStateFromLocalStorage();
|
||||
if (!hydratedLegacy) return;
|
||||
const migratedStateJson = JSON.stringify(toPersistedState(hydratedLegacy));
|
||||
dispatch({ type: "HYDRATE_PERSISTED_STATE", snapshot: hydratedLegacy });
|
||||
try {
|
||||
await api.server.setRendererState({ stateJson: migratedStateJson });
|
||||
if (!disposed) {
|
||||
lastPersistedStateJsonRef.current = migratedStateJson;
|
||||
clearLegacyPersistedStateFromLocalStorage();
|
||||
}
|
||||
} catch {
|
||||
// Keep running with hydrated legacy state. Persist effect will retry.
|
||||
}
|
||||
} catch {
|
||||
if (disposed) return;
|
||||
const hydratedLegacy = readLegacyPersistedStateFromLocalStorage();
|
||||
if (hydratedLegacy) {
|
||||
dispatch({ type: "HYDRATE_PERSISTED_STATE", snapshot: hydratedLegacy });
|
||||
}
|
||||
} finally {
|
||||
if (!disposed) {
|
||||
setPersistenceReady(true);
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
};
|
||||
}, [dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!persistenceReady) return;
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
|
||||
const stateJson = JSON.stringify(toPersistedState(state));
|
||||
if (lastPersistedStateJsonRef.current === stateJson) return;
|
||||
const persistTimer = window.setTimeout(() => {
|
||||
void api.server
|
||||
.setRendererState({ stateJson })
|
||||
.then(() => {
|
||||
lastPersistedStateJsonRef.current = stateJson;
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, 150);
|
||||
|
||||
return () => {
|
||||
window.clearTimeout(persistTimer);
|
||||
};
|
||||
}, [persistenceReady, state]);
|
||||
|
||||
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
|
||||
}
|
||||
|
||||
@@ -141,6 +141,8 @@ export function createWsNativeApi(): NativeApi {
|
||||
},
|
||||
server: {
|
||||
getConfig: () => transport.request(WS_METHODS.serverGetConfig),
|
||||
getRendererState: () => transport.request(WS_METHODS.serverGetRendererState),
|
||||
setRendererState: (input) => transport.request(WS_METHODS.serverSetRendererState, input),
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -34,12 +34,12 @@
|
||||
"t3": "./dist/index.mjs",
|
||||
},
|
||||
"dependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/node": "^22.10.2",
|
||||
"@types/ws": "^8.5.13",
|
||||
@@ -54,7 +54,6 @@
|
||||
"@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",
|
||||
@@ -430,10 +429,6 @@
|
||||
|
||||
"@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
-3
@@ -18,10 +18,9 @@
|
||||
"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"
|
||||
"build:contracts": "turbo run build --filter=@t3tools/contracts",
|
||||
"clean": "rm -rf node_modules apps/*/node_modules packages/*/node_modules apps/*/dist apps/*/dist-electron packages/*/dist .turbo apps/*/.turbo packages/*/.turbo"
|
||||
},
|
||||
"devDependencies": {
|
||||
"oxfmt": "^0.28.0",
|
||||
|
||||
@@ -7,5 +7,6 @@ export * from "./model";
|
||||
export * from "./ws";
|
||||
export * from "./keybindings";
|
||||
export * from "./server";
|
||||
export * from "./rendererState";
|
||||
export * from "./project";
|
||||
export * from "./git";
|
||||
@@ -32,6 +32,7 @@ import type {
|
||||
ProjectRemoveInput,
|
||||
} from "./project";
|
||||
import type { ServerConfig } from "./server";
|
||||
import type { RendererStateSetInput, RendererStateSnapshot } from "./rendererState";
|
||||
import type {
|
||||
TerminalClearInput,
|
||||
TerminalCloseInput,
|
||||
@@ -116,5 +117,7 @@ export interface NativeApi {
|
||||
};
|
||||
server: {
|
||||
getConfig: () => Promise<ServerConfig>;
|
||||
getRendererState: () => Promise<RendererStateSnapshot | null>;
|
||||
setRendererState: (input: RendererStateSetInput) => Promise<void>;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { rendererStateSetInputSchema, rendererStateSnapshotSchema } from "./rendererState";
|
||||
|
||||
describe("rendererState contracts", () => {
|
||||
it("parses renderer state snapshot", () => {
|
||||
const parsed = rendererStateSnapshotSchema.parse({
|
||||
stateJson: '{"version":8,"projects":[],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}',
|
||||
updatedAt: "2026-02-18T10:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(parsed.updatedAt).toBe("2026-02-18T10:00:00.000Z");
|
||||
});
|
||||
|
||||
it("requires non-empty stateJson for set input", () => {
|
||||
expect(() => rendererStateSetInputSchema.parse({ stateJson: "" })).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const RENDERER_STATE_MAX_JSON_CHARS = 25_000_000;
|
||||
|
||||
export const rendererStateSnapshotSchema = z.object({
|
||||
stateJson: z.string().min(1).max(RENDERER_STATE_MAX_JSON_CHARS),
|
||||
updatedAt: z.string().datetime(),
|
||||
});
|
||||
|
||||
export const rendererStateSetInputSchema = z.object({
|
||||
stateJson: z.string().min(1).max(RENDERER_STATE_MAX_JSON_CHARS),
|
||||
});
|
||||
|
||||
export type RendererStateSnapshot = z.infer<typeof rendererStateSnapshotSchema>;
|
||||
export type RendererStateSetInput = z.input<typeof rendererStateSetInputSchema>;
|
||||
@@ -40,6 +40,8 @@ export const WS_METHODS = {
|
||||
|
||||
// Server meta
|
||||
serverGetConfig: "server.getConfig",
|
||||
serverGetRendererState: "server.getRendererState",
|
||||
serverSetRendererState: "server.setRendererState",
|
||||
} as const;
|
||||
|
||||
// ── Push Event Channels ──────────────────────────────────────────────
|
||||
|
||||
@@ -1,624 +0,0 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
function createMarkdownSummary({ tracePath, donePayload, summary, thresholds }) {
|
||||
const THREAD_COL_WIDTH = 8;
|
||||
const TITLE_COL_WIDTH = 15;
|
||||
const pad = (value, width) => String(value).padEnd(width, " ");
|
||||
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})`);
|
||||
}
|
||||
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);
|
||||
});
|
||||
+1
-7
@@ -5,19 +5,13 @@
|
||||
"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_PERF_AUTOMATION",
|
||||
"T3CODE_DESKTOP_PERF_TRACE_OUT",
|
||||
"T3CODE_DESKTOP_PERF_DONE_OUT",
|
||||
"T3CODE_DESKTOP_PERF_SEED_PATH",
|
||||
"T3CODE_ELECTRON_STARTUP_TIMEOUT_MS"
|
||||
"T3CODE_DESKTOP_WS_URL"
|
||||
],
|
||||
"tasks": {
|
||||
"build": {
|
||||
|
||||
Reference in new issue
Block a user