diff --git a/config/scripts/performance/fleet-gate/fleet-gate-scenarios.mjs b/config/scripts/performance/fleet-gate/fleet-gate-scenarios.mjs
index 8de2de63a0c..ef2f94ade20 100755
--- a/config/scripts/performance/fleet-gate/fleet-gate-scenarios.mjs
+++ b/config/scripts/performance/fleet-gate/fleet-gate-scenarios.mjs
@@ -116,15 +116,31 @@ async function streamAgentStatus({ page, userDataDir, windowMs }) {
return { note: `${posted} hook events over ${panes.length} panes`, failed }
}
+// Setup, not measured: show a seeded workspace that has a terminal, so keys take the real PTY round trip.
+async function showTerminalWorkspace(page) {
+ await page.evaluate(() => {
+ const state = window.__store.getState()
+ const withTerminal = Object.entries(state.tabsByWorktree ?? {}).find(
+ ([, tabs]) => Array.isArray(tabs) && tabs.length > 0
+ )
+ if (withTerminal && state.activeWorktreeId !== withTerminal[0]) {
+ state.setActiveWorktree(withTerminal[0])
+ }
+ })
+ await sleep(3_000)
+}
+
async function typeIntoComposer({ page, windowMs }) {
+ await showTerminalWorkspace(page)
const target = await page.evaluate(() => {
- const candidates = [
- ...document.querySelectorAll('textarea, [contenteditable="true"], .xterm-helper-textarea')
- ]
- const visible = candidates.find((element) => {
- const rect = element.getBoundingClientRect()
- return rect.width > 0 && rect.height > 0
- })
+ const visible =
+ [...document.querySelectorAll('.xterm-helper-textarea')].find(
+ (element) => element.closest('.xterm')?.getClientRects().length
+ ) ??
+ [...document.querySelectorAll('textarea, [contenteditable="true"]')].find((element) => {
+ const rect = element.getBoundingClientRect()
+ return rect.width > 0 && rect.height > 0
+ })
if (!visible) {
return null
}
@@ -173,6 +189,7 @@ async function switchWorkspaces({ page, windowMs }) {
const deadline = Date.now() + windowMs
let switches = 0
let missed = 0
+ let firstError = null
while (Date.now() < deadline) {
const id = pair[switches % 2]
try {
@@ -180,13 +197,19 @@ async function switchWorkspaces({ page, windowMs }) {
.locator(`[data-worktree-id="${id}"] [data-worktree-card-surface]`)
.first()
.click({ timeout: 5_000 })
- } catch {
+ } catch (error) {
missed += 1
+ firstError ??= String(error?.message ?? error)
+ .split('\n')[0]
+ .slice(0, 160)
}
switches += 1
await sleep(SWITCH_INTERVAL_MS)
}
- return { note: `${switches - missed} switches between 2 cards`, missed }
+ return {
+ note: `${switches - missed} switches between 2 cards${firstError ? ` (first miss: ${firstError})` : ''}`,
+ missed
+ }
}
export const SCENARIOS = {
diff --git a/config/scripts/performance/fleet-gate/fleet-gate-seed.mjs b/config/scripts/performance/fleet-gate/fleet-gate-seed.mjs
deleted file mode 100755
index a0e0e025e38..00000000000
--- a/config/scripts/performance/fleet-gate/fleet-gate-seed.mjs
+++ /dev/null
@@ -1,92 +0,0 @@
-// Turns a real profile's state databases into a fleet seed that a test copy can open without side effects.
-import { createHash } from 'node:crypto'
-import fs from 'node:fs'
-import path from 'node:path'
-
-const PROFILE_ID = 'local-default'
-
-// Domains that would make a test copy reach real hosts or run agents on a schedule.
-const NEUTRALIZED_DOMAINS = [
- 'sshTargets',
- 'sshRemotePtyLeases',
- 'sshPtyConsumerRecoveries',
- 'automations',
- 'bots'
-]
-
-function seedProfileDatabase(seedDir) {
- return path.join(seedDir, 'profiles', PROFILE_ID, 'profile-state.db')
-}
-
-export async function prepareFleetSeed(sourceDir, seedDir) {
- const { DatabaseSync } = await import('node:sqlite')
- const profileSource = path.join(sourceDir, 'profile-state.db')
- const chatSource = path.join(sourceDir, 'agent-session-domain.db')
- for (const file of [profileSource, chatSource]) {
- if (!fs.existsSync(file)) {
- throw new Error(`seed source is missing ${file}`)
- }
- }
- fs.rmSync(seedDir, { recursive: true, force: true })
- fs.mkdirSync(path.dirname(seedProfileDatabase(seedDir)), { recursive: true })
- // VACUUM INTO writes a consistent copy even if the source has a live WAL.
- for (const [from, to] of [
- [profileSource, seedProfileDatabase(seedDir)],
- [chatSource, path.join(seedDir, 'agent-session-domain.db')]
- ]) {
- const source = new DatabaseSync(from, { readOnly: true })
- source.exec(`VACUUM INTO '${to.replaceAll("'", "''")}'`)
- source.close()
- }
- const db = new DatabaseSync(seedProfileDatabase(seedDir))
- const update = db.prepare(
- 'UPDATE profile_state_documents SET payload = ?, content_hash = ? WHERE domain = ?'
- )
- const emptyList = '[]'
- const hash = createHash('sha256').update(emptyList, 'utf8').digest('hex')
- const neutralized = []
- for (const domain of NEUTRALIZED_DOMAINS) {
- if (update.run(emptyList, hash, domain).changes > 0) {
- neutralized.push(domain)
- }
- }
- db.close()
- return { seedDir, neutralized, census: await describeFleetSeed(seedDir) }
-}
-
-export async function describeFleetSeed(seedDir) {
- const { DatabaseSync } = await import('node:sqlite')
- const chat = new DatabaseSync(path.join(seedDir, 'agent-session-domain.db'), { readOnly: true })
- const count = (table) => {
- try {
- return chat.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get().n
- } catch {
- return null
- }
- }
- const census = {
- chatRecords: count('agent_session_records'),
- chatTabs: count('agent_session_tabs')
- }
- chat.close()
- return census
-}
-
-export function assertFleetSeed(seedDir) {
- for (const file of [
- seedProfileDatabase(seedDir),
- path.join(seedDir, 'agent-session-domain.db')
- ]) {
- if (!fs.existsSync(file)) {
- throw new Error(
- `fleet seed ${seedDir} is missing ${path.relative(seedDir, file)}; build one with --prepare-seed
`
- )
- }
- }
-}
-
-/** Copy-on-write clone where the filesystem supports it (APFS, btrfs, XFS); a plain copy otherwise. */
-export function cloneFleetSeed(seedDir, userDataDir) {
- fs.rmSync(userDataDir, { recursive: true, force: true })
- fs.cpSync(seedDir, userDataDir, { recursive: true, mode: fs.constants.COPYFILE_FICLONE })
-}
diff --git a/config/scripts/performance/fleet-gate/fleet-gate-synthetic-seed.mjs b/config/scripts/performance/fleet-gate/fleet-gate-synthetic-seed.mjs
new file mode 100644
index 00000000000..8abf14d315b
--- /dev/null
+++ b/config/scripts/performance/fleet-gate/fleet-gate-synthetic-seed.mjs
@@ -0,0 +1,238 @@
+// Builds a synthetic fleet profile through the app's own APIs: 1,800 worktrees, 100 folders, chat tabs at rest, terminals.
+import { execFileSync } from 'node:child_process'
+import fs from 'node:fs'
+import path from 'node:path'
+
+export const SEED_SHAPE = { worktrees: 1_800, folders: 100, chats: 1_800, terminals: 20 }
+const SEED_FORMAT = 1
+
+function git(cwd, args) {
+ execFileSync('git', args, { cwd, stdio: 'ignore' })
+}
+
+/** One small repo with linked worktrees plus plain folders; paths stay fixed so every seed built on it stays valid. */
+export function ensureFleetCorpus(corpusDir) {
+ const marker = path.join(corpusDir, '.fleet-corpus-ready')
+ if (fs.existsSync(marker)) {
+ return corpusDir
+ }
+ fs.rmSync(corpusDir, { recursive: true, force: true })
+ const repo = path.join(corpusDir, 'fleet-repo')
+ fs.mkdirSync(path.join(repo, 'src'), { recursive: true })
+ git(corpusDir, ['init', '-q', '-b', 'main', repo])
+ git(repo, ['config', 'user.email', 'fleet-gate@example.invalid'])
+ git(repo, ['config', 'user.name', 'Fleet Gate'])
+ for (let index = 1; index <= 20; index += 1) {
+ fs.writeFileSync(path.join(repo, 'src', `f${index}.ts`), `export const v${index} = ${index}\n`)
+ }
+ fs.writeFileSync(path.join(repo, 'README.md'), '# fleet repo\n')
+ git(repo, ['add', '-A'])
+ git(repo, ['commit', '-q', '-m', 'init'])
+ for (let index = 1; index <= SEED_SHAPE.worktrees; index += 1) {
+ const name = `wt-${String(index).padStart(4, '0')}`
+ git(repo, ['worktree', 'add', '-q', '-b', name, path.join(corpusDir, 'wt', name), 'main'])
+ }
+ for (let index = 1; index <= SEED_SHAPE.folders; index += 1) {
+ const folder = path.join(corpusDir, 'folders', `folder-${String(index).padStart(3, '0')}`)
+ fs.mkdirSync(folder, { recursive: true })
+ fs.writeFileSync(path.join(folder, 'notes.txt'), `notes ${index}\n`)
+ }
+ fs.writeFileSync(marker, `${new Date().toISOString()}\n`)
+ return corpusDir
+}
+
+export function readSeedReceipt(seedDir) {
+ try {
+ const receipt = JSON.parse(fs.readFileSync(path.join(seedDir, '.fleet-seed.json'), 'utf8'))
+ return receipt.format === SEED_FORMAT ? receipt : null
+ } catch {
+ return null
+ }
+}
+
+export function completedOnboardingProfile() {
+ return {
+ settings: {
+ telemetry: {
+ optedIn: false,
+ installId: '00000000-0000-4000-8000-000000000000',
+ existedBeforeTelemetryRelease: false
+ }
+ },
+ onboarding: { flowVersion: 2, closedAt: 1, outcome: 'completed', lastCompletedStep: 3 },
+ ui: {
+ contextualToursSeenIds: [
+ 'workspace-board',
+ 'browser',
+ 'tasks',
+ 'automations',
+ 'workspace-creation'
+ ],
+ contextualToursAutoEligible: false,
+ projectOrderManualDefaultNoticeDismissed: true
+ }
+ }
+}
+
+async function addWorkspaces(page, corpusDir) {
+ return page.evaluate(
+ async ({ repoPath, folderRoot, folders }) => {
+ const store = window.__store
+ const added = await window.api.repos.add({ path: repoPath, kind: 'git' })
+ if ('error' in added) {
+ throw new Error(`repo add failed: ${JSON.stringify(added.error)}`)
+ }
+ await store.getState().fetchRepos({ runtimeEnvironmentId: null })
+ await store.getState().fetchWorktrees(added.repo.id, { requireAuthoritative: true })
+ const imported = (store.getState().detectedWorktreesByRepo[added.repo.id]?.worktrees ?? [])
+ .filter((worktree) => !worktree.selectedCheckout)
+ .map((worktree) => worktree.path)
+ await store.getState().updateRepo(added.repo.id, {
+ externalWorktreeVisibility: 'show',
+ importedExternalWorktreePaths: imported,
+ externalWorktreeInboxBaselinePaths: imported
+ })
+ await store.getState().fetchWorktrees(added.repo.id, { requireAuthoritative: true })
+ let folderErrors = 0
+ for (let index = 1; index <= folders; index += 1) {
+ const folderPath = `${folderRoot}/folder-${String(index).padStart(3, '0')}`
+ const result = await window.api.repos.add({ path: folderPath, kind: 'folder' })
+ if (!result?.repo?.id) {
+ folderErrors += 1
+ }
+ }
+ return { imported: imported.length, folderErrors }
+ },
+ {
+ repoPath: path.join(corpusDir, 'fleet-repo'),
+ folderRoot: path.join(corpusDir, 'folders'),
+ folders: SEED_SHAPE.folders
+ }
+ )
+}
+
+// Chats are created at rest through agentSession.create, so no provider process runs.
+async function seedChats(page, count) {
+ return page.evaluate(async (total) => {
+ const canon = (value) =>
+ value === null || typeof value !== 'object'
+ ? JSON.stringify(value ?? null)
+ : Array.isArray(value)
+ ? `[${value.map(canon).join(',')}]`
+ : `{${Object.entries(value)
+ .filter(([, entry]) => entry !== undefined)
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
+ .map(([key, entry]) => `${JSON.stringify(key)}:${canon(entry)}`)
+ .join(',')}}`
+ const sha = async (text) =>
+ [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)))]
+ .map((byte) => byte.toString(16).padStart(2, '0'))
+ .join('')
+ const list = await window.api.runtime.call({ method: 'worktree.list', params: { limit: 5000 } })
+ const worktrees = list.result.worktrees.sort((a, b) => (a.path < b.path ? -1 : 1))
+ const out = { ok: 0, errors: {} }
+ for (let index = 0; index < Math.min(total, worktrees.length); index += 1) {
+ const fields = {
+ worktree: `id:${worktrees[index].id}`,
+ agent: index % 2 === 0 ? 'claude' : 'codex'
+ }
+ const sessionId = crypto.randomUUID()
+ const payloadFingerprint = await sha(
+ canon({ method: 'agentSession.create', sessionId, fields })
+ )
+ const params = {
+ envelope: {
+ sessionId,
+ clientOperationId: `${Date.now()}-${crypto.randomUUID().replaceAll('-', '')}`,
+ expectedRuntimeFence: null,
+ payloadFingerprint
+ },
+ ...fields
+ }
+ try {
+ const response = await window.api.runtime.call({ method: 'agentSession.create', params })
+ if (response.ok && response.result?.ok !== false) {
+ out.ok += 1
+ } else {
+ const key = JSON.stringify(response.error ?? response.result?.refusal ?? response).slice(
+ 0,
+ 200
+ )
+ out.errors[key] = (out.errors[key] ?? 0) + 1
+ }
+ } catch (error) {
+ const key = `throw ${String(error?.message).slice(0, 200)}`
+ out.errors[key] = (out.errors[key] ?? 0) + 1
+ }
+ }
+ return out
+ }, count)
+}
+
+async function seedTerminals(page, count) {
+ return page.evaluate(async (total) => {
+ const list = await window.api.runtime.call({ method: 'worktree.list', params: { limit: 5000 } })
+ const worktrees = list.result.worktrees
+ .filter((worktree) => /\/wt\/wt-\d{4}$/.test(worktree.path))
+ .sort((a, b) => (a.path < b.path ? -1 : 1))
+ .slice(0, total)
+ let ok = 0
+ for (const worktree of worktrees) {
+ const response = await window.api.runtime.call({
+ method: 'terminal.create',
+ params: { worktree: `id:${worktree.id}`, clientMutationId: crypto.randomUUID() }
+ })
+ if (response.ok) {
+ ok += 1
+ }
+ }
+ return { ok }
+ }, count)
+}
+
+export async function readFleetCensus(page) {
+ return page.evaluate(async () => {
+ const tabs = await window.api.runtime.call({ method: 'session.tabs.listAll', params: {} })
+ let chatTabs = 0
+ let terminalTabs = 0
+ for (const snapshot of tabs.result?.snapshots ?? []) {
+ for (const tab of snapshot.tabs ?? []) {
+ if (tab.type === 'terminal') {
+ terminalTabs += 1
+ } else {
+ chatTabs += 1
+ }
+ }
+ }
+ const list = await window.api.runtime.call({ method: 'worktree.list', params: { limit: 5000 } })
+ return { workspaces: list.result?.totalCount ?? null, chatTabs, terminalTabs }
+ })
+}
+
+/** Seeds through a launched app; launch() returns { app, page } with page session-ready, close() quits it gracefully. */
+export async function buildSyntheticFleetSeed({ seedDir, corpusDir, builtBy, launch }) {
+ ensureFleetCorpus(corpusDir)
+ fs.rmSync(seedDir, { recursive: true, force: true })
+ fs.mkdirSync(seedDir, { recursive: true })
+ fs.writeFileSync(
+ path.join(seedDir, 'orca-data.json'),
+ `${JSON.stringify(completedOnboardingProfile(), null, 2)}\n`
+ )
+ const { page, close } = await launch(seedDir)
+ try {
+ const workspaces = await addWorkspaces(page, corpusDir)
+ const chats = await seedChats(page, SEED_SHAPE.chats)
+ const terminals = await seedTerminals(page, SEED_SHAPE.terminals)
+ const census = await readFleetCensus(page)
+ const receipt = { format: SEED_FORMAT, builtBy, workspaces, chats, terminals, census }
+ await close()
+ fs.writeFileSync(
+ path.join(seedDir, '.fleet-seed.json'),
+ `${JSON.stringify(receipt, null, 2)}\n`
+ )
+ return receipt
+ } catch (error) {
+ await close().catch(() => {})
+ throw error
+ }
+}
diff --git a/config/scripts/performance/fleet-gate/run-fleet-gate.mjs b/config/scripts/performance/fleet-gate/run-fleet-gate.mjs
index 9d99cd8fcdc..ae6547916be 100755
--- a/config/scripts/performance/fleet-gate/run-fleet-gate.mjs
+++ b/config/scripts/performance/fleet-gate/run-fleet-gate.mjs
@@ -1,5 +1,5 @@
#!/usr/bin/env node
-// Fleet-scale perf gate: OLD vs NEW on a ~1,900-workspace profile clone. Usage: docs/readme/fleet-perf-gate.md.
+// Fleet-scale perf gate: OLD vs NEW on a ~1,900-workspace synthetic profile. Usage: docs/readme/fleet-perf-gate.md.
import { _electron as electron } from '@stablyai/playwright-test'
import { execFileSync, spawnSync } from 'node:child_process'
import fs from 'node:fs'
@@ -13,22 +13,21 @@ import { installRendererProbe } from './fleet-gate-renderer-probe.mjs'
import { compareRuns, formatTable, windowMetrics } from './fleet-gate-report.mjs'
import { SCENARIOS } from './fleet-gate-scenarios.mjs'
import {
- assertFleetSeed,
- cloneFleetSeed,
- describeFleetSeed,
- prepareFleetSeed
-} from './fleet-gate-seed.mjs'
+ buildSyntheticFleetSeed,
+ readFleetCensus,
+ readSeedReceipt
+} from './fleet-gate-synthetic-seed.mjs'
const CACHE_ROOT =
process.env.ORCA_FLEET_GATE_CACHE ?? path.join(os.homedir(), '.cache', 'orca-fleet-gate')
const KEEP_BUILDS = 4
+const KEEP_SEEDS = 2
function parseArgs(argv) {
const options = {
old: null,
new: 'HEAD',
- seed: process.env.ORCA_FLEET_SEED_DIR ?? path.join(CACHE_ROOT, 'seed'),
- prepareSeed: null,
+ seed: process.env.ORCA_FLEET_SEED_DIR ?? null,
runs: 2,
settleMs: 120_000,
windowMs: 30_000,
@@ -51,7 +50,6 @@ function parseArgs(argv) {
'--old': () => (options.old = value()),
'--new': () => (options.new = value()),
'--seed': () => (options.seed = path.resolve(value())),
- '--prepare-seed': () => (options.prepareSeed = path.resolve(value())),
'--runs': () => (options.runs = Number(value())),
'--settle-ms': () => (options.settleMs = Number(value())),
'--window-ms': () => (options.windowMs = Number(value())),
@@ -112,22 +110,21 @@ function ensureBuild(repoRoot, sha) {
)
run('pnpm', ['run', 'ensure:electron-runtime'], dir, log)
fs.writeFileSync(marker, `${new Date().toISOString()}\n`)
- pruneBuilds(buildsDir, new Set([dir]))
+ pruneCache(buildsDir, '.fleet-gate-built', KEEP_BUILDS, new Set([dir]))
return dir
}
-function pruneBuilds(buildsDir, keep) {
- const builds = fs
- .readdirSync(buildsDir, { withFileTypes: true })
+function pruneCache(parentDir, markerName, keepCount, keep) {
+ const entries = fs
+ .readdirSync(parentDir, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
- .map((entry) => path.join(buildsDir, entry.name))
+ .map((entry) => path.join(parentDir, entry.name))
.map((dir) => ({
dir,
- mtime:
- fs.statSync(path.join(dir, '.fleet-gate-built'), { throwIfNoEntry: false })?.mtimeMs ?? 0
+ mtime: fs.statSync(path.join(dir, markerName), { throwIfNoEntry: false })?.mtimeMs ?? 0
}))
.sort((a, b) => b.mtime - a.mtime)
- for (const { dir } of builds.slice(KEEP_BUILDS)) {
+ for (const { dir } of entries.slice(keepCount)) {
if (!keep.has(dir)) {
fs.rmSync(dir, { recursive: true, force: true })
}
@@ -206,7 +203,7 @@ function readWindowState() {
}
/** The session-ready app window; on timeout, writes what every window showed so one run explains the failure. */
-async function waitForAppWindow(app, { arm, sha, runDir, options, stderrTail }) {
+async function waitForAppWindow(app, { label, userDataDir, outDir, stderrTail }) {
const consoleErrors = []
const watch = (page) =>
page.on('console', (message) => {
@@ -234,31 +231,27 @@ async function waitForAppWindow(app, { arm, sha, runDir, options, stderrTail })
for (const page of app.windows()) {
windows.push(await page.evaluate(readWindowState).catch((error) => ({ error: String(error) })))
}
- const outDir = options.out ?? path.join(CACHE_ROOT, 'reports')
fs.mkdirSync(outDir, { recursive: true })
- const stem = path.join(outDir, `not-ready-${arm}-${sha.slice(0, 11)}-${Date.now()}`)
+ const stem = path.join(outDir, `not-ready-${label}-${Date.now()}`)
await app
.windows()[0]
?.screenshot({ path: `${stem}.png` })
.catch(() => {})
- const userDataFiles = fs.readdirSync(path.join(runDir, 'user-data')).slice(0, 40)
+ const userDataFiles = fs.readdirSync(userDataDir).slice(0, 40)
fs.writeFileSync(
`${stem}.json`,
`${JSON.stringify({ windows, consoleErrors, stderrTail, userDataFiles }, null, 2)}\n`
)
- console.log(`[fleet-gate] ${arm} never became ready: ${JSON.stringify(windows).slice(0, 600)}`)
+ console.log(`[fleet-gate] ${label} never became ready: ${JSON.stringify(windows).slice(0, 600)}`)
console.log(
`[fleet-gate] console errors: ${JSON.stringify(consoleErrors.slice(-5)).slice(0, 600)}`
)
console.log(`[fleet-gate] stderr tail: ${JSON.stringify(stderrTail.slice(-8)).slice(0, 800)}`)
- throw new Error(
- `${arm} ${sha.slice(0, 11)} not session-ready after ${READY_TIMEOUT_MS / 1000}s (${stem}.json)`
- )
+ throw new Error(`${label} not session-ready after ${READY_TIMEOUT_MS / 1000}s (${stem}.json)`)
}
-async function measureOnce({ arm, sha, buildDir, options, runDir }) {
- const userDataDir = path.join(runDir, 'user-data')
- cloneFleetSeed(options.seed, userDataDir)
+/** Launches one hidden copy on userDataDir; close() quits it (gracefully first) and is safe to call twice. */
+async function launchCopy({ buildDir, runDir, userDataDir, label, outDir }) {
const executablePath = createRequire(path.join(buildDir, 'package.json'))('electron')
const app = await electron.launch({
executablePath,
@@ -266,14 +259,69 @@ async function measureOnce({ arm, sha, buildDir, options, runDir }) {
env: isolatedEnv(runDir, userDataDir),
timeout: 180_000
})
- const result = { arm, sha, windows: {}, census: null, notes: [] }
const stderrTail = []
app.process().stderr?.on('data', (chunk) => {
stderrTail.push(...String(chunk).split('\n').filter(Boolean))
stderrTail.splice(0, Math.max(0, stderrTail.length - 40))
})
+ let closed = false
+ const close = async () => {
+ if (closed) {
+ return
+ }
+ closed = true
+ await Promise.race([
+ app.close().catch(() => {}),
+ new Promise((resolve) => setTimeout(resolve, 30_000))
+ ])
+ const child = app.process()
+ if (child.exitCode === null && child.signalCode === null) {
+ child.kill('SIGKILL')
+ }
+ }
+ try {
+ const page = await waitForAppWindow(app, { label, userDataDir, outDir, stderrTail })
+ return { app, page, close }
+ } catch (error) {
+ await close()
+ throw error
+ }
+}
+
+/** A seed made by the OLD build, so NEW only ever opens it forward, as an upgrade would. */
+async function ensureSeed({ oldSha, oldBuild, outDir }) {
+ const seedsDir = path.join(CACHE_ROOT, 'seeds')
+ const seedDir = path.join(seedsDir, oldSha)
+ const existing = readSeedReceipt(seedDir)
+ if (existing) {
+ fs.utimesSync(path.join(seedDir, '.fleet-seed.json'), new Date(), new Date())
+ return { seedDir, receipt: existing }
+ }
+ console.log(`[fleet-gate] seeding a synthetic fleet with ${oldSha.slice(0, 12)}`)
+ const runDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orca-fleet-seed-'))
+ try {
+ const receipt = await buildSyntheticFleetSeed({
+ seedDir,
+ corpusDir: path.join(CACHE_ROOT, 'corpus'),
+ builtBy: oldSha,
+ launch: (userDataDir) =>
+ launchCopy({ buildDir: oldBuild, runDir, userDataDir, label: 'seed', outDir })
+ })
+ console.log(`[fleet-gate] seed ${JSON.stringify(receipt)}`)
+ pruneCache(seedsDir, '.fleet-seed.json', KEEP_SEEDS, new Set([seedDir]))
+ return { seedDir, receipt }
+ } finally {
+ fs.rmSync(runDir, { recursive: true, force: true })
+ }
+}
+
+async function measureOnce({ arm, sha, buildDir, seedDir, options, runDir, outDir }) {
+ const userDataDir = path.join(runDir, 'user-data')
+ fs.cpSync(seedDir, userDataDir, { recursive: true, mode: fs.constants.COPYFILE_FICLONE })
+ const result = { arm, sha, windows: {}, census: null, notes: [] }
+ const label = `${arm}-${sha.slice(0, 11)}`
+ const { app, page, close } = await launchCopy({ buildDir, runDir, userDataDir, label, outDir })
try {
- const page = await waitForAppWindow(app, { arm, sha, runDir, options, stderrTail })
const probeState = await installMainProbeIn(app)
if (probeState !== 'installed') {
result.notes.push(`main probe ${probeState}: R→M counts only send(), not invoke()`)
@@ -282,17 +330,10 @@ async function measureOnce({ arm, sha, buildDir, options, runDir }) {
if (renderer.breakpoints === 0) {
result.notes.push('store notify loop not found: store pubs/wakeups not measured')
}
- console.log(`[fleet-gate] ${arm} ${sha.slice(0, 12)} up; settling ${options.settleMs / 1000}s`)
+ console.log(`[fleet-gate] ${label} up; settling ${options.settleMs / 1000}s`)
await new Promise((resolve) => setTimeout(resolve, options.settleMs))
- result.census = await page.evaluate(() => {
- const state = window.__store.getState()
- return {
- workspaces: Object.values(state.worktreesByRepo).flat().length,
- tabBuckets: Object.keys(state.unifiedTabsByWorktree ?? {}).length,
- terminalTabs: Object.values(state.tabsByWorktree ?? {}).flat().length,
- agentStatuses: Object.keys(state.agentStatusByPaneKey ?? {}).length
- }
- })
+ result.census = await readFleetCensus(page)
+ await page.screenshot({ path: path.join(outDir, `${label}-${Date.now()}.png`) }).catch(() => {})
for (const name of options.scenarios) {
const windowMs = name === 'idle' ? options.idleWindowMs : options.windowMs
await resetMainProbe(app)
@@ -320,18 +361,11 @@ async function measureOnce({ arm, sha, buildDir, options, runDir }) {
.map(([channel, row]) => `${channel} ${row.n}`)
}
console.log(
- `[fleet-gate] ${arm} ${name}: ${JSON.stringify(result.windows[name].metrics)} ${driven.note ?? ''}`
+ `[fleet-gate] ${label} ${name}: ${JSON.stringify(result.windows[name].metrics)} ${driven.note ?? ''} top M→R ${result.windows[name].topOut.join('; ')}`
)
}
} finally {
- await Promise.race([
- app.close().catch(() => {}),
- new Promise((resolve) => setTimeout(resolve, 30_000))
- ])
- const child = app.process()
- if (child.exitCode === null && child.signalCode === null) {
- child.kill('SIGKILL')
- }
+ await close()
fs.rmSync(runDir, { recursive: true, force: true })
}
return result
@@ -340,13 +374,6 @@ async function measureOnce({ arm, sha, buildDir, options, runDir }) {
async function main() {
const options = parseArgs(process.argv.slice(2))
const repoRoot = git(process.cwd(), ['rev-parse', '--show-toplevel'])
- if (options.prepareSeed) {
- const prepared = await prepareFleetSeed(options.prepareSeed, options.seed)
- console.log(
- `[fleet-gate] seed ready at ${prepared.seedDir}; neutralized ${prepared.neutralized.join(', ') || 'nothing'}; ${JSON.stringify(prepared.census)}`
- )
- return
- }
const newSha = git(repoRoot, ['rev-parse', `${options.new}^{commit}`])
const oldSha = git(repoRoot, [
'rev-parse',
@@ -363,9 +390,12 @@ async function main() {
console.log(`hot-path changes (${hot.length}): ${hot.slice(0, 10).join(', ')}`)
return
}
- assertFleetSeed(options.seed)
- const seedCensus = await describeFleetSeed(options.seed)
+ const outDir = options.out ?? path.join(CACHE_ROOT, 'reports')
+ fs.mkdirSync(outDir, { recursive: true })
const builds = { old: ensureBuild(repoRoot, oldSha), new: ensureBuild(repoRoot, newSha) }
+ const seed = options.seed
+ ? { seedDir: options.seed, receipt: null }
+ : await ensureSeed({ oldSha, oldBuild: builds.old, outDir })
const shas = { old: oldSha, new: newSha }
const runs = []
const schedule = buildCounterbalancedSchedule(options.runs, 'old', 'new')
@@ -378,7 +408,9 @@ async function main() {
arm,
sha: shas[arm],
buildDir: builds[arm],
+ seedDir: seed.seedDir,
options,
+ outDir,
runDir: path.join(runsRoot, `${arm}-${runs.length}`)
})
)
@@ -398,12 +430,10 @@ async function main() {
}
const header = [
`FLEET GATE OLD ${oldSha.slice(0, 11)} NEW ${newSha.slice(0, 11)} ${options.runs} runs each (alternating) ${os.hostname()} ${process.platform}`,
- `census: ${census ? `${String(census.workspaces)} workspaces, ${String(census.tabBuckets)} tab buckets, ${String(census.terminalTabs)} terminal tabs, ${String(census.agentStatuses)} agent statuses` : 'n/a'}; seed ${String(seedCensus.chatRecords)} chat records, ${String(seedCensus.chatTabs)} chat tabs`,
+ `census (read back after settle): ${census ? `${String(census.workspaces)} workspaces, ${String(census.chatTabs)} chat tabs, ${String(census.terminalTabs)} terminal tabs` : 'n/a'}; seed ${seed.receipt ? `synthetic, built by ${String(seed.receipt.builtBy).slice(0, 11)}` : String(options.seed)}`,
`hot-path files: ${hot.length}${options.force && hot.length === 0 ? ' (forced)' : ''}`
].join('\n')
const { text, passed } = formatTable({ rows, header, notes })
- const outDir = options.out ?? path.join(CACHE_ROOT, 'reports')
- fs.mkdirSync(outDir, { recursive: true })
const stem = path.join(
outDir,
`fleet-gate-${oldSha.slice(0, 11)}-${newSha.slice(0, 11)}-${Date.now()}`
diff --git a/docs/readme/fleet-perf-gate.md b/docs/readme/fleet-perf-gate.md
index 58f91fe8a4d..15641380c2b 100644
--- a/docs/readme/fleet-perf-gate.md
+++ b/docs/readme/fleet-perf-gate.md
@@ -1,6 +1,6 @@
# Fleet perf gate
-A real-app OLD vs NEW check at fleet scale (~1,900 workspaces, ~1,800 chat tabs). It exists because some regressions only show when every workspace pays: an idle desktop that sends itself 143 tab-update frames per second looks fine with 10 workspaces.
+A real-app OLD vs NEW check at fleet scale (~1,900 workspaces, ~1,800 chat tabs, synthetic). It exists because some regressions only show when every workspace pays: an idle desktop that sends itself 143 tab-update frames per second looks fine with 10 workspaces.
```sh
pnpm perf:fleet-gate --old [--new HEAD] [--runs 2] [--scenarios idle,typing,streaming,switch]
@@ -11,7 +11,7 @@ It is a no-op unless the change touches a hot path (main process, preload/IPC, s
## What it does
1. Builds OLD and NEW in e2e mode, each in its own shared clone under `~/.cache/orca-fleet-gate/builds/` (cached by commit; the newest four are kept).
-2. For each run, clones the seed into a throwaway user-data dir and home, launches the copy hidden, waits for the session to load, and lets it settle (`--settle-ms`, 120 s).
+2. Seeds a synthetic fleet once per OLD commit (below). For each run, clones the seed into a throwaway user-data dir and home, launches the copy hidden, waits for the session to load, and lets it settle (`--settle-ms`, 120 s).
3. Measures four windows: `idle` (60 s, no input), `typing` (10 keys/s into the first visible input), `streaming` (20 agent hook events/s across 10 workspaces, through the real hook endpoint) and `switch` (click between two workspace cards once a second).
4. Runs OLD and NEW alternately (`--runs` pairs, counterbalanced) so drift on the machine hits both.
@@ -34,14 +34,8 @@ A metric fails when every NEW run is worse than every OLD run by more than the m
## Seed
-The seed is a user-data folder holding `profiles/local-default/profile-state.db` and `agent-session-domain.db`. Make one from a real profile's two database files:
-
-```sh
-pnpm perf:fleet-gate --prepare-seed [--seed ]
-```
-
-Preparing a seed empties SSH targets, remote PTY leases, automations and bots, so a test copy never connects to real hosts or starts scheduled agents. The default seed location is `~/.cache/orca-fleet-gate/seed` (`ORCA_FLEET_SEED_DIR` overrides it). Seeds hold a real user's workspace names and chats, so keep them on team machines and out of CI.
+The gate builds its own synthetic fleet; no real user data is involved. It makes one small git repo with 1,800 linked worktrees plus 100 plain folders (`~/.cache/orca-fleet-gate/corpus`). Then it adds them through the app's own APIs, creates 1,800 chat tabs at rest (no agent process runs) and 20 terminals. The seed is built by the OLD build, so NEW opens it the way an upgrade would. It is cached per OLD commit (`seeds/`, newest two kept), and each run starts from a copy-on-write clone of it. The table header prints the census read back from the app after settling. `--seed ` (or `ORCA_FLEET_SEED_DIR`) measures on an existing profile instead.
## Why not CI
-The seed is real user data, and wall-clock rates on shared hosted runners are too noisy for 25% margins. Count contracts that need neither (`pnpm test:perf:contracts`) stay in CI.
+It needs two app builds and about 30 minutes of a quiet machine, and wall-clock rates on shared hosted runners are too noisy for 25% margins. Count contracts that need neither (`pnpm test:perf:contracts`) stay in CI.