Repository navigation
Description
What is slow
Clicking a thread that belongs to a different project than the one open makes the server compute git status, the Changes totals and the diff preview for that project. On Windows this one click starts 87–90 git processes (6.0–6.6 s of summed git process time), and the Changes totals appear 2.6–2.8 s after the click. About a third of those processes repeat one lookup: resolveBaseBranchForNoUpstream, which answers "what base branch does this branch compare against" with up to 7 git processes run one after another, and runs 5–6 times in the same click.
Measured
- Windows Server 2025, 4 logical CPUs, Defender real-time scanning on. Commit
f2ec853fbb, server from source, production web build, headless Chromium through Playwright. - Seed: 10 projects (git repos with 20 files, one commit), ~141 finished devReplay threads.
proj-0has an origin withmaintracking it;proj-1has an origin and is on an unpushed branchfeature/x(the state of a fresh T3 worktree branch); the rest have no remote. - 3 cross-project switches (into a no-remote repo twice, into the feature-branch repo once):
| switch into | git processes | base-branch lookups (git) | local status reads (git) |
|---|---|---|---|
| no remote | 90 | 6 (36) | 3 (41) |
| no remote | 89 | 5 (34) | 3 (40) |
| feature branch, origin, no upstream | 87 | 6 (29) | 3 (35) |
- Each completed lookup takes 180–390 ms on Windows (7 serial git processes:
config --get branch.<b>.t3-merge-base-ref,branch.<b>.t3-merge-base,branch.<b>.gh-merge-base,remote get-url origin,remote,rev-parse <b>@{upstream},show-ref refs/heads/master). - Linux comparison, same seed shape: 85 git processes for the feature-branch repo (6 lookups), 48 for
mainwith an upstream (4 lookups). Upstream tracking does not avoid it, because the diff preview always takes this path. - While a thread stays open, every 30-s status poll runs 2 more lookups (13 git processes per poll).
How to measure it again
- Build the web app (
cd apps/web && vp build). Fromapps/server, start a seeding server:T3CODE_DEV_SEED=0 node src/bin.ts serve --base-dir <home> --port <p> --host 127.0.0.1 --dev-url http://localhost:5733. Wait ~40 s. - Seed with
node seed.cjs <apps/server dir> <home> <reposDir> 10 10 4(below). On Windows each devReplay thread leaves adev-replay-agent.tsnode process running; 10 threads per project is enough. Give one repo an origin and an unpushed branch:git clone --bare proj-1 bare1.git; git -C proj-1 remote add origin <abs>/bare1.git; git -C proj-1 push -u origin main; git -C proj-1 checkout -b feature/x, then commit a change. - Stop the server and its replay agents. Restart it on the same home without
--dev-url, so it serves the production web. - Pair:
node src/bin.ts pair --ttl 1h --base-dir <home>and take thehttp...pair#token=...URL (rewrite the host to127.0.0.1:<p>). node switch.cjs <node_modules/.pnpm/playwright@*/node_modules/playwright> <pairUrl> 14 clicks.json. Thennode tracecount.cjs clicks.json 6000 <home>/userdata/logs/server.trace.ndjson.1 <home>/userdata/logs/server.trace.ndjson. A cross-project switch is a click whosereqlist starts with aT(trackedOnly) entry.
// seed.cjs <serverDir> <home> <reposDir> <projects> <threadsPerProject> [concurrency]
const { execFileSync, execFile } = require("node:child_process"); const fs = require("node:fs"); const path = require("node:path");
const [serverDir, home, reposDir, nP, nT, conc = "4"] = process.argv.slice(2);
const run = (a) => new Promise((res, rej) => execFile(process.execPath, ["src/bin.ts", ...a], { cwd: serverDir, env: { ...process.env, T3CODE_DEV_SEED: "0" }, maxBuffer: 1 << 26 }, (e, o, er) => e ? rej(new Error(String(er || e.message))) : res(o)));
const retry = async (a) => { try { return await run(a); } catch { return await run(a); } };
(async () => { const jobs = [];
for (let i = 0; i < +nP; i++) { const dir = path.join(reposDir, `proj-${i}`); fs.mkdirSync(dir, { recursive: true });
for (let f = 0; f < 20; f++) fs.writeFileSync(path.join(dir, `file${f}.txt`), `hello ${i} ${f}\n`);
execFileSync("git", ["init", "-q", "-b", "main"], { cwd: dir }); execFileSync("git", ["add", "."], { cwd: dir });
execFileSync("git", ["-c", "user.email=a@b.c", "-c", "user.name=seed", "commit", "-qm", "init"], { cwd: dir });
const pid = /Added project (\S+)/.exec(await retry(["project", "add", dir, "--base-dir", home]))[1];
for (let t = 0; t < +nT; t++) jobs.push([pid, `task ${i}-${t}`]); }
let next = 0; await Promise.all(Array.from({ length: +conc }, async () => { while (next < jobs.length) { const [pid, m] = jobs[next++];
await retry(["thread", "start", "--base-dir", home, "--provider", "devReplay", "--model", "todo-list", "--wait", "--json", pid, m]); } }));
console.log("DONE", jobs.length); })();// switch.cjs <playwrightDir> <pairUrl> <clicks> <out.json>: clicks sidebar threads; per click the diff-preview requests, interrupts, status subscriptions and answer time
const [pw, pairUrl, clicks, out] = process.argv.slice(2); const { chromium } = require(pw); const fs = require("node:fs");
(async () => { const b = await chromium.launch(); const p = await (await b.newContext({ viewport: { width: 1600, height: 1000 } })).newPage();
let cur = null; const ids = new Set(); const res = [];
p.on("websocket", (ws) => {
ws.on("framesent", (f) => { let m; try { m = JSON.parse(String(f.payload)); } catch { return; } if (!cur) return;
if (m.tag === "review.getDiffPreview") { ids.add(String(m.id)); cur.req.push(`${m.payload?.trackedOnly ? "T" : ""}${Date.now() - cur.at}:${String(m.payload?.cwd).split(/[\\/]/).pop()}`); }
else if (m.tag === "subscribeVcsStatus") cur.statusSubs++;
else if (m._tag === "Interrupt" && ids.has(String(m.requestId))) cur.interrupts++; });
ws.on("framereceived", (f) => { if (!cur) return; const s = String(f.payload); if (!s.includes('"Exit"')) return; let m; try { m = JSON.parse(s); } catch { return; }
for (const x of [].concat(m)) if (x._tag === "Exit" && ids.has(String(x.requestId))) cur.answerAt = Date.now() - cur.at; }); });
await p.goto(pairUrl); await p.waitForTimeout(20000);
const n = await p.locator("[data-thread-item]").count();
for (let i = 0; i < +clicks; i++) { const idx = (i * 7 + 1) % n; cur = { at: Date.now(), idx, req: [], interrupts: 0, statusSubs: 0, answerAt: null };
await p.locator("[data-thread-item]").nth(idx).click(); await p.waitForTimeout(6000); console.log(JSON.stringify(cur)); res.push(cur); cur = null; }
fs.writeFileSync(out, JSON.stringify(res)); await b.close(); })();// tracecount.cjs <windows.json> <windowMs> <trace.ndjson>...: per window, git processes and named spans (duration/git processes under it/exit)
const fs = require("node:fs"); const [winFile, W, ...traces] = process.argv.slice(2);
const sp = new Map(); for (const f of traces) for (const l of fs.readFileSync(f, "utf8").split("\n")) { try { const r = JSON.parse(l); if (r.type === "effect-span") sp.set(r.spanId, r); } catch {} }
const kids = new Map(); for (const s of sp.values()) { const k = kids.get(s.parentSpanId) || []; k.push(s); kids.set(s.parentSpanId, k); }
const st = (s) => Number(BigInt(s.startTimeUnixNano) / 1000000n);
const git = (s) => { let n = 0; const q = [s]; while (q.length) { const x = q.pop(); if (x.name === "runGitCommand") n++; q.push(...(kids.get(x.spanId) || [])); } return n; };
const NAMES = ["resolveBaseBranchForNoUpstream", "GitWorkflowService.localStatus", "GitWorkflowService.remoteStatus", "VcsStatusBroadcaster.refreshRemoteStatus", "ws.rpc.review.getDiffPreview", "ws.rpc.subscribeVcsStatus"];
for (const w of JSON.parse(fs.readFileSync(winFile, "utf8"))) { const a = w.at, b = a + +W; const ins = [...sp.values()].filter((s) => st(s) >= a && st(s) < b);
const o = { at: a, idx: w.idx, gitProcesses: ins.filter((s) => s.name === "runGitCommand").length };
for (const n of NAMES) o[n] = ins.filter((s) => s.name === n).map((s) => `${Math.round(s.durationMs)}ms/${git(s)}git/${s.exit._tag[0]}`);
console.log(JSON.stringify(o)); }Where the time goes
apps/server/src/vcs/GitVcsDriverCore.ts, resolveBaseBranchForNoUpstream. In one cross-project switch it is called from:
readBranchChangeTotals→resolveReviewMergeBase, once per local status read (2–3 per switch, inVcsStatusBroadcastergetOrLoadLocalStatusandrefreshRemoteStatus→refreshLocalStatusCore);computeAheadCountAgainstBaseinreadStatusDetailsRemote(1);getReviewDiffPreview→resolveReviewMergeBaseforreview.getDiffPreview(2: the trackedOnly pass and the full pass).
Each call reads the same branch config, remotes and refs again, serially. Trace excerpt from one switch into a no-remote repo (start offset from the click, duration, git processes): +841 179ms 2git (interrupted), +1180 287ms 7git, +1759 370ms 7git, +1951 317ms 6git, +2255 390ms 7git, +2967 261ms 7git.
Why it is avoidable
The answer depends only on the branch's config and the repository's refs, and none of them change within one switch, so the later calls repeat the first. The same inputs feed several callers that run within a second of each other.
What a fix has to show
The same switch measurement, before and after, at least 3 cross-project and 5 same-project switches:
resolveBaseBranchForNoUpstreamwork per cross-project switch goes from 5–6 completed lookups (29–36 git processes) to at most 1 per cwd while refs and branch config are unchanged (about 7 git processes), so git processes per cross-project switch drop from ~88 to about 62 or fewer.- The 30-s poll's 2 lookups (13 git processes) drop to at most 1 when refs did not move.
- Must stay: one lookup per cwd after any ref or
branch.*config change (a fetch, a checkout, a commit, a base branch the user sets). The result must match today's for configuredt3-merge-base-ref,t3-merge-base/gh-merge-base, tracked upstream, origin default branch and themain/masterfallback. - Overlaps with the local-status re-read finding for the 30-s poll: each read of local status includes one lookup. Count the two separately.
Found by the automated Windows performance sweep on f2ec853.
Found by the automated Windows performance sweep on f2ec853.
Activity