Add desktop perf seed data and update perf trace workflow

- add `apps/desktop/scripts/perf-seed.json` for seeded desktop perf automation runs
- update desktop/web perf automation and trace scripts to use the new seeded flow
- refresh workspace task/dependency config (`turbo.json`, `apps/web/package.json`, `bun.lock`) to support the perf tooling changes
This commit is contained in:
Julius Marminge committed 2026-02-16 09:13:14 -08:00
1 parent 257b52db10
commit ed2ef9634f
7 files changed
+3976 -197

No files matched your search

File diff suppressed because it is too large. Load diff
+141 -8
View File
@@ -6,6 +6,7 @@ import { BrowserWindow, contentTracing, type WebContents } from "electron";
const PERF_AUTOMATION_ENABLED = process.env.T3CODE_DESKTOP_PERF_AUTOMATION === "1";
const PERF_TRACE_OUT_PATH = process.env.T3CODE_DESKTOP_PERF_TRACE_OUT?.trim() ?? "";
const PERF_DONE_OUT_PATH = process.env.T3CODE_DESKTOP_PERF_DONE_OUT?.trim() ?? "";
const PERF_SEED_PATH = process.env.T3CODE_DESKTOP_PERF_SEED_PATH?.trim() ?? "";
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
@@ -126,6 +127,95 @@ interface PerfPersistedState {
}
const LARGE_THREAD_EXCHANGE_COUNT = 120;
const BENCHMARK_THREAD_COUNT = 2;
interface PerfThreadStat {
id: string;
messageCount: number;
}
interface ResolvedPerfSeed {
source: string;
resolvedPath: string | null;
state: unknown;
benchmarkThreadIds: string[];
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function collectThreadStats(state: unknown): PerfThreadStat[] {
if (!isRecord(state)) return [];
const threads = state.threads;
if (!Array.isArray(threads)) return [];
const stats: PerfThreadStat[] = [];
for (const thread of threads) {
if (!isRecord(thread)) continue;
const id = typeof thread.id === "string" ? thread.id : "";
if (id.length === 0) continue;
const messages = thread.messages;
const messageCount = Array.isArray(messages) ? messages.length : 0;
stats.push({ id, messageCount });
}
return stats;
}
function pickBenchmarkThreadIds(stats: PerfThreadStat[]): string[] {
return [...stats]
.sort((a, b) => b.messageCount - a.messageCount)
.slice(0, BENCHMARK_THREAD_COUNT)
.map((entry) => entry.id);
}
function resolvePerfSeed(): ResolvedPerfSeed {
if (PERF_SEED_PATH.length === 0) {
const generated = buildPerfSeedState();
const stats = collectThreadStats(generated);
return {
source: "generated",
resolvedPath: null,
state: generated,
benchmarkThreadIds: pickBenchmarkThreadIds(stats),
};
}
const resolvedPath = path.isAbsolute(PERF_SEED_PATH)
? PERF_SEED_PATH
: path.resolve(process.cwd(), PERF_SEED_PATH);
if (!fs.existsSync(resolvedPath)) {
throw new Error(`Perf seed file not found: ${resolvedPath}`);
}
let parsed: unknown;
try {
parsed = JSON.parse(fs.readFileSync(resolvedPath, "utf8"));
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed to parse perf seed JSON at ${resolvedPath}: ${message}`);
}
if (!isRecord(parsed)) {
throw new Error(`Perf seed must be a JSON object: ${resolvedPath}`);
}
if (!Array.isArray(parsed.projects)) {
throw new Error(`Perf seed is missing "projects" array: ${resolvedPath}`);
}
if (!Array.isArray(parsed.threads)) {
throw new Error(`Perf seed is missing "threads" array: ${resolvedPath}`);
}
const stats = collectThreadStats(parsed);
return {
source: "file",
resolvedPath,
state: parsed,
benchmarkThreadIds: pickBenchmarkThreadIds(stats),
};
}
function buildLargeThreadMessage(
projectName: string,
@@ -274,8 +364,7 @@ function buildPerfSeedState(): PerfPersistedState {
};
}
async function seedRendererState(window: BrowserWindow): Promise<void> {
const state = buildPerfSeedState();
async function seedRendererState(window: BrowserWindow, state: unknown): Promise<void> {
const script = `
(() => {
const key = "t3code:renderer-state:v7";
@@ -288,11 +377,13 @@ async function seedRendererState(window: BrowserWindow): Promise<void> {
async function runRendererPerfInteractions(
window: BrowserWindow,
benchmarkThreadIds: string[],
): Promise<{
threadClicks: number;
typedChars: number;
selectedModel: string | null;
largeThreadRenderStats: { threadId: string; messageCount: number; renderMs: number }[];
benchmarkThreadIds: string[];
}> {
const script = `
(async () => {
@@ -319,8 +410,20 @@ async function runRendererPerfInteractions(
return true;
};
const threadButtons = Array.from(document.querySelectorAll("[data-perf-thread-id]"));
must(threadButtons.length >= 4, "Expected seeded thread rows to be rendered.");
const getThreadButtons = () =>
Array.from(document.querySelectorAll("[data-perf-thread-id]")).filter(
(node) => node instanceof HTMLElement,
);
await waitFor(
() => getThreadButtons().length >= 1,
15_000,
"Expected seeded thread rows to be rendered.",
);
const threadButtons = getThreadButtons();
must(threadButtons.length >= 1, "Expected seeded thread rows to be rendered.");
const renderedThreadIds = threadButtons
.map((node) => node.getAttribute("data-perf-thread-id"))
.filter((value) => typeof value === "string" && value.length > 0);
const clickCount = Math.min(8, threadButtons.length);
for (let index = 0; index < clickCount; index += 1) {
@@ -360,8 +463,17 @@ async function runRendererPerfInteractions(
};
const largeThreadRenderStats = [];
const largeThreadIds = ["perf-project-1-thread-large", "perf-project-2-thread-large"];
for (const threadId of largeThreadIds) {
const preferredThreadIds = ${JSON.stringify(benchmarkThreadIds)}.filter(
(value) => typeof value === "string" && value.length > 0,
);
const benchmarkThreadIds = preferredThreadIds.filter((threadId) =>
renderedThreadIds.includes(threadId),
);
if (benchmarkThreadIds.length === 0) {
benchmarkThreadIds.push(...renderedThreadIds.slice(0, ${BENCHMARK_THREAD_COUNT}));
}
for (const threadId of benchmarkThreadIds) {
largeThreadRenderStats.push(await measureThreadRender(threadId));
}
@@ -443,6 +555,7 @@ async function runRendererPerfInteractions(
typedChars: inputText.length,
selectedModel,
largeThreadRenderStats,
benchmarkThreadIds,
};
})();
`;
@@ -494,14 +607,23 @@ export async function runDesktopPerfAutomation(window: BrowserWindow): Promise<v
let tracePath = PERF_TRACE_OUT_PATH;
let isTraceRecording = false;
const startedAt = Date.now();
let seed: ResolvedPerfSeed | null = null;
try {
seed = resolvePerfSeed();
const seedLabel =
seed.source === "file" ? `file (${seed.resolvedPath ?? "unknown"})` : seed.source;
const benchmarkThreadLabel =
seed.benchmarkThreadIds.length > 0 ? seed.benchmarkThreadIds.join(", ") : "none";
console.log(`[desktop-perf] seed source: ${seedLabel}`);
console.log(`[desktop-perf] benchmark thread ids: ${benchmarkThreadLabel}`);
console.log("[desktop-perf] waiting for initial load");
await waitForDidFinishLoad(window.webContents, {
timeoutMs: 60_000,
label: "initial load",
});
console.log("[desktop-perf] seeding renderer state");
await seedRendererState(window);
await seedRendererState(window, seed.state);
window.webContents.reload();
console.log("[desktop-perf] waiting for reload");
await waitForDidFinishLoad(window.webContents, {
@@ -515,7 +637,7 @@ export async function runDesktopPerfAutomation(window: BrowserWindow): Promise<v
await contentTracing.startRecording(traceConfig);
isTraceRecording = true;
console.log("[desktop-perf] running scripted interactions");
const interactions = await runRendererPerfInteractions(window);
const interactions = await runRendererPerfInteractions(window, seed.benchmarkThreadIds);
await delay(300);
console.log("[desktop-perf] stopping trace recording");
tracePath = await withTimeout(
@@ -536,6 +658,10 @@ export async function runDesktopPerfAutomation(window: BrowserWindow): Promise<v
status: "ok",
tracePath,
interactions,
seed: {
source: seed.source,
path: seed.resolvedPath,
},
startedAt: new Date(startedAt).toISOString(),
completedAt: new Date(completedAt).toISOString(),
durationMs: completedAt - startedAt,
@@ -571,6 +697,13 @@ export async function runDesktopPerfAutomation(window: BrowserWindow): Promise<v
status: "error",
error: message,
tracePath,
seed:
seed === null
? undefined
: {
source: seed.source,
path: seed.resolvedPath,
},
startedAt: new Date(startedAt).toISOString(),
completedAt: new Date().toISOString(),
},
+1
View File
@@ -14,6 +14,7 @@
"@base-ui/react": "^1.2.0",
"@t3tools/contracts": "workspace:*",
"@tanstack/react-query": "^5.90.0",
"@tanstack/react-virtual": "^3.13.18",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"class-variance-authority": "^0.7.1",
+246 -169
View File
@@ -14,7 +14,6 @@ import {
type ClipboardEvent,
type DragEvent,
type FormEvent,
Fragment,
type KeyboardEvent,
memo,
type RefObject,
@@ -26,6 +25,7 @@ import {
useState,
} from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { type VirtualItem, useVirtualizer } from "@tanstack/react-virtual";
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
import { serverConfigQueryOptions } from "~/lib/serverReactQuery";
@@ -159,7 +159,6 @@ export default function ChatView() {
const [nowTick, setNowTick] = useState(() => Date.now());
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const messagesScrollRef = useRef<HTMLDivElement>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);
const shouldAutoScrollRef = useRef(true);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
@@ -1021,6 +1020,7 @@ export default function ChatView() {
<MessagesTimeline
hasMessages={activeThread.messages.length > 0}
isWorking={isWorking}
scrollContainerRef={messagesScrollRef}
timelineEntries={timelineEntries}
completionDividerBeforeEntryId={completionDividerBeforeEntryId}
completionSummary={completionSummary}
@@ -1029,7 +1029,6 @@ export default function ChatView() {
expandedWorkGroups={expandedWorkGroups}
onToggleWorkGroup={onToggleWorkGroup}
onImageExpand={onExpandTimelineImage}
messagesEndRef={messagesEndRef}
/>
</div>
@@ -1422,6 +1421,7 @@ const PendingApprovalsPanel = memo(function PendingApprovalsPanel({
interface MessagesTimelineProps {
hasMessages: boolean;
isWorking: boolean;
scrollContainerRef: RefObject<HTMLDivElement | null>;
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
completionDividerBeforeEntryId: string | null;
completionSummary: string | null;
@@ -1430,12 +1430,34 @@ interface MessagesTimelineProps {
expandedWorkGroups: Record<string, boolean>;
onToggleWorkGroup: (groupId: string) => void;
onImageExpand: (image: ExpandedImagePreview) => void;
messagesEndRef: RefObject<HTMLDivElement | null>;
}
type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
type TimelineMessage = Extract<TimelineEntry, { kind: "message" }>["message"];
type TimelineRow =
| {
kind: "work";
id: string;
groupedEntries: {
id: string;
tone: "thinking" | "tool" | "info" | "error";
label: string;
detail?: string | null;
}[];
}
| {
kind: "message";
id: string;
message: TimelineMessage;
showCompletionDivider: boolean;
}
| { kind: "working"; id: string };
const MessagesTimeline = memo(function MessagesTimeline({
hasMessages,
isWorking,
scrollContainerRef,
timelineEntries,
completionDividerBeforeEntryId,
completionSummary,
@@ -1444,8 +1466,67 @@ 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">
@@ -1455,181 +1536,177 @@ const MessagesTimeline = memo(function MessagesTimeline({
}
return (
<div className="mx-auto max-w-3xl space-y-4">
{timelineEntries.map((timelineEntry, index) => {
if (timelineEntry.kind === "work" && timelineEntries[index - 1]?.kind === "work") {
return null;
}
<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;
const showCompletionDivider =
timelineEntry.kind === "message" &&
timelineEntry.message.role === "assistant" &&
completionDividerBeforeEntryId === timelineEntry.id;
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})`;
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
)}
return (
<div className="rounded-lg border border-border/80 bg-card/45 px-3 py-2">
<div className="mb-1.5 flex items-center justify-between gap-3">
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
{groupLabel}
</p>
</div>
))}
</div>
</div>
</Fragment>
);
}
if (timelineEntry.message.role === "user") {
const userImages = timelineEntry.message.attachments ?? [];
return (
<Fragment key={timelineEntry.id}>
<div className="flex justify-end">
<div className="max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
{userImages.length > 0 && (
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
{userImages.map((image) => (
<div
key={image.id}
className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
{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)}
>
{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>
)}
{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>
)}
{timelineEntry.message.text && (
<pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
{timelineEntry.message.text}
</pre>
)}
<p className="mt-1.5 text-right text-[10px] text-muted-foreground/30">
{formatTimestamp(timelineEntry.message.createdAt)}
</p>
</div>
</div>
</Fragment>
);
}
</div>
);
})()}
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>
{row.kind === "message" &&
row.message.role === "user" &&
(() => {
const userImages = row.message.attachments ?? [];
return (
<div className="flex justify-end">
<div className="max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
{userImages.length > 0 && (
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
{userImages.map((image: NonNullable<TimelineMessage["attachments"]>[number]) => (
<div
key={image.id}
className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
>
{image.previewUrl ? (
<img
src={image.previewUrl}
alt={image.name}
className="h-full max-h-[220px] w-full cursor-zoom-in object-cover"
onClick={() =>
onImageExpand({ src: image.previewUrl!, name: image.name })
}
/>
) : (
<div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
{image.name}
</div>
)}
</div>
))}
</div>
)}
{row.message.text && (
<pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
{row.message.text}
</pre>
)}
<p className="mt-1.5 text-right text-[10px] text-muted-foreground/30">
{formatTimestamp(row.message.createdAt)}
</p>
</div>
</div>
);
})()}
{row.kind === "message" &&
row.message.role === "assistant" &&
(() => {
const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)");
return (
<>
{row.showCompletionDivider && (
<div className="my-3 flex items-center gap-3">
<span className="h-px flex-1 bg-border" />
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
{completionSummary ? `Response • ${completionSummary}` : "Response"}
</span>
<span className="h-px flex-1 bg-border" />
</div>
)}
<div className="px-1 py-0.5">
<ChatMarkdown text={messageText} />
<p className="mt-1.5 text-[10px] text-muted-foreground/30">
{formatMessageMeta(
row.message.createdAt,
row.message.streaming
? formatElapsed(row.message.createdAt, nowIso)
: formatElapsed(
row.message.createdAt,
assistantCompletionByItemId.get(row.message.id),
),
)}
</p>
</div>
</>
);
})()}
{row.kind === "working" && (
<div className="flex items-center gap-2 py-0.5 pl-1.5">
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
<div className="flex items-center pt-1">
<span className="inline-flex items-center gap-[3px]">
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
</span>
</div>
</div>
)}
</div>
</Fragment>
</div>
);
})}
{isWorking && (
<div className="flex items-center gap-2 py-0.5 pl-1.5">
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
<div className="flex items-center pt-1">
<span className="inline-flex items-center gap-[3px]">
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
</span>
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
);
});
+5
View File
@@ -54,6 +54,7 @@
"@base-ui/react": "^1.2.0",
"@t3tools/contracts": "workspace:*",
"@tanstack/react-query": "^5.90.0",
"@tanstack/react-virtual": "^3.13.18",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"class-variance-authority": "^0.7.1",
@@ -429,6 +430,10 @@
"@tanstack/react-query": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/query-core": "5.90.20" }, "peerDependencies": { "react": "^18 || ^19" } }, "sha512-0Lu6y5t+tvlTJMTO7oh5NSpJfpg/5D41LlThfepTixPYkJ0sE2Jj0m0f6yYqujBwIXlId87e234+MxG3D3g7kg=="],
"@tanstack/react-virtual": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/virtual-core": "3.13.18" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-dZkhyfahpvlaV0rIKnvQiVoWPyURppl6w4m9IwMDpuIjcJ1sD9YGWrt0wISvgU7ewACXx2Ct46WPgI6qAD4v6A=="],
"@tanstack/virtual-core": ["@tanstack/[email protected]", "", {}, "sha512-Mx86Hqu1k39icq2Zusq+Ey2J6dDWTjDvEv43PJtRCoEYTLyfaPnxIQ6iy7YAOK0NV/qOEmZQ/uCufrppZxTgcg=="],
"@tybys/wasm-util": ["@tybys/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg=="],
"@types/babel__core": ["@types/[email protected]", "", { "dependencies": { "@babel/parser": "^7.20.7", "@babel/types": "^7.20.7", "@types/babel__generator": "*", "@types/babel__template": "*", "@types/babel__traverse": "*" } }, "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA=="],
+105 -19
View File
@@ -7,15 +7,56 @@ import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__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) {
const args = new Set(argv.slice(2));
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: args.has("--post-pr"),
postPr,
seedPath,
};
}
@@ -165,6 +206,10 @@ function createMarkdownSummary({ tracePath, donePayload, summary, thresholds })
const largeThreadRenderStats = Array.isArray(donePayload.interactions?.largeThreadRenderStats)
? donePayload.interactions.largeThreadRenderStats
: [];
const seedSource =
donePayload.seed?.source === "file"
? `file (\`${donePayload.seed?.path ?? "unknown"}\`)`
: donePayload.seed?.source ?? "generated";
const lines = [
marker,
"## Desktop Dev Perf Trace",
@@ -174,6 +219,7 @@ function createMarkdownSummary({ tracePath, donePayload, summary, thresholds })
`- Started: ${donePayload.startedAt ?? "n/a"}`,
`- Completed: ${donePayload.completedAt ?? "n/a"}`,
`- Duration: ${donePayload.durationMs ?? "n/a"} ms`,
`- Seed source: ${seedSource}`,
"",
"### Interaction Run",
"",
@@ -181,7 +227,7 @@ function createMarkdownSummary({ tracePath, donePayload, summary, thresholds })
`- Typed chars: ${donePayload.interactions?.typedChars ?? "n/a"}`,
`- Model selected: ${donePayload.interactions?.selectedModel ?? "n/a"}`,
"",
"### Large Thread Render",
"### Benchmark Thread Render",
"",
"| Thread | Messages | Render (ms) |",
"| --- | ---: | ---: |",
@@ -310,24 +356,15 @@ function postSummaryToPr(summaryPath) {
);
}
function prepareDesktopPerfState(stateDir) {
function prepareDesktopPerfState(stateDir, perfProjects = defaultPerfProjects) {
fs.mkdirSync(stateDir, { recursive: true });
const perfProjects = [
{
id: "perf-project-1",
cwd: "/tmp/perf/codething-mvp",
name: "codething-mvp",
},
{
id: "perf-project-2",
cwd: "/tmp/perf/contracts-bench",
name: "contracts-bench",
},
];
for (const project of perfProjects) {
fs.mkdirSync(project.cwd, { recursive: true });
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();
@@ -350,6 +387,52 @@ function prepareDesktopPerfState(stateDir) {
);
}
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, "-");
@@ -361,7 +444,9 @@ async function main() {
const summaryPath = path.join(artifactsDir, "summary.md");
const logPath = path.join(artifactsDir, "run.log");
const stateDir = path.join(artifactsDir, "state");
prepareDesktopPerfState(stateDir);
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");
@@ -376,6 +461,7 @@ async function main() {
T3CODE_DESKTOP_PERF_AUTOMATION: "1",
T3CODE_DESKTOP_PERF_TRACE_OUT: tracePath,
T3CODE_DESKTOP_PERF_DONE_OUT: donePath,
...(seedPath ? { T3CODE_DESKTOP_PERF_SEED_PATH: seedPath } : {}),
T3CODE_DEV_INSTANCE: `desktop-perf-${timestamp}`,
T3CODE_LOG_WS_EVENTS: "0",
T3CODE_STATE_DIR: stateDir,
+2 -1
View File
@@ -14,7 +14,8 @@
"T3CODE_DESKTOP_WS_URL",
"T3CODE_DESKTOP_PERF_AUTOMATION",
"T3CODE_DESKTOP_PERF_TRACE_OUT",
"T3CODE_DESKTOP_PERF_DONE_OUT"
"T3CODE_DESKTOP_PERF_DONE_OUT",
"T3CODE_DESKTOP_PERF_SEED_PATH"
],
"tasks": {
"build": {