Skip to content

fix: agent switching leaves the session list waiting - #150092

Merged
jalehman merged 4 commits into
mainfrom
openclaw/agent-switch-session-performance
Sep 17, 2026
Merged

jalehman merged 4 commits into
mainfrom
openclaw/agent-switch-session-performance

Conversation

@jalehman

@jalehman jalehman commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: switching agents leaves the session sidebar waiting for the previous chat's startup work, and returning to a loaded agent waits for another list response.

User Impact

Explicit agent switches can fetch the selected agent's sessions immediately. Returning to a loaded agent can show its matching, still-valid list while a fresh server request runs. Server invalidation, local mutations, observer failure, connection changes, and query changes retire stale presentation.

Why This Change Was Made

Foreground navigation should not queue behind background hydration. Warm presentation reuses the existing roster owner rather than adding independent storage, and remains separate from authoritative state. Request generations fence superseded navigation; server invalidation also fences warm admission for reads already in flight.

Visual delivery and final evidence acceptance are incomplete. Do not merge.

Historical evidence

Rebased candidate: 114bfa58bcc28ad1dbbf4f347cf0c0e665dd7aa4 on 82d4d1cc175549e222e3cb2605716f277eff6a00. Current-base validation below supersedes earlier candidate measurements.

  • Full session suite: 65 files / 1,040 tests passed, including configuration invalidation during an outstanding read.
  • Bundled browser proof passed: Writer rows appear before delayed chat startup; Main rows reappear while its replacement list request is held. Earlier fence candidates failed this proof and were corrected, not accepted.
  • Invalidation regression red/green verified: removing the admission fence fails the expected null-presentation assertion; restoring it passes. Final independent autoreview: scoped-clean at P0–P2, no actionable findings.
  • Before/after five-run synthetic benchmark: baseline recorded with 200 rows per agent, 150 ms list delay, and 600 ms cold startup delay. Final candidate: cold-switch median 309.0 ms (baseline 852.4 ms), warm-return median 36.6 ms (baseline 287.4 ms). This is deterministic fixture evidence, not a production latency guarantee.
  • Final source-only scoped lint passed: 0 warnings / 0 errors across 10 changed files.
  • UI typecheck and broader changed-file checks are blocked by the local hermetic declaration boundary: the shared TypeScript installation resolves outside this worktree. Dependencies and the boundary were not altered.
  • Before/after screenshots and benchmark summary are uploaded directly to this PR and browser-verified: both images loaded with nonzero natural dimensions and visible layout. All five-run samples, raw JSON, controls, limitations, and reproduction harness are published separately. Originating-chat render confirmation and complete run-to-commit provenance remain open.

Changes walkthrough

File Change
ui/src/lib/sessions/index.ts Connect foreground selection and warm presentation
ui/src/lib/sessions/session-agent-selection.ts Distinguish picker intent from reconciliation
ui/src/lib/sessions/session-list-query.ts Retain foreground intent and warm ownership
ui/src/lib/sessions/session-roster-refresh.ts Prioritize selection and fence response admission
ui/src/lib/sessions/session-primary-windows.ts Own scoped warm presentation leases
ui/src/lib/sessions/session-list-observation.ts Extract observed-query lifecycle
ui/src/lib/sessions/selection-hydration.test.ts Preserve automatic startup behavior
ui/src/lib/sessions/agent-selection-priority.test.ts Cover foreground supersession
ui/src/lib/sessions/warm-selection-presentation.test.ts Cover query scope and invalidation
ui/src/e2e/agent-switch-roster.e2e.test.ts Hold startup and list responses in browser proof

View the OpenClaw team session

Repair validation — adb125973be693e24780a9b451a37681d593601d

The repair separates automatic startup binding from deliberate selection, keeps scoped history defaults behind lifecycle checks without authorizing stale descriptor updates, fixes typed RPC mocks, and gives the private agent-switch browser server a serial test owner. The prestarted-history regression failed before the fix; all six scoped-history cases are preserved in a dedicated sibling suite.

  • 545 focused unit tests passed (424 history/lifecycle + 121 lineage/selection).
  • 26 browser tests passed for startup priority, agent switching, and queue recovery on byte-identical production/browser-harness sources. Exact committed-head rerun is being collected separately.
  • Final staged candidate autoreview: scoped-clean P0–P2; the normal-hook commit tree exactly matches the reviewed tree 03f9392fda9f54487d3d00efe7f4aad609c7e95a.
  • UI/root/script lint, i18n verification, dead-export scans, coercion guard, line-growth and assertion guards passed. No coverage or guard was disabled.
  • Local typechecking is still unverified: the compiler boundary correctly rejects this checkout's externally linked dependencies. No dependencies or compiler guards were changed. Hosted exact-head CI is required; this is not a readiness or merge claim.

The existing screenshot and video evidence remains historical at its explicitly recorded source identities. The five paired normal-speed recordings and full measurements are attached directly here; they do not claim to measure this latest repair commit. Originating-chat screenshot rendering remains unverified. The PR is currently ready for review; this update preserves that state and does not clear the remaining exact-head CI/review or delivery gates. No merge authorization has been given.

Current-head acceptance: d6b040f3e5bd3d574f6d1f15a9d3f1672267b5c8

  • Exact-head CI completed successfully, including production/test typechecks, lint, build artifacts and the UI performance gate. The local compiler boundary remains a separate local limitation.
  • Held-request browser proof: one test passed, showing Writer rows before delayed startup completes and warm Main rows before the replacement list response.
  • Five paired synthetic benchmark repetitions completed against this exact integrated candidate: cold-switch median 405.9 → 149.8 ms; warm-return median 160.5 → 113.7 ms. The linked evidence contains every sample, source verification, controls and limitations. The older baseline does not isolate this PR's contribution; these are not production-latency claims.
  • ClawSweeper reviewed this head with no actionable code or security findings. Its evidence and originating-chat screenshot-delivery holds are not waived.
  • Visual delivery remains incomplete. New screenshots and ten normal-speed recordings exist locally, but their inspection and destination rendering are unverified. Historical published media keeps its original source identity. No merge authorization.

@clawsweeper

clawsweeper Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui size: L maintainer Maintainer-authored PR labels Sep 16, 2026
@jalehman
jalehman force-pushed the openclaw/agent-switch-session-performance branch from c7d30ea to 114bfa5 Compare September 16, 2026 13:52
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 16, 2026
@clawsweeper

clawsweeper Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 16, 2026, 7:09 PM ET / 23:09 UTC (Revision 7).

ClawSweeper review

What this changes

The PR makes agent switching load sidebar sessions promptly, reuses valid previously loaded lists, and preserves newer session details when delayed chat history arrives.

Merge readiness

⛔ Blocked before merge - 2 items remain

This remains a useful, distinct fix. The new evidence resolves the current-head validation and benchmark-provenance concern, and no actionable code or security findings remain. The explicit visual-delivery hold still applies.

Priority: P2
Reviewed head: d6b040f3e5bd3d574f6d1f15a9d3f1672267b5c8

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A sound owner-level repair with strong bounded browser evidence and successful exact-head CI; the delivery hold does not lower implementation quality.
Proof confidence 🦞 diamond lobster (5/6) ✨ media proof bonus Sufficient (linked_artifact): The exact-head Chromium run exercises the rendered agent picker and roster owner against a synthetic Gateway, showing Writer rows before startup completes and warm Main rows before replacement data arrives. The complete source-bound benchmark adds observed timings; historical screenshots retain their original identity. The separate originating-chat screenshot-delivery gate remains open.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (linked_artifact): The exact-head Chromium run exercises the rendered agent picker and roster owner against a synthetic Gateway, showing Writer rows before startup completes and warm Main rows before replacement data arrives. The complete source-bound benchmark adds observed timings; historical screenshots retain their original identity. The separate originating-chat screenshot-delivery gate remains open.
Evidence reviewed 9 items Pinned source and clean checkout: The checkout matches the reviewed head and reported benchmark tree: d6b040f, tree 941389b6412836e096875b434fd65784c6cac56e. Final git status remained clean. Review used the pinned introduced delta, not the stale test-merge result.
Foreground selection and scoped reuse: Explicit selection supersedes the old request's publication generation and starts the selected roster without background admission. Warm presentation remains in the existing managed-list owner, checks connection epoch and query identity, and retires on invalidation. These changes add no persistent format, public plugin API, or authorization grant.
Delayed-history safeguards: Defaults-only admission retains connection and deletion-generation checks while preventing stale descriptor publication; the chat consumer preserves the current row and skips stale descriptor/run-state updates. The focused scoped-history suite retains the prior controls and adds prestarted-history coverage.
Findings None None.
Security None None.

How this fits together

The Control UI session roster turns agent selections and Gateway session responses into sidebar rows. Its refresh owner coordinates foreground navigation, background loading, and temporary presentation of previously loaded sessions.

flowchart TD
  A[Agent selection] --> B{Explicit navigation?}
  B -->|Yes| C[Immediate roster request]
  B -->|No| D[Background startup queue]
  D --> C
  C --> E[Gateway session response]
  E --> F[Scope and freshness checks]
  F --> G[Selected agent sidebar]
  H[Valid loaded session list] --> G
Loading

Before merge

  • Resolve merge risk (P1) - Required before/after screenshot rendering in the originating chat remains unverified and explicitly unwaived; inspecting images in this review does not satisfy that destination.
  • Complete next step (P2) - Confirm the inspected, sanitized before/after screenshots render in the originating chat and record completion in the PR body; clear the visual-delivery hold only after both required destinations are verified.
Agent review details

Security

None.

PR surface

Source +259, Tests +586. Total +845 across 26 files.

View PR surface stats
Area Files Added Removed Net
Source 14 365 106 +259
Tests 12 767 181 +586
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 26 1132 287 +845

Review metrics

Metric Value Why it matters
Net production versus test growth Production +259 lines; tests and test support +586 lines Production growth implements foreground scheduling and scoped reuse within the existing owner; most added coverage protects ordering and invalidation.
Current-head browser evidence 1 held-request test; 5 paired benchmark repetitions The held requests demonstrate independence from startup and replacement responses; benchmark samples supplement that proof without isolating this PR's performance contribution.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Keep foreground selection and temporary loaded-list presentation within the existing roster owner, preserving its scope, invalidation, and stale-response fences.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Keep foreground selection and temporary loaded-list presentation within the existing roster owner, preserving its scope, invalidation, and stale-response fences.

Do we have a high-confidence way to reproduce the issue?

Yes: inspected main queues agent-selection refresh behind background admission, and the held-startup/held-list browser scenario directly exercises that boundary. This read-only review did not execute a new reproduction.

Is this the best way to solve the issue?

Yes: the patch extends the existing roster owner, preserves automatic startup priority, and keeps reusable presentation separate from authoritative state.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 307255794c48.

Labels

Label changes:

  • remove proof: 📸 screenshot: Current real behavior proof evidence kind is linked_artifact.

Label justifications:

  • P2: This fixes avoidable sidebar waiting during agent navigation without evidence of an emergency or unusable core workflow.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (linked_artifact): The exact-head Chromium run exercises the rendered agent picker and roster owner against a synthetic Gateway, showing Writer rows before startup completes and warm Main rows before replacement data arrives. The complete source-bound benchmark adds observed timings; historical screenshots retain their original identity. The separate originating-chat screenshot-delivery gate remains open.
  • proof: sufficient: Contributor real behavior proof is sufficient. The exact-head Chromium run exercises the rendered agent picker and roster owner against a synthetic Gateway, showing Writer rows before startup completes and warm Main rows before replacement data arrives. The complete source-bound benchmark adds observed timings; historical screenshots retain their original identity. The separate originating-chat screenshot-delivery gate remains open.

Evidence

What I checked:

  • Pinned source and clean checkout: The checkout matches the reviewed head and reported benchmark tree: d6b040f, tree 941389b6412836e096875b434fd65784c6cac56e. Final git status remained clean. Review used the pinned introduced delta, not the stale test-merge result. (d6b040f3e5bd)
  • Foreground selection and scoped reuse: Explicit selection supersedes the old request's publication generation and starts the selected roster without background admission. Warm presentation remains in the existing managed-list owner, checks connection epoch and query identity, and retires on invalidation. These changes add no persistent format, public plugin API, or authorization grant. (ui/src/lib/sessions/session-roster-refresh.ts:635, d6b040f3e5bd)
  • Delayed-history safeguards: Defaults-only admission retains connection and deletion-generation checks while preventing stale descriptor publication; the chat consumer preserves the current row and skips stale descriptor/run-state updates. The focused scoped-history suite retains the prior controls and adds prestarted-history coverage. (ui/src/lib/sessions/session-reconciliation.ts:225, d6b040f3e5bd)
  • Current-head browser behavior: fix: agent switching leaves the session list waiting #150092 (comment) reports one passing Chromium test at the exact head. The inspected test selects Writer while chat.startup is deferred, then returns to Main while its replacement sessions.list response is deferred, asserting matching rows and absence of the other agent's rows. This is rendered Control UI proof against a synthetic Gateway, not deployed-Gateway performance. (ui/src/e2e/agent-switch-roster.e2e.test.ts:56, d6b040f3e5bd)
  • Complete benchmark evidence inspected: Read the complete comment, including all samples and the reproduction harness, without executing it: fix: agent switching leaves the session list waiting #150092 (comment). Its SHA-256 matches the captured source identity ae790609cda9290bb08b5bd551a487e1caade4b3833927407ace196445df5da5. Five paired repetitions report cold medians of 405.9→149.8 ms and warm medians of 160.5→113.7 ms. The older baseline does not isolate this PR's contribution, and the report appropriately disclaims production-latency conclusions. (d6b040f3e5bd)
  • CI identity verified: GitHub reports run 35159077780 completed successfully with head_sha equal to the pinned PR head: https://github.com/openclaw/openclaw/actions/runs/35159077780. This supersedes the earlier current-head CI uncertainty. (d6b040f3e5bd)

Likely related people:

  • jalehman: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (6 earlier review cycles)
  • reviewed 2026-09-16T13:59:42.274Z sha 114bfa5 :: blocked before merge. :: none
  • reviewed 2026-09-16T14:14:59.195Z sha 114bfa5 :: blocked before merge. :: none
  • reviewed 2026-09-16T20:20:34.324Z sha adb125973be693e24780a9b451a37681d593601d :: blocked before merge. :: none
  • reviewed 2026-09-16T20:31:12.266Z sha 9ad4cc5 :: blocked before merge. :: none
  • reviewed 2026-09-16T20:49:47.450Z sha faf9e5c :: blocked before merge. :: none
  • reviewed 2026-09-16T22:50:44.689Z sha d6b040f :: blocked before merge. :: none

@jalehman

Copy link
Copy Markdown
Contributor Author

Agent-switch benchmark: raw samples and reproduction harness

Publication-time PR head: 114bfa58bcc28ad1dbbf4f347cf0c0e665dd7aa4. The existing PR evidence identifies this as the rebased candidate. These are the retained before and rebased measurement files, not a new execution. The JSON files themselves do not embed Git SHAs; baseline commit provenance and independent candidate/run binding remain to be attached. Do not interpret the stage name alone as exact-head proof.

Measurement and controls

Synthetic browser fixture, not production latency: 200 sessions per agent; sessions.list responses scheduled with the same 150 ms delay; first Writer chat.startup held for 600 ms; five fresh browser contexts per stage; Main initially loaded, then Writer cold switch, then Main warm return. Both stages use the same recorded fixture parameters. Harness uses Chromium, 1440×900 viewport, en-US locale and source-mode Control UI. Browser/version and machine-load equality were not recorded in these JSON files and are not claimed here.

firstRows measures elapsed browser performance.now() from the captured picker click to the first matching visible sidebar row observed by MutationObserver (or the queued observation). It is DOM visibility, not a compositor-paint timestamp. Cold = first Writer selection; warm = return to already-loaded Main. Request dispatch and response times are recorded separately. The p95 below is the nearest-rank statistic of only five samples (therefore the maximum); it is not a reliable population-tail estimate.

Case Before median ms Rebased median ms Before five-sample p95 ms Rebased five-sample p95 ms
Cold Writer 852.4 309.0 899.5 331.4
Warm Main return 287.4 36.6 356.9 55.7

Every sample (milliseconds)

Stage Run Selection First visible rows List dispatch List response
before 1 writer 899.5 648.9 801.8
before 1 main 356.9 94.6 278.2
before 2 writer 841.1 641.0 791.1
before 2 main 270.7 82.2 232.4
before 3 writer 851.9 649.1 799.4
before 3 main 306.3 112.9 263.1
before 4 writer 852.4 635.8 786.1
before 4 main 257.6 69.3 219.5
before 5 writer 886.6 656.1 806.3
before 5 main 287.4 95.7 245.9
rebased 1 writer 281.3 60.3 217.6
rebased 1 main 36.6 107.1 257.3
rebased 2 writer 323.7 44.2 234.6
rebased 2 main 32.7 176.9 327.0
rebased 3 writer 279.4 43.4 212.7
rebased 3 main 31.9 173.2 323.3
rebased 4 writer 331.4 47.4 245.8
rebased 4 main 42.3 143.4 293.5
rebased 5 writer 309.0 68.7 249.3
rebased 5 main 55.7 136.0 301.6

Each measured selection recorded exactly one primary list dispatch and response. Rebased cold rows arrive before the 600 ms transcript release; rebased warm rows arrive before the replacement list response. This establishes the synthetic timing behavior, not a real-Gateway acceptance result.

Reproduction

Save the harness below as .artifacts/agent-switch-measure.mts in each identified revision checkout with its repository-approved dependencies and Chromium already available. The harness imports repository test helpers and writes measurements, screenshots and first-run video under the Control UI E2E artifact directory. Invocation below is supplied for reproduction; it was not rerun during this publication. No dependency installation or version changes are implied.

PROOF_STAGE=before pnpm exec tsx .artifacts/agent-switch-measure.mts
# In the candidate checkout:
PROOF_STAGE=rebased pnpm exec tsx .artifacts/agent-switch-measure.mts
Complete measurement harness
import { writeFile } from 'node:fs/promises';
import path from 'node:path';
import { chromium } from 'playwright';
import { startControlUiE2eServer, installMockGateway, resolvePlaywrightChromiumExecutablePath } from '../ui/src/test-helpers/control-ui-e2e.ts';
import { createControlUiE2eArtifactDir } from '../ui/src/test-helpers/control-ui-e2e-artifacts.ts';
import { createControlUiSessionRow } from '../ui/src/test-helpers/control-ui-session-fixtures.ts';
const stage = process.env.PROOF_STAGE || 'before';
const dir = createControlUiE2eArtifactDir(`agent-switch-measure-${stage}`);
const server = await startControlUiE2eServer(undefined, { source: true });
const browser = await chromium.launch({ executablePath: resolvePlaywrightChromiumExecutablePath(chromium.executablePath()) });
const rows = ['main', 'writer'].flatMap(agent => Array.from({ length: 200 }, (_, i) => createControlUiSessionRow(`agent:${agent}:${i === 0 ? 'main' : `dashboard:item-${i}`}`, `${agent === 'main' ? 'Main' : 'Writer'} project ${String(i).padStart(3, '0')}`, 1789540000000 - i * 1000, { agentId: agent })));
const samples: any[] = [];
try {
  for (let run = 0; run < 5; run++) {
    const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'en-US', ...(run === 0 ? { recordVideo: { dir, size: { width: 1440, height: 900 } } } : {}) });
    const page = await context.newPage();
    page.setDefaultTimeout(20000);
    // tsx names serialized fixture callbacks using this compile-time helper.
    await page.addInitScript('globalThis.__name = (target) => target;');
    try {
      await installMockGateway(page, { sessions: rows, historyMessages: [{ role: 'assistant', content: 'Synthetic baseline conversation.' }], methodResponses: { 'agents.list': { defaultId: 'main', mainKey: 'main', scope: 'per-sender', agents: [{ id: 'main', name: 'Main' }, { id: 'writer', name: 'Writer' }] } } });
      await page.goto(`${server.baseUrl}chat/main`);
      await page.locator('[data-session-key="agent:main:dashboard:item-1"]').first().waitFor();
      await page.evaluate((fixtureRows) => {
        const w = window as any;
        const gateway = w.openclawControlUiE2eGateway;
        w.measurements = [];
        const observe = () => {
          const measurement = w.measurements.at(-1);
          if (!measurement || measurement.firstRows !== undefined) return;
          const row = document.querySelector(`openclaw-app-sidebar [data-session-key="agent:${measurement.agentId}:dashboard:item-1"]`) as HTMLElement;
          if (row?.getClientRects().length) measurement.firstRows = performance.now() - measurement.click;
        };
        new MutationObserver(observe).observe(document.body, { subtree: true, childList: true, attributes: true });
        document.addEventListener('click', event => {
          const option = event.composedPath().find((node: any) => node?.matches?.('.sidebar-agent-menu__agent-switch')) as HTMLElement | undefined;
          if (!option) return;
          const agentId = option.getAttribute('value')?.slice('agent:'.length);
          if (!agentId) return;
          const measurement: any = { agentId, click: performance.now(), dispatch: [], response: [] };
          w.measurements.push(measurement);
          // A deterministic server delay for the cold transcript. Warm return retains its real pane.
          if (agentId === 'writer' && w.measurements.length === 1) {
            gateway.deferNext('chat.startup');
            setTimeout(() => { measurement.historyRelease = performance.now() - measurement.click; gateway.resolveDeferred('chat.startup'); }, 600);
          }
          queueMicrotask(observe);
        }, true);
        gateway.setRequestHandler('sessions.list', ({ params, respond }: any) => {
          const primary = !params.hasBoard && !params.spawnedBy && !params.archived;
          const measurement = w.measurements.at(-1);
          if (primary && measurement) measurement.dispatch.push({ agentId: params.agentId, ms: performance.now() - measurement.click });
          const sessions = primary ? fixtureRows.filter(row => row.agentId === params.agentId) : [];
          setTimeout(() => {
            if (primary && measurement) measurement.response.push({ agentId: params.agentId, ms: performance.now() - measurement.click });
            respond({ ts: Date.now(), count: sessions.length, sessions, defaults: { model: 'gpt-5.5', modelProvider: 'openai', contextTokens: null }, hasMore: false, nextOffset: null });
          }, 150);
        });
      }, rows);
      for (const [index, agent] of ['writer', 'main'].entries()) {
        const sidebar = page.locator('openclaw-app-sidebar');
        await sidebar.getByRole('button', { name: /Switch agent/ }).click();
        await sidebar.locator(`wa-dropdown-item[value="agent:${agent}"]`).click();
        if (run === 0) await page.screenshot({ path: path.join(dir, `${index * 2 + 1}-${agent}-selected.png`) });
        await page.waitForFunction((id) => {
          const m = (window as any).measurements.at(-1);
          return m?.agentId === id && m.firstRows !== undefined && m.response.length > 0 && (id !== 'writer' || m.historyRelease !== undefined);
        }, agent);
        await page.locator(`[data-session-key="agent:${agent}:dashboard:item-1"]`).first().waitFor();
        if (run === 0) await page.screenshot({ path: path.join(dir, `${index * 2 + 2}-${agent}-loaded.png`) });
      }
      samples.push({ run, measurements: await page.evaluate(() => (window as any).measurements) });
    } catch (error) {
      await page.screenshot({ path: path.join(dir, `failure-${run}.png`) }).catch(() => {});
      throw error;
    } finally { await context.close(); }
  }
  const summary = Object.fromEntries(['writer', 'main'].map(agentId => {
    const values = samples.flatMap(s => s.measurements).filter(m => m.agentId === agentId).map(m => m.firstRows).sort((a, b) => a - b);
    return [agentId === 'writer' ? 'coldSwitch' : 'warmReturn', { samples: values.length, medianMs: values[Math.floor(values.length / 2)], p95Ms: values[Math.ceil(values.length * .95) - 1] }];
  }));
  await writeFile(path.join(dir, 'measurements.json'), JSON.stringify({ stage, fixture: { rowsPerAgent: 200, listDelayMs: 150, coldHistoryDelayMs: 600, repeats: 5 }, summary, samples }, null, 2));
  console.log(JSON.stringify({ dir, summary }, null, 2));
} finally { await browser.close(); await server.close(); }
Unrounded original measurement JSON
{
  "before": {
    "stage": "before",
    "fixture": {
      "rowsPerAgent": 200,
      "listDelayMs": 150,
      "coldHistoryDelayMs": 600,
      "repeats": 5
    },
    "summary": {
      "coldSwitch": {
        "samples": 5,
        "medianMs": 852.4000000953674,
        "p95Ms": 899.5
      },
      "warmReturn": {
        "samples": 5,
        "medianMs": 287.39999985694885,
        "p95Ms": 356.89999985694885
      }
    },
    "samples": [
      {
        "run": 0,
        "measurements": [
          {
            "agentId": "writer",
            "click": 5716.200000047684,
            "dispatch": [
              {
                "agentId": "writer",
                "ms": 648.8999998569489
              }
            ],
            "response": [
              {
                "agentId": "writer",
                "ms": 801.7999999523163
              }
            ],
            "historyRelease": 600.2999999523163,
            "firstRows": 899.5
          },
          {
            "agentId": "main",
            "click": 7223.5,
            "dispatch": [
              {
                "agentId": "main",
                "ms": 94.59999990463257
              }
            ],
            "response": [
              {
                "agentId": "main",
                "ms": 278.2000000476837
              }
            ],
            "firstRows": 356.89999985694885
          }
        ]
      },
      {
        "run": 1,
        "measurements": [
          {
            "agentId": "writer",
            "click": 4104.799999952316,
            "dispatch": [
              {
                "agentId": "writer",
                "ms": 641
              }
            ],
            "response": [
              {
                "agentId": "writer",
                "ms": 791.1000001430511
              }
            ],
            "historyRelease": 600.1000001430511,
            "firstRows": 841.1000001430511
          },
          {
            "agentId": "main",
            "click": 5201.799999952316,
            "dispatch": [
              {
                "agentId": "main",
                "ms": 82.20000004768372
              }
            ],
            "response": [
              {
                "agentId": "main",
                "ms": 232.40000009536743
              }
            ],
            "firstRows": 270.7000000476837
          }
        ]
      },
      {
        "run": 2,
        "measurements": [
          {
            "agentId": "writer",
            "click": 3937.5999999046326,
            "dispatch": [
              {
                "agentId": "writer",
                "ms": 649.1000001430511
              }
            ],
            "response": [
              {
                "agentId": "writer",
                "ms": 799.4000000953674
              }
            ],
            "historyRelease": 600.4000000953674,
            "firstRows": 851.9000000953674
          },
          {
            "agentId": "main",
            "click": 5133,
            "dispatch": [
              {
                "agentId": "main",
                "ms": 112.89999985694885
              }
            ],
            "response": [
              {
                "agentId": "main",
                "ms": 263.09999990463257
              }
            ],
            "firstRows": 306.2999999523163
          }
        ]
      },
      {
        "run": 3,
        "measurements": [
          {
            "agentId": "writer",
            "click": 3767.5,
            "dispatch": [
              {
                "agentId": "writer",
                "ms": 635.7999999523163
              }
            ],
            "response": [
              {
                "agentId": "writer",
                "ms": 786.1000001430511
              }
            ],
            "historyRelease": 600.2999999523163,
            "firstRows": 852.4000000953674
          },
          {
            "agentId": "main",
            "click": 4907,
            "dispatch": [
              {
                "agentId": "main",
                "ms": 69.29999995231628
              }
            ],
            "response": [
              {
                "agentId": "main",
                "ms": 219.5
              }
            ],
            "firstRows": 257.60000014305115
          }
        ]
      },
      {
        "run": 4,
        "measurements": [
          {
            "agentId": "writer",
            "click": 2958.2000000476837,
            "dispatch": [
              {
                "agentId": "writer",
                "ms": 656.0999999046326
              }
            ],
            "response": [
              {
                "agentId": "writer",
                "ms": 806.2999999523163
              }
            ],
            "historyRelease": 600.2999999523163,
            "firstRows": 886.5999999046326
          },
          {
            "agentId": "main",
            "click": 4170.600000143051,
            "dispatch": [
              {
                "agentId": "main",
                "ms": 95.69999980926514
              }
            ],
            "response": [
              {
                "agentId": "main",
                "ms": 245.89999985694885
              }
            ],
            "firstRows": 287.39999985694885
          }
        ]
      }
    ]
  },
  "rebased": {
    "stage": "rebased",
    "fixture": {
      "rowsPerAgent": 200,
      "listDelayMs": 150,
      "coldHistoryDelayMs": 600,
      "repeats": 5
    },
    "summary": {
      "coldSwitch": {
        "samples": 5,
        "medianMs": 309,
        "p95Ms": 331.40000009536743
      },
      "warmReturn": {
        "samples": 5,
        "medianMs": 36.59999990463257,
        "p95Ms": 55.700000047683716
      }
    },
    "samples": [
      {
        "run": 0,
        "measurements": [
          {
            "agentId": "writer",
            "click": 4627.700000047684,
            "dispatch": [
              {
                "agentId": "writer",
                "ms": 60.299999952316284
              }
            ],
            "response": [
              {
                "agentId": "writer",
                "ms": 217.59999990463257
              }
            ],
            "firstRows": 281.2999999523163,
            "historyRelease": 600.2000000476837
          },
          {
            "agentId": "main",
            "click": 5681.900000095367,
            "dispatch": [
              {
                "agentId": "main",
                "ms": 107.09999990463257
              }
            ],
            "response": [
              {
                "agentId": "main",
                "ms": 257.2999999523163
              }
            ],
            "firstRows": 36.59999990463257
          }
        ]
      },
      {
        "run": 1,
        "measurements": [
          {
            "agentId": "writer",
            "click": 2435.9000000953674,
            "dispatch": [
              {
                "agentId": "writer",
                "ms": 44.200000047683716
              }
            ],
            "response": [
              {
                "agentId": "writer",
                "ms": 234.59999990463257
              }
            ],
            "firstRows": 323.7000000476837,
            "historyRelease": 600.2000000476837
          },
          {
            "agentId": "main",
            "click": 3352.100000143051,
            "dispatch": [
              {
                "agentId": "main",
                "ms": 176.89999985694885
              }
            ],
            "response": [
              {
                "agentId": "main",
                "ms": 327
              }
            ],
            "firstRows": 32.700000047683716
          }
        ]
      },
      {
        "run": 2,
        "measurements": [
          {
            "agentId": "writer",
            "click": 2409.4000000953674,
            "dispatch": [
              {
                "agentId": "writer",
                "ms": 43.39999985694885
              }
            ],
            "response": [
              {
                "agentId": "writer",
                "ms": 212.70000004768372
              }
            ],
            "firstRows": 279.39999985694885,
            "historyRelease": 600.2000000476837
          },
          {
            "agentId": "main",
            "click": 3368,
            "dispatch": [
              {
                "agentId": "main",
                "ms": 173.20000004768372
              }
            ],
            "response": [
              {
                "agentId": "main",
                "ms": 323.2999999523163
              }
            ],
            "firstRows": 31.90000009536743
          }
        ]
      },
      {
        "run": 3,
        "measurements": [
          {
            "agentId": "writer",
            "click": 2935.699999809265,
            "dispatch": [
              {
                "agentId": "writer",
                "ms": 47.40000009536743
              }
            ],
            "response": [
              {
                "agentId": "writer",
                "ms": 245.80000019073486
              }
            ],
            "firstRows": 331.40000009536743,
            "historyRelease": 600.2000000476837
          },
          {
            "agentId": "main",
            "click": 3738.199999809265,
            "dispatch": [
              {
                "agentId": "main",
                "ms": 143.40000009536743
              }
            ],
            "response": [
              {
                "agentId": "main",
                "ms": 293.5
              }
            ],
            "firstRows": 42.30000019073486
          }
        ]
      },
      {
        "run": 4,
        "measurements": [
          {
            "agentId": "writer",
            "click": 3166.9000000953674,
            "dispatch": [
              {
                "agentId": "writer",
                "ms": 68.69999980926514
              }
            ],
            "response": [
              {
                "agentId": "writer",
                "ms": 249.29999995231628
              }
            ],
            "firstRows": 309,
            "historyRelease": 600.1999998092651
          },
          {
            "agentId": "main",
            "click": 3986,
            "dispatch": [
              {
                "agentId": "main",
                "ms": 136
              }
            ],
            "response": [
              {
                "agentId": "main",
                "ms": 301.59999990463257
              }
            ],
            "firstRows": 55.700000047683716
          }
        ]
      }
    ]
  }
}

Remaining proof gaps

  • Exact baseline SHA and independently verified candidate/source-equivalence binding for these retained runs.
  • Before/after images rendered directly in this PR and originating chat. No image delivery is claimed by this textual comment.
  • UI typecheck / broader changed-file validation and current-head CI acceptance.
  • The PR body reports 65 files / 1,040 passing session tests and bundled-browser proof; those statements are not independently revalidated by this benchmark publication.
  • Draft/no-merge hold remains.

@jalehman

Copy link
Copy Markdown
Contributor Author

Before / after: selected agent's rows while chat startup is held

Inspected screenshots contain synthetic conversations and project names, no visible credentials or private conversations. These are different fixture captures demonstrating behavior, not matched-frame timing measurements. Held-request conditions are established by the harness/test, not by the static pixels alone.

Before — Writer selected, sidebar empty while startup is held

Before: Writer selected but session sidebar empty while startup is held

After — Writer rows visible before held startup is released

After: Writer project rows visible before held startup completes

Candidate recorded by the retained rebased proof: 114bfa58bcc28ad1dbbf4f347cf0c0e665dd7aa4. Baseline investigation records 027f99d61a931508e7c76dfdc19214025012ac15; complete run-to-revision provenance remains under verification. The retained bundled browser log reports one passing held-request test, and session-suite log reports 65 files / 1,040 passing tests. This upload is not a new test execution.

Five-run synthetic benchmark

Selection Before median Rebased median
Cold Writer switch 852.4 ms 309.0 ms
Warm Main return 287.4 ms 36.6 ms

200 rows per agent; 150 ms list delay; 600 ms cold startup hold. DOM visibility from picker click, not compositor paint. All samples, raw JSON, controls, limitations and complete reproduction harness.

With the linked harness saved in each verified revision checkout:

PROOF_STAGE=before pnpm exec tsx .artifacts/agent-switch-measure.mts
PROOF_STAGE=rebased pnpm exec tsx .artifacts/agent-switch-measure.mts

Typecheck/changed-file validation, full CI acceptance, complete provenance and originating-chat image-render confirmation remain open. PR remains draft; no merge authorization.

@jalehman

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Same head 114bfa58bcc28ad1dbbf4f347cf0c0e665dd7aa4; new proof is now linked from the PR body. Before/after screenshots are uploaded directly to the PR and browser-verified: #150092 (comment) . All five-run samples and reproduction harness: #150092 (comment) . Please reassess the updated evidence. Typecheck/changed-file validation, originating-chat render confirmation and full provenance remain open; this is not a clearance claim or merge request.

@clawsweeper

clawsweeper Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@jalehman

Copy link
Copy Markdown
Contributor Author

Matched agent-switch video proof — five repetitions, normal speed

These are actual Chromium recordings, not generated video. There are five paired repetitions, each recorded as its original separate video: cold Main → Writer, then warm Writer → Main. No playback speed changes or injected network/RPC delays. The visible clock resets at the agent-switch click event; it stops at the first animation frame with the target row visible and hit-testable.

Boundary: synthetic/mocked Gateway, source-mode UI on the same shared Linux host, 200 sessions per agent, 1440×900 viewport, same fixture and browser. This is not live-Gateway performance or a production-bundle benchmark. Source-module compilation is warmed before each side; each measured repetition starts with a fresh browser context. Run order alternates AB/BA. Readability pauses occur only between actions and after measurement. The players are separate, not frame-synchronized; compare the common click-relative clocks, not player position. Shared-host CPU scheduling is not controlled.

Sources: baseline 82d4d1cc175549e222e3cb2605716f277eff6a00; candidate 114bfa58bcc28ad1dbbf4f347cf0c0e665dd7aa4 plus the current, uncommitted repair patch SHA-256 5003808d356e3257afa55001e47495289f2dd7a85801424d3b648bce5c009159. This is explicitly the working candidate, not a claim that the published PR head alone produced these numbers. Both UI/shared-source snapshot hashes and the candidate patch hash were rechecked after capture. The candidate remains under repair; this evidence does not clear CI/review or the independent chat-defaults regression.

The ten original clips below are ordered before-run-1, after-run-1, then the same pair for runs 2 through 5. Each has BEFORE/AFTER and repetition labels in the recording. All takes are included, without concatenation, cuts, retiming, or re-encoding.

Observed click-to-usable-row times (milliseconds)

Case Baseline median [min–max] Candidate median [min–max] Baseline / candidate standard deviation
Cold switch 526.8 [404.5–611.6] 144.5 [132.7–252.1] 69.7 / 44.4
Warm return 245.0 [210.7–293.3] 159.2 [107.3–194.7] 26.7 / 28.6

These samples replace neither production measurements nor the earlier deliberately delayed fixture. Their timing definition differs from the earlier DOM-mutation benchmark. No take was dropped.

Complete measurements and capture conditions
{
  "manifest": {
    "baseline": "82d4d1cc175549e222e3cb2605716f277eff6a00",
    "candidateHead": "114bfa58bcc28ad1dbbf4f347cf0c0e665dd7aa4",
    "candidatePatchSha256": "5003808d356e3257afa55001e47495289f2dd7a85801424d3b648bce5c009159"
  },
  "conditions": {
    "boundary": "mocked Gateway, source-mode UI",
    "browser": "153.0.8010.12",
    "platform": "linux",
    "arch": "x64",
    "cpu": "Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz",
    "viewport": "1440x900",
    "rowsPerAgent": 200,
    "repetitions": 5,
    "order": "AB, BA, AB, BA, AB",
    "rpcDelayMs": 0,
    "network": "loopback; no throttling",
    "timing": "capture-phase agent-switch click event to first animation frame with visible hit-testable item-1 row",
    "betweenActionReadabilityPausesMs": [
      1000,
      1500
    ]
  },
  "summary": {
    "before": {
      "writer": {
        "n": 5,
        "min": 404.5,
        "median": 526.7999999523163,
        "max": 611.5999999046326,
        "mean": 512.5999999523162,
        "sd": 69.73507007817449,
        "samples": [
          404.5,
          473.89999985694885,
          526.7999999523163,
          546.2000000476837,
          611.5999999046326
        ]
      },
      "main": {
        "n": 5,
        "min": 210.70000004768372,
        "median": 245,
        "max": 293.2999999523163,
        "mean": 247.5199999809265,
        "sd": 26.714744969827954,
        "samples": [
          210.70000004768372,
          237.59999990463257,
          245,
          251,
          293.2999999523163
        ]
      }
    },
    "after": {
      "writer": {
        "n": 5,
        "min": 132.69999980926514,
        "median": 144.5,
        "max": 252.09999990463257,
        "mean": 169.97999992370606,
        "sd": 44.40844062192535,
        "samples": [
          132.69999980926514,
          139.20000004768372,
          144.5,
          181.39999985694885,
          252.09999990463257
        ]
      },
      "main": {
        "n": 5,
        "min": 107.29999995231628,
        "median": 159.20000004768372,
        "max": 194.70000004768372,
        "mean": 153.2,
        "sd": 28.56053224969894,
        "samples": [
          107.29999995231628,
          142.09999990463257,
          159.20000004768372,
          162.70000004768372,
          194.70000004768372
        ]
      }
    }
  },
  "samples": [
    {
      "run": 0,
      "stage": "before",
      "measurements": [
        {
          "agentId": "writer",
          "click": 4496.800000190735,
          "dispatch": [
            {
              "agentId": "writer",
              "ms": 391
            }
          ],
          "response": [
            {
              "agentId": "writer",
              "ms": 391.5
            }
          ],
          "usableMs": 473.89999985694885
        },
        {
          "agentId": "main",
          "click": 7748.700000047684,
          "dispatch": [
            {
              "agentId": "main",
              "ms": 129
            }
          ],
          "response": [
            {
              "agentId": "main",
              "ms": 129.70000004768372
            }
          ],
          "usableMs": 293.2999999523163
        }
      ]
    },
    {
      "run": 0,
      "stage": "after",
      "measurements": [
        {
          "agentId": "writer",
          "click": 3963.2000000476837,
          "dispatch": [
            {
              "agentId": "writer",
              "ms": 66.79999995231628
            }
          ],
          "response": [
            {
              "agentId": "writer",
              "ms": 67.40000009536743
            }
          ],
          "usableMs": 144.5
        },
        {
          "agentId": "main",
          "click": 6987,
          "dispatch": [
            {
              "agentId": "main",
              "ms": 114.20000004768372
            }
          ],
          "response": [
            {
              "agentId": "main",
              "ms": 114.70000004768372
            }
          ],
          "usableMs": 107.29999995231628
        }
      ]
    },
    {
      "run": 1,
      "stage": "after",
      "measurements": [
        {
          "agentId": "writer",
          "click": 3941.5,
          "dispatch": [
            {
              "agentId": "writer",
              "ms": 55.69999980926514
            }
          ],
          "response": [
            {
              "agentId": "writer",
              "ms": 56
            }
          ],
          "usableMs": 132.69999980926514
        },
        {
          "agentId": "main",
          "click": 7027.299999952316,
          "dispatch": [
            {
              "agentId": "main",
              "ms": 150.5
            }
          ],
          "response": [
            {
              "agentId": "main",
              "ms": 151
            }
          ],
          "usableMs": 142.09999990463257
        }
      ]
    },
    {
      "run": 1,
      "stage": "before",
      "measurements": [
        {
          "agentId": "writer",
          "click": 5302.200000047684,
          "dispatch": [
            {
              "agentId": "writer",
              "ms": 479.19999980926514
            }
          ],
          "response": [
            {
              "agentId": "writer",
              "ms": 479.7999999523163
            }
          ],
          "usableMs": 611.5999999046326
        },
        {
          "agentId": "main",
          "click": 8783.099999904633,
          "dispatch": [
            {
              "agentId": "main",
              "ms": 91.40000009536743
            }
          ],
          "response": [
            {
              "agentId": "main",
              "ms": 91.90000009536743
            }
          ],
          "usableMs": 210.70000004768372
        }
      ]
    },
    {
      "run": 2,
      "stage": "before",
      "measurements": [
        {
          "agentId": "writer",
          "click": 4857.899999856949,
          "dispatch": [
            {
              "agentId": "writer",
              "ms": 448.5
            }
          ],
          "response": [
            {
              "agentId": "writer",
              "ms": 449.2000000476837
            }
          ],
          "usableMs": 546.2000000476837
        },
        {
          "agentId": "main",
          "click": 8020.200000047684,
          "dispatch": [
            {
              "agentId": "main",
              "ms": 116.59999990463257
            }
          ],
          "response": [
            {
              "agentId": "main",
              "ms": 117.39999985694885
            }
          ],
          "usableMs": 251
        }
      ]
    },
    {
      "run": 2,
      "stage": "after",
      "measurements": [
        {
          "agentId": "writer",
          "click": 4497.799999952316,
          "dispatch": [
            {
              "agentId": "writer",
              "ms": 102.09999990463257
            }
          ],
          "response": [
            {
              "agentId": "writer",
              "ms": 102.5
            }
          ],
          "usableMs": 252.09999990463257
        },
        {
          "agentId": "main",
          "click": 7654.599999904633,
          "dispatch": [
            {
              "agentId": "main",
              "ms": 172
            }
          ],
          "response": [
            {
              "agentId": "main",
              "ms": 172.79999995231628
            }
          ],
          "usableMs": 162.70000004768372
        }
      ]
    },
    {
      "run": 3,
      "stage": "after",
      "measurements": [
        {
          "agentId": "writer",
          "click": 4085.5,
          "dispatch": [
            {
              "agentId": "writer",
              "ms": 58.30000019073486
            }
          ],
          "response": [
            {
              "agentId": "writer",
              "ms": 58.700000047683716
            }
          ],
          "usableMs": 139.20000004768372
        },
        {
          "agentId": "main",
          "click": 7024,
          "dispatch": [
            {
              "agentId": "main",
              "ms": 203.20000004768372
            }
          ],
          "response": [
            {
              "agentId": "main",
              "ms": 203.70000004768372
            }
          ],
          "usableMs": 194.70000004768372
        }
      ]
    },
    {
      "run": 3,
      "stage": "before",
      "measurements": [
        {
          "agentId": "writer",
          "click": 4170.100000143051,
          "dispatch": [
            {
              "agentId": "writer",
              "ms": 402.7999999523163
            }
          ],
          "response": [
            {
              "agentId": "writer",
              "ms": 403.2999999523163
            }
          ],
          "usableMs": 526.7999999523163
        },
        {
          "agentId": "main",
          "click": 7307.799999952316,
          "dispatch": [
            {
              "agentId": "main",
              "ms": 112.10000014305115
            }
          ],
          "response": [
            {
              "agentId": "main",
              "ms": 112.70000004768372
            }
          ],
          "usableMs": 245
        }
      ]
    },
    {
      "run": 4,
      "stage": "before",
      "measurements": [
        {
          "agentId": "writer",
          "click": 4529.900000095367,
          "dispatch": [
            {
              "agentId": "writer",
              "ms": 330.09999990463257
            }
          ],
          "response": [
            {
              "agentId": "writer",
              "ms": 330.39999985694885
            }
          ],
          "usableMs": 404.5
        },
        {
          "agentId": "main",
          "click": 7720.400000095367,
          "dispatch": [
            {
              "agentId": "main",
              "ms": 100.20000004768372
            }
          ],
          "response": [
            {
              "agentId": "main",
              "ms": 100.79999995231628
            }
          ],
          "usableMs": 237.59999990463257
        }
      ]
    },
    {
      "run": 4,
      "stage": "after",
      "measurements": [
        {
          "agentId": "writer",
          "click": 3978.5,
          "dispatch": [
            {
              "agentId": "writer",
              "ms": 85.59999990463257
            }
          ],
          "response": [
            {
              "agentId": "writer",
              "ms": 86.20000004768372
            }
          ],
          "usableMs": 181.39999985694885
        },
        {
          "agentId": "main",
          "click": 7082.099999904633,
          "dispatch": [
            {
              "agentId": "main",
              "ms": 170
            }
          ],
          "response": [
            {
              "agentId": "main",
              "ms": 170.5
            }
          ],
          "usableMs": 159.20000004768372
        }
      ]
    }
  ]
}
Reproduction harness

Run node --import tsx .artifacts/agent-switch-video-proof/record.mts against the documented immutable source snapshots with the existing repository dependencies. The installed minimal encoder does not support the requested concat option, so the original unedited WebM recordings are attached instead. No retiming filter is used. Snapshot manifest, candidate patch, original per-run videos and full logs are retained in .artifacts/agent-switch-video-proof/.

import { writeFile, readFile, mkdir } from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import { chromium } from 'playwright';
const root = path.dirname(new URL(import.meta.url).pathname);
const manifest = JSON.parse(await readFile(path.join(root, 'source-manifest.json'), 'utf8'));
const helpers = Object.fromEntries(await Promise.all(['before','after'].map(async stage => [stage, await import(path.join(root,stage,'ui/src/test-helpers/control-ui-e2e.ts'))])));
const { createControlUiSessionRow } = await import(path.join(root,'after/ui/src/test-helpers/control-ui-session-fixtures.ts'));
const rows = ['main','writer'].flatMap(agent => Array.from({length:200},(_,i) => createControlUiSessionRow(`agent:${agent}:${i===0?'main':`dashboard:item-${i}`}`, `${agent==='main'?'Main':'Writer'} project ${String(i).padStart(3,'0')}`,1789540000000-i*1000,{agentId:agent})));
const servers:any = {}; const samples:any[]=[];
const browser = await chromium.launch({executablePath:helpers.after.resolvePlaywrightChromiumExecutablePath(chromium.executablePath())});
async function install(page:any, stage:string) {
  await page.addInitScript('globalThis.__name = (target) => target;');
  await helpers[stage].installMockGateway(page,{sessions:rows,historyMessages:[{role:'assistant',content:'Synthetic matched browser performance fixture.'}],methodResponses:{'agents.list':{defaultId:'main',mainKey:'main',scope:'per-sender',agents:[{id:'main',name:'Main'},{id:'writer',name:'Writer'}]}}});
  await page.goto(`${servers[stage].baseUrl}chat/main`);
  await page.locator('openclaw-app-sidebar [data-session-key="agent:main:dashboard:item-1"]').first().waitFor();
}
try {
 for(const stage of ['before','after']) {
  servers[stage]=await helpers[stage].startControlUiE2eServer(undefined,{source:true});
  const context=await browser.newContext({viewport:{width:1440,height:900},locale:'en-US'});
  const page=await context.newPage(); await install(page,stage);
  // Prime source-module compilation outside the recorded fresh contexts.
  const sidebar=page.locator('openclaw-app-sidebar');
  await sidebar.getByRole('button',{name:/Switch agent/}).click();
  await sidebar.locator('wa-dropdown-item[value="agent:writer"]').click();
  await page.locator('openclaw-app-sidebar [data-session-key="agent:writer:dashboard:item-1"]').first().waitFor();
  await context.close();
 }
 for(let run=0;run<5;run++) for(const stage of run%2===0?['before','after']:['after','before']) {
  const dir=path.join(root,'clips',stage);await mkdir(dir,{recursive:true});
  const context=await browser.newContext({viewport:{width:1440,height:900},locale:'en-US',recordVideo:{dir,size:{width:1440,height:900}}});
  const page=await context.newPage();page.setDefaultTimeout(30000);
  try {
   await install(page,stage);
   await page.evaluate(({rows,stage,run,identity}:any)=>{
    const w=window as any;const gateway=w.openclawControlUiE2eGateway;w.measurements=[];
    const panel=document.createElement('div');panel.id='performance-proof';panel.style.cssText='position:fixed;right:20px;bottom:20px;z-index:2147483647;background:#081526;color:white;border:2px solid #66cfff;border-radius:10px;padding:18px;width:490px;font:18px/1.5 monospace;pointer-events:none';document.body.append(panel);
    const title=`${stage.toUpperCase()} | repetition ${run+1}/5 | NORMAL SPEED`;
    const render=(m:any)=>{panel.textContent=`${title}\n${identity}\nMOCK GATEWAY · 200 rows/agent · no added delays\n${m?`${m.agentId==='writer'?'COLD: Main → Writer':'WARM: Writer → Main'}\n${m.usableMs===undefined?'Waiting for usable row':'Usable row visible'}: ${(m.usableMs??performance.now()-m.click).toFixed(1)} ms`:'Ready: fresh browser context, Main loaded'}\nClock: click event → first usable-row animation frame`;panel.style.whiteSpace='pre-wrap';};render(null);
    document.addEventListener('click',(event)=>{
     const option=event.composedPath().find((n:any)=>n?.matches?.('.sidebar-agent-menu__agent-switch')) as HTMLElement|undefined;
     const agentId=option?.getAttribute('value')?.slice(6);if(!agentId)return;
     const m:any={agentId,click:performance.now(),dispatch:[],response:[]};w.measurements.push(m);
     const frame=()=>{
      const el=document.querySelector(`openclaw-app-sidebar [data-session-key="agent:${agentId}:dashboard:item-1"]`) as HTMLElement|null;
      if(el){const b=el.getBoundingClientRect();const hit=document.elementFromPoint(b.x+b.width/2,b.y+b.height/2);if(b.width>0&&b.height>0&&b.y>=0&&b.bottom<=innerHeight&&hit&&(el===hit||el.contains(hit))&&!el.closest('[inert],[aria-disabled="true"]')) m.usableMs=performance.now()-m.click;}
      render(m);if(m.usableMs===undefined)requestAnimationFrame(frame);
     };requestAnimationFrame(frame);
    },true);
    gateway.setRequestHandler('sessions.list',({params,respond}:any)=>{
     const primary=!params.hasBoard&&!params.spawnedBy&&!params.archived;
     const m=w.measurements.at(-1);if(primary&&m)m.dispatch.push({agentId:params.agentId,ms:performance.now()-m.click});
     const sessions=primary?rows.filter((r:any)=>r.agentId===params.agentId):[];
     respond({ts:Date.now(),count:sessions.length,sessions,defaults:{model:'gpt-5.5',modelProvider:'openai',contextTokens:null},hasMore:false,nextOffset:null});
     if(primary&&m)m.response.push({agentId:params.agentId,ms:performance.now()-m.click});
    });
   },{rows,stage,run,identity:stage==='before'?`base ${manifest.baseline.slice(0,12)}`:`candidate ${manifest.candidateHead.slice(0,12)} + patch ${manifest.candidatePatchSha256.slice(0,10)}`});
   for(const agent of ['writer','main']) {
    // Pauses only provide readable context between actions, never delay measured work.
    await page.waitForTimeout(1000);
    const sidebar=page.locator('openclaw-app-sidebar');
    await sidebar.getByRole('button',{name:/Switch agent/}).click();
    await sidebar.locator(`wa-dropdown-item[value="agent:${agent}"]`).click();
    await page.waitForFunction((id:string)=>{const m=(window as any).measurements.at(-1);return m?.agentId===id&&m.usableMs!==undefined&&m.response.some((r:any)=>r.agentId===id);},agent);
    await page.waitForTimeout(1500);
    if(run===0)await page.screenshot({path:path.join(root,`${stage}-${agent}.png`)});
   }
   samples.push({run,stage,measurements:await page.evaluate(()=>(window as any).measurements)});
   const video=page.video();await context.close();await video.saveAs(path.join(dir,`run-${run+1}.webm`));
   await writeFile(path.join(root,'samples.partial.json'),JSON.stringify(samples,null,2));
  } catch(e) {await page.screenshot({path:path.join(root,`failure-${stage}-${run}.png`)}).catch(()=>{});await context.close();throw e;}
 }
 const summary:any={};
 for(const stage of ['before','after']){summary[stage]={};for(const agent of ['writer','main']){const a=samples.filter(s=>s.stage===stage).flatMap(s=>s.measurements).filter(m=>m.agentId===agent).map(m=>m.usableMs).sort((a,b)=>a-b);const mean=a.reduce((a,b)=>a+b,0)/a.length;summary[stage][agent]={n:a.length,min:a[0],median:a[2],max:a.at(-1),mean,sd:Math.sqrt(a.reduce((s,x)=>s+(x-mean)**2,0)/a.length),samples:a};}}
 await writeFile(path.join(root,'results.json'),JSON.stringify({manifest:{baseline:manifest.baseline,candidateHead:manifest.candidateHead,candidatePatchSha256:manifest.candidatePatchSha256},conditions:{boundary:'mocked Gateway, source-mode UI',browser:browser.version(),platform:os.platform(),arch:os.arch(),cpu:os.cpus()[0]?.model,viewport:'1440x900',rowsPerAgent:200,repetitions:5,order:'AB, BA, AB, BA, AB',rpcDelayMs:0,network:'loopback; no throttling',timing:'capture-phase agent-switch click event to first animation frame with visible hit-testable item-1 row',betweenActionReadabilityPausesMs:[1000,1500]},summary,samples},null,2));
 console.log(JSON.stringify({root,summary}));
}finally{await browser.close();for(const server of Object.values(servers) as any[])await server.close();}
before-run-1.webm
after-run-1.webm
before-run-2.webm
after-run-2.webm
before-run-3.webm
after-run-3.webm
before-run-4.webm
after-run-4.webm
before-run-5.webm
after-run-5.webm

@jalehman
jalehman marked this pull request as ready for review September 16, 2026 20:05
@clawsweeper clawsweeper Bot added proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 16, 2026
@jalehman
jalehman force-pushed the openclaw/agent-switch-session-performance branch from adb1259 to 9ad4cc5 Compare September 16, 2026 20:23
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Sep 16, 2026
jalehman and others added 2 commits September 16, 2026 13:42
Fix exact background-selection assertions and derive the supplemental reconciliation promise type. Refs agent-switch-4b7.
@jalehman

Copy link
Copy Markdown
Contributor Author

Current-head browser behavior proof

Verified d6b040f3e5bd3d574f6d1f15a9d3f1672267b5c8 with a clean worktree on September 16, 2026. 1 browser test passed (1 file), exit 0.

The Chromium test exercised the rendered Control UI against a synthetic Gateway with 200 session rows per agent. Writer rows appeared while chat.startup remained deferred. Returning to Main displayed its warm rows while the replacement sessions.list response remained deferred; rows from the other agent were absent in each selected view.

OPENCLAW_CAPTURE_UI_PROOF=1 node scripts/run-vitest.mjs run \
  --config test/vitest/vitest.ui-e2e.config.ts --configLoader runner \
  ui/src/e2e/agent-switch-roster.e2e.test.ts \
  ui/src/e2e/chat-startup-request-priority.e2e.test.ts \
  ui/src/e2e/queue-update-reload.e2e.test.ts

Only agent-switch-roster.e2e.test.ts matched; the other two path filters did not select suites. This is one exact-head behavior test, not a claim of 26 tests passing.

Screenshot files were captured, but media inspection and originating-chat render verification are blocked by the available tool policies. They have not been accepted as delivered visual evidence. The earlier published screenshots/videos retain their historical source identities. Current-head five-run benchmark provenance, image delivery, hosted CI/compiler results, and completed current-head ClawSweeper review remain open. No merge-readiness claim or merge authorization.

@jalehman

Copy link
Copy Markdown
Contributor Author

Exact-head five-run synthetic benchmark

Candidate: d6b040f3e5bd3d574f6d1f15a9d3f1672267b5c8, tree 941389b6412836e096875b434fd65784c6cac56e. Baseline: 82d4d1cc175549e222e3cb2605716f277eff6a00. The run completed with exit 0: five paired repetitions, 10 stage runs and 20 measured selections. The candidate was clean before and after capture; its tracked input inventory and harness hash were unchanged. The retained baseline matches 23,454 regular Git blobs at its declared commit; 12 instruction-file symlinks were separately covered by the retained SHA-256 manifest.

Observed click-to-usable-row times

Selection Baseline median [min–max], ms Exact-head median [min–max], ms Baseline / candidate SD, ms
Cold Main → Writer 405.9 [362.7–508.9] 149.8 [135.4–195.6] 48.8 / 21.6
Warm Writer → Main 160.5 [150.4–202.6] 113.7 [100.3–131.5] 20.9 / 10.2

Boundary and limitations: Chromium/source-mode Control UI against a synthetic Gateway; 200 rows per agent, 1440×900 viewport, no added network or RPC delay. Fresh browser contexts follow source-module warmup, with paired AB/BA order on the same shared host. Timing starts at the captured picker click and ends at the first animation frame where the selected row is visible and hit-testable. Readability pauses occur outside the measured interval. CPU scheduling is uncontrolled. The older baseline versus the integrated candidate does not isolate this PR's contribution and does not establish production latency or a population-tail estimate.

The exact-head held-request browser test is published separately. Exact-head CI completed successfully, including production/test typechecks, lint, build artifacts and the Control UI performance gate. This does not change the separate local compiler-boundary result.

Ten original normal-speed videos and screenshots were captured locally, but their inspection, upload and originating-chat rendering are not verified. Historical published media retains its stated source identity. Screenshot delivery remains a completion gate; no merge authorization is implied.

All raw samples, controls and source verification
{
  "verification": {
    "candidateHead": "d6b040f3e5bd3d574f6d1f15a9d3f1672267b5c8",
    "candidateTree": "941389b6412836e096875b434fd65784c6cac56e",
    "baseline": "82d4d1cc175549e222e3cb2605716f277eff6a00",
    "exit": 0,
    "stageRuns": 10,
    "measurements": 20,
    "normalSpeedOriginalVideos": 10,
    "sourceUnchanged": true,
    "resultSha256": "0481f344d589d17b4ac10cd3837b481131622386d98424a3ea7c55ac9bfa30b3",
    "harnessSha256": "54dfa05c9b110625d3c8475b8f8782d0e71aad2adc46bf036551c8ac61041c97",
    "visualInspectionAndDelivery": "not verified; existing tool-policy boundaries remain"
  },
  "conditions": {
    "boundary": "mocked Gateway, source-mode UI",
    "browser": "153.0.8010.12",
    "platform": "linux",
    "arch": "x64",
    "cpu": "Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz",
    "viewport": "1440x900",
    "rowsPerAgent": 200,
    "repetitions": 5,
    "order": "AB, BA, AB, BA, AB",
    "rpcDelayMs": 0,
    "network": "loopback; no throttling",
    "timing": "capture-phase agent-switch click event to first animation frame with visible hit-testable item-1 row",
    "betweenActionReadabilityPausesMs": [
      1000,
      1500
    ]
  },
  "samples": [
    {
      "run": 0,
      "stage": "before",
      "measurements": [
        {
          "agentId": "writer",
          "click": 4007.899999856949,
          "dispatch": [
            {
              "agentId": "writer",
              "ms": 335.40000009536743
            }
          ],
          "response": [
            {
              "agentId": "writer",
              "ms": 335.7999999523163
            }
          ],
          "usableMs": 407.10000014305115
        },
        {
          "agentId": "main",
          "click": 7129,
          "dispatch": [
            {
              "agentId": "main",
              "ms": 62.39999985694885
            }
          ],
          "response": [
            {
              "agentId": "main",
              "ms": 62.799999952316284
            }
          ],
          "usableMs": 151.19999980926514
        }
      ]
    },
    {
      "run": 0,
      "stage": "after",
      "measurements": [
        {
          "agentId": "writer",
          "click": 3929.2999999523163,
          "dispatch": [
            {
              "agentId": "writer",
              "ms": 54.799999952316284
            }
          ],
          "response": [
            {
              "agentId": "writer",
              "ms": 55.200000047683716
            }
          ],
          "usableMs": 138.90000009536743
        },
        {
          "agentId": "main",
          "click": 7051,
          "dispatch": [
            {
              "agentId": "main",
              "ms": 138.79999995231628
            }
          ],
          "response": [
            {
              "agentId": "main",
              "ms": 139.29999995231628
            }
          ],
          "usableMs": 131.5
        }
      ]
    },
    {
      "run": 1,
      "stage": "after",
      "measurements": [
        {
          "agentId": "writer",
          "click": 3997.0999999046326,
          "dispatch": [
            {
              "agentId": "writer",
              "ms": 90.5
            }
          ],
          "response": [
            {
              "agentId": "writer",
              "ms": 91.10000014305115
            }
          ],
          "usableMs": 195.60000014305115
        },
        {
          "agentId": "main",
          "click": 7100.899999856949,
          "dispatch": [
            {
              "agentId": "main",
              "ms": 122.60000014305115
            }
          ],
          "response": [
            {
              "agentId": "main",
              "ms": 123
            }
          ],
          "usableMs": 115.80000019073486
        }
      ]
    },
    {
      "run": 1,
      "stage": "before",
      "measurements": [
        {
          "agentId": "writer",
          "click": 3958.0999999046326,
          "dispatch": [
            {
              "agentId": "writer",
              "ms": 317.60000014305115
            }
          ],
          "response": [
            {
              "agentId": "writer",
              "ms": 318.10000014305115
            }
          ],
          "usableMs": 405.90000009536743
        },
        {
          "agentId": "main",
          "click": 7085.899999856949,
          "dispatch": [
            {
              "agentId": "main",
              "ms": 65.5
            }
          ],
          "response": [
            {
              "agentId": "main",
              "ms": 65.90000009536743
            }
          ],
          "usableMs": 187
        }
      ]
    },
    {
      "run": 2,
      "stage": "before",
      "measurements": [
        {
          "agentId": "writer",
          "click": 4015.300000190735,
          "dispatch": [
            {
              "agentId": "writer",
              "ms": 291.59999990463257
            }
          ],
          "response": [
            {
              "agentId": "writer",
              "ms": 291.7999999523163
            }
          ],
          "usableMs": 362.69999980926514
        },
        {
          "agentId": "main",
          "click": 6999.800000190735,
          "dispatch": [
            {
              "agentId": "main",
              "ms": 57
            }
          ],
          "response": [
            {
              "agentId": "main",
              "ms": 57.299999952316284
            }
          ],
          "usableMs": 150.39999985694885
        }
      ]
    },
    {
      "run": 2,
      "stage": "after",
      "measurements": [
        {
          "agentId": "writer",
          "click": 3964.7000000476837,
          "dispatch": [
            {
              "agentId": "writer",
              "ms": 68.20000004768372
            }
          ],
          "response": [
            {
              "agentId": "writer",
              "ms": 68.70000004768372
            }
          ],
          "usableMs": 152.79999995231628
        },
        {
          "agentId": "main",
          "click": 6733.299999952316,
          "dispatch": [
            {
              "agentId": "main",
              "ms": 120.40000009536743
            }
          ],
          "response": [
            {
              "agentId": "main",
              "ms": 120.90000009536743
            }
          ],
          "usableMs": 113.70000004768372
        }
      ]
    },
    {
      "run": 3,
      "stage": "after",
      "measurements": [
        {
          "agentId": "writer",
          "click": 4008.399999856949,
          "dispatch": [
            {
              "agentId": "writer",
              "ms": 56.5
            }
          ],
          "response": [
            {
              "agentId": "writer",
              "ms": 57.10000014305115
            }
          ],
          "usableMs": 149.80000019073486
        },
        {
          "agentId": "main",
          "click": 7043.399999856949,
          "dispatch": [
            {
              "agentId": "main",
              "ms": 115.60000014305115
            }
          ],
          "response": [
            {
              "agentId": "main",
              "ms": 116
            }
          ],
          "usableMs": 109.10000014305115
        }
      ]
    },
    {
      "run": 3,
      "stage": "before",
      "measurements": [
        {
          "agentId": "writer",
          "click": 3817.600000143051,
          "dispatch": [
            {
              "agentId": "writer",
              "ms": 318.7000000476837
            }
          ],
          "response": [
            {
              "agentId": "writer",
              "ms": 319.09999990463257
            }
          ],
          "usableMs": 399.7999999523163
        },
        {
          "agentId": "main",
          "click": 6936,
          "dispatch": [
            {
              "agentId": "main",
              "ms": 79.30000019073486
            }
          ],
          "response": [
            {
              "agentId": "main",
              "ms": 79.70000004768372
            }
          ],
          "usableMs": 160.5
        }
      ]
    },
    {
      "run": 4,
      "stage": "before",
      "measurements": [
        {
          "agentId": "writer",
          "click": 3961.100000143051,
          "dispatch": [
            {
              "agentId": "writer",
              "ms": 412.89999985694885
            }
          ],
          "response": [
            {
              "agentId": "writer",
              "ms": 413.39999985694885
            }
          ],
          "usableMs": 508.89999985694885
        },
        {
          "agentId": "main",
          "click": 7068.700000047684,
          "dispatch": [
            {
              "agentId": "main",
              "ms": 74.59999990463257
            }
          ],
          "response": [
            {
              "agentId": "main",
              "ms": 75.20000004768372
            }
          ],
          "usableMs": 202.59999990463257
        }
      ]
    },
    {
      "run": 4,
      "stage": "after",
      "measurements": [
        {
          "agentId": "writer",
          "click": 3955.699999809265,
          "dispatch": [
            {
              "agentId": "writer",
              "ms": 55.5
            }
          ],
          "response": [
            {
              "agentId": "writer",
              "ms": 55.700000047683716
            }
          ],
          "usableMs": 135.40000009536743
        },
        {
          "agentId": "main",
          "click": 7007.5,
          "dispatch": [
            {
              "agentId": "main",
              "ms": 106.5
            }
          ],
          "response": [
            {
              "agentId": "main",
              "ms": 106.89999985694885
            }
          ],
          "usableMs": 100.29999995231628
        }
      ]
    }
  ]
}
Reproduction harness

With the declared baseline snapshot, the clean candidate checkout and their existing approved dependencies, supply source-manifest.json with baseline, candidateHead, candidatePatchSha256 (SHA-256 of the empty patch), and absolute roots.before / roots.after. Run node --import tsx record.mts from the candidate checkout. No dependency or source changes are part of this procedure.

import { writeFile, readFile, mkdir } from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import { chromium } from 'playwright';
const root = path.dirname(new URL(import.meta.url).pathname);
const manifest = JSON.parse(await readFile(path.join(root, 'source-manifest.json'), 'utf8'));
const helpers = Object.fromEntries(await Promise.all(['before','after'].map(async stage => [stage, await import(path.join(manifest.roots[stage],'ui/src/test-helpers/control-ui-e2e.ts'))])));
const { createControlUiSessionRow } = await import(path.join(manifest.roots.after,'ui/src/test-helpers/control-ui-session-fixtures.ts'));
const rows = ['main','writer'].flatMap(agent => Array.from({length:200},(_,i) => createControlUiSessionRow(`agent:${agent}:${i===0?'main':`dashboard:item-${i}`}`, `${agent==='main'?'Main':'Writer'} project ${String(i).padStart(3,'0')}`,1789540000000-i*1000,{agentId:agent})));
const servers:any = {}; const samples:any[]=[];
const browser = await chromium.launch({executablePath:helpers.after.resolvePlaywrightChromiumExecutablePath(chromium.executablePath())});
async function install(page:any, stage:string) {
  await page.addInitScript('globalThis.__name = (target) => target;');
  await helpers[stage].installMockGateway(page,{sessions:rows,historyMessages:[{role:'assistant',content:'Synthetic matched browser performance fixture.'}],methodResponses:{'agents.list':{defaultId:'main',mainKey:'main',scope:'per-sender',agents:[{id:'main',name:'Main'},{id:'writer',name:'Writer'}]}}});
  await page.goto(`${servers[stage].baseUrl}chat/main`);
  await page.locator('openclaw-app-sidebar [data-session-key="agent:main:dashboard:item-1"]').first().waitFor();
}
try {
 for(const stage of ['before','after']) {
  servers[stage]=await helpers[stage].startControlUiE2eServer(undefined,{source:true});
  const context=await browser.newContext({viewport:{width:1440,height:900},locale:'en-US'});
  const page=await context.newPage(); await install(page,stage);
  // Prime source-module compilation outside the recorded fresh contexts.
  const sidebar=page.locator('openclaw-app-sidebar');
  await sidebar.getByRole('button',{name:/Switch agent/}).click();
  await sidebar.locator('wa-dropdown-item[value="agent:writer"]').click();
  await page.locator('openclaw-app-sidebar [data-session-key="agent:writer:dashboard:item-1"]').first().waitFor();
  await context.close();
 }
 for(let run=0;run<5;run++) for(const stage of run%2===0?['before','after']:['after','before']) {
  const dir=path.join(root,'clips',stage);await mkdir(dir,{recursive:true});
  const context=await browser.newContext({viewport:{width:1440,height:900},locale:'en-US',recordVideo:{dir,size:{width:1440,height:900}}});
  const page=await context.newPage();page.setDefaultTimeout(30000);
  try {
   await install(page,stage);
   await page.evaluate(({rows,stage,run,identity}:any)=>{
    const w=window as any;const gateway=w.openclawControlUiE2eGateway;w.measurements=[];
    const panel=document.createElement('div');panel.id='performance-proof';panel.style.cssText='position:fixed;right:20px;bottom:20px;z-index:2147483647;background:#081526;color:white;border:2px solid #66cfff;border-radius:10px;padding:18px;width:490px;font:18px/1.5 monospace;pointer-events:none';document.body.append(panel);
    const title=`${stage.toUpperCase()} | repetition ${run+1}/5 | NORMAL SPEED`;
    const render=(m:any)=>{panel.textContent=`${title}\n${identity}\nMOCK GATEWAY · 200 rows/agent · no added delays\n${m?`${m.agentId==='writer'?'COLD: Main → Writer':'WARM: Writer → Main'}\n${m.usableMs===undefined?'Waiting for usable row':'Usable row visible'}: ${(m.usableMs??performance.now()-m.click).toFixed(1)} ms`:'Ready: fresh browser context, Main loaded'}\nClock: click event → first usable-row animation frame`;panel.style.whiteSpace='pre-wrap';};render(null);
    document.addEventListener('click',(event)=>{
     const option=event.composedPath().find((n:any)=>n?.matches?.('.sidebar-agent-menu__agent-switch')) as HTMLElement|undefined;
     const agentId=option?.getAttribute('value')?.slice(6);if(!agentId)return;
     const m:any={agentId,click:performance.now(),dispatch:[],response:[]};w.measurements.push(m);
     const frame=()=>{
      const el=document.querySelector(`openclaw-app-sidebar [data-session-key="agent:${agentId}:dashboard:item-1"]`) as HTMLElement|null;
      if(el){const b=el.getBoundingClientRect();const hit=document.elementFromPoint(b.x+b.width/2,b.y+b.height/2);if(b.width>0&&b.height>0&&b.y>=0&&b.bottom<=innerHeight&&hit&&(el===hit||el.contains(hit))&&!el.closest('[inert],[aria-disabled="true"]')) m.usableMs=performance.now()-m.click;}
      render(m);if(m.usableMs===undefined)requestAnimationFrame(frame);
     };requestAnimationFrame(frame);
    },true);
    gateway.setRequestHandler('sessions.list',({params,respond}:any)=>{
     const primary=!params.hasBoard&&!params.spawnedBy&&!params.archived;
     const m=w.measurements.at(-1);if(primary&&m)m.dispatch.push({agentId:params.agentId,ms:performance.now()-m.click});
     const sessions=primary?rows.filter((r:any)=>r.agentId===params.agentId):[];
     respond({ts:Date.now(),count:sessions.length,sessions,defaults:{model:'gpt-5.5',modelProvider:'openai',contextTokens:null},hasMore:false,nextOffset:null});
     if(primary&&m)m.response.push({agentId:params.agentId,ms:performance.now()-m.click});
    });
   },{rows,stage,run,identity:stage==='before'?`base ${manifest.baseline.slice(0,12)}`:`exact candidate ${manifest.candidateHead.slice(0,12)}`});
   for(const agent of ['writer','main']) {
    // Pauses only provide readable context between actions, never delay measured work.
    await page.waitForTimeout(1000);
    const sidebar=page.locator('openclaw-app-sidebar');
    await sidebar.getByRole('button',{name:/Switch agent/}).click();
    await sidebar.locator(`wa-dropdown-item[value="agent:${agent}"]`).click();
    await page.waitForFunction((id:string)=>{const m=(window as any).measurements.at(-1);return m?.agentId===id&&m.usableMs!==undefined&&m.response.some((r:any)=>r.agentId===id);},agent);
    await page.waitForTimeout(1500);
    if(run===0)await page.screenshot({path:path.join(root,`${stage}-${agent}.png`)});
   }
   samples.push({run,stage,measurements:await page.evaluate(()=>(window as any).measurements)});
   const video=page.video();await context.close();await video.saveAs(path.join(dir,`run-${run+1}.webm`));
   await writeFile(path.join(root,'samples.partial.json'),JSON.stringify(samples,null,2));
  } catch(e) {await page.screenshot({path:path.join(root,`failure-${stage}-${run}.png`)}).catch(()=>{});await context.close();throw e;}
 }
 const summary:any={};
 for(const stage of ['before','after']){summary[stage]={};for(const agent of ['writer','main']){const a=samples.filter(s=>s.stage===stage).flatMap(s=>s.measurements).filter(m=>m.agentId===agent).map(m=>m.usableMs).sort((a,b)=>a-b);const mean=a.reduce((a,b)=>a+b,0)/a.length;summary[stage][agent]={n:a.length,min:a[0],median:a[2],max:a.at(-1),mean,sd:Math.sqrt(a.reduce((s,x)=>s+(x-mean)**2,0)/a.length),samples:a};}}
 await writeFile(path.join(root,'results.json'),JSON.stringify({manifest:{baseline:manifest.baseline,candidateHead:manifest.candidateHead,candidatePatchSha256:manifest.candidatePatchSha256},conditions:{boundary:'mocked Gateway, source-mode UI',browser:browser.version(),platform:os.platform(),arch:os.arch(),cpu:os.cpus()[0]?.model,viewport:'1440x900',rowsPerAgent:200,repetitions:5,order:'AB, BA, AB, BA, AB',rpcDelayMs:0,network:'loopback; no throttling',timing:'capture-phase agent-switch click event to first animation frame with visible hit-testable item-1 row',betweenActionReadabilityPausesMs:[1000,1500]},summary,samples},null,2));
 console.log(JSON.stringify({root,summary}));
}finally{await browser.close();for(const server of Object.values(servers) as any[])await server.close();}

@jalehman

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Same head d6b040f3e5bd3d574f6d1f15a9d3f1672267b5c8. New source-bound five-paired-run benchmark, every sample, baseline Git verification and harness: #150092 (comment). The PR body now links that evidence, exact-head held-request browser proof and successful CI (production/test types, lint, build and UI performance). Please reassess those new inputs. Before/after screenshot rendering in the originating chat remains unverified and is not waived. This requests review only, not repair or merge.

@clawsweeper

clawsweeper Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot removed the proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. label Sep 16, 2026
@jalehman
jalehman merged commit a5be827 into main Sep 17, 2026
161 checks passed
@jalehman
jalehman deleted the openclaw/agent-switch-session-performance branch September 17, 2026 00:05
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 17, 2026
* fix: show selected agent sessions without waiting for chat startup

* fix(ui): preserve startup priority and scoped history ordering

* test(ui): align selection and reconciliation contracts

Fix exact background-selection assertions and derive the supplemental reconciliation promise type. Refs agent-switch-4b7.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant