Skip to content

perf(ui): overlap chat startup with Gateway connection - #185683

Merged
steipete merged 13 commits into
mainfrom
solid2/w-boot-early-subscribe
Oct 27, 2026
Merged

steipete merged 13 commits into
mainfrom
solid2/w-boot-early-subscribe

Conversation

@steipete

@steipete steipete commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Related: #185464

What Problem This Solves

Chat startup waits for the renderer graph before connecting to the Gateway and loading the initial transcript. This keeps module evaluation and network round trips on the same critical path.

User Impact

Chat becomes ready sooner by overlapping the Gateway handshake and initial subscription with application loading. Cached reloads continue rendering when the Gateway is unreachable.

Why This Change Was Made

Start the existing GatewayBrowserClient before renderer evaluation, then let the application adopt that same client and subscription. The transport retains ordered events until attachment, bounded to 256 events, 2 MiB, and 10 seconds. It preserves one connection and the existing authentication, admission, retry, and authority owners.

Pre-attach authentication errors reach the login owner; retryable rejection retains the protocol client and its retry budget. Rejected subscriptions reach the pane's existing read-retry policy. A changed history request discards only the stale prefetched snapshot, preserving live delivery while the history owner requests the correct shape. Cached views use the credential owner's existing boot-record admission and never wait for a missing Gateway challenge.

Route/credential mismatch, overflow, and timeout fall back to ordinary startup. Native handoffs, ingress documents, short references, and confirmation-required Gateways retain their existing path. A name-shaped literal remains a guess: if the route owner resolves a different target, the bounded handoff retires and ordinary startup reconnects. This accepted extra reconnect avoids a second route resolver. No protocol change or new dependency.

Evidence

Performance

The final comparison against main 979c8decf7dfe07616aac6243f7bcf78d505be58 passed 480/480 observations: 20 interleaved pairs for cold/warm boot, Chromium/WebKit, and localhost/100 ms, including an identical-base A/A control. Immutable production bundles use identical build metadata, all 37 matching plugin inputs, and all 61 matching emitted plugin files. Values are median / p95 readiness in milliseconds.

Boot / network Chromium base → head WebKit base → head WebKit / Chromium base → head
Cold / localhost 425.3 / 446.7 → 400.8 / 424.7 (-5.8%) 664.0 / 705.0 → 610.5 / 659.0 (-8.1%) 1.56× → 1.52×
Cold / 100 ms 988.8 / 1009.6 → 855.2 / 886.0 (-13.5%) 1090.0 / 1136.0 → 998.0 / 1031.0 (-8.4%) 1.10× → 1.17×
Warm / localhost 239.1 / 282.1 → 214.9 / 253.8 (-10.1%) 432.0 / 461.0 → 396.5 / 453.0 (-8.2%) 1.81× → 1.84×
Warm / 100 ms 830.7 / 853.2 → 695.7 / 737.9 (-16.2%) 812.0 / 858.0 → 685.5 / 718.0 (-15.6%) 0.98× → 0.99×

Every readiness p95 improves. Chromium local script CPU improves 11.7% cold / 10.3% warm; all script and task p95s improve. Warm/100 ms task CPU moves +2.1% against an A/A +1.9%, within the acceptance band, with p95 -4.4%. Local warm Chromium A/A p95 moves -6.0%; CPU and twenty-pair results qualify that noisy tail. No affected CPU regression exceeds the band. WebKit has no untraced CPU counter; its readiness is elapsed time.

Earlier qualified matrices add 1,440 observations and 16 separate profiler captures: 1,920 valid untraced observations overall. An 86-observation intermediate run was stopped and excluded after main changed route prewarming. The 100 ms profile delays each HTTP request and inbound mock Gateway frame; it is synthetic latency, not physical-network or live-provider RTT. Warm means a same-context reload retaining IndexedDB; mocked routing disables HTTP caching. Every final observation uses one connection.

The remote engine ratios are below 1.3×; local ratios remain 1.52× cold / 1.84× warm. Earlier WebKit Timeline/ScriptProfiler/CPUProfiler and Chromium CDP/source-map captures identify remaining transcript layout, virtualization, and Solid work; this PR does not claim the residual gap is exclusively engine-internal.

Size / requests Main baseline Integrated head
Startup JS gzip 271,382 B / 5 90,195 B / 3
Startup CSS gzip 32,702 B / 1 32,702 B / 1
Full Chat JS gzip 1,267,240 B / 20 1,267,973 B / 19
New Session JS gzip 768,861 B / 16 771,110 B / 15

Strict performance comparison passes. The startup ratchet matches the measured 90,195 B. The largest chunk remains below its existing 571,274 B cap. Full-route requests decrease by one; plugin stylesheet URLs stay lazy.

Correctness and validation

Proof Result
Transport handoff 14 passing tests: ordered delivery, one socket, history-shape changes, auth/error/retry, timeout/overflow, narration isolation and approval replay bounds
Real pane handoff Initial transcript and pre-attach final delivered exactly once, one socket, no fallback history RPC
Existing lifecycle / prewarm 24 connection, 3 preload, and 12 snapshot-prewarm tests pass
Saved-startup recovery All three recovery variants pass with original fixtures and one-socket assertions
Warm offline / missing challenge Both merged cases pass; cached shell, transcript and draft restore before connect, then reconciliation succeeds
Mock observer IDs Regression red before repair; all 12 mock-Gateway tests pass
Final performance 480/480 observations pass; every readiness median and p95 improves
Static / production proof Integrated UI typecheck, focused lint/format, build, strict size check, and production Knip pass; inherited bootstrap max-lines debt retained separately
Independent review Full integrated diff reviewed through P2 with no actionable findings
Full CI ci:full, current head d4291e0dd875151efe2ed9f43839f28be7acc800: 40493570441: 47 jobs passed, 23 skipped, no failures

Earlier CI exposed and drove repairs to error delivery, retryable admission, and saved-startup live delivery. Run 40489643508 passed the saved-recovery case but failed “real chat route recovers current account state after complete snapshot ordering”: Account B arrived, but the picker was closed at assertion time. That exact case passed separately on both the base and repaired head. This integration also includes main's authoritative-readiness test correction from #185745; the failure is not described as inherited or as proven fixed solely by a passing replay. Current-head full CI passed all required jobs, including all UI browser and real-Gateway shards.

The directly coupled mock now tracks observer IDs independently; releasing one same-session subscription no longer silences another. Original recovery ACK fixtures and assertions are preserved.

All browsers are headless. No remote leases or local Docker. Reports and captures are under the lane's .artifacts/; no report is committed.

Physical LOC across touched files: production UI 2,798 → 3,247 (+449); tests 4,404 → 5,070 (+666); harness/build/docs 4,899 → 5,015 (+116); total 12,101 → 13,332 (+1,231). The added code implements the bounded transport handoff and its ordering/error proof. Domain and protocol ownership remain unchanged.

Before / after

Inspected synthetic fixtures only; rendered UI is preserved.

Desktop before Desktop after
Desktop before Desktop after
Mobile WebKit before Mobile WebKit after
Mobile WebKit before Mobile WebKit after

Adopt the existing authenticated transport and initial subscription after a bounded event handoff. Preserve live event ordering, foreground ownership, and normal reconnect recovery while the renderer loads.
@steipete steipete added the ci:full Keep ordinary native-locale CI selection on the next PR run. label Oct 27, 2026
@clawsweeper

clawsweeper Bot commented Oct 27, 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-27T11:11:44.502013Z d4291e0 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui scripts Repository scripts size: XL labels Oct 27, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d38608a0fc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +25 to +26
route?.kind !== "literal" ||
route.namespace !== "chat"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Exclude unresolved name links from early Gateway startup

For display-name links such as /chat/roboclaw/deploy-monitor, sessionRefFromPath returns kind: "literal" with a slugCandidate, so this guard incorrectly treats the name as an exact session key. loadChatRoute subsequently resolves that name through the Gateway and canonicalizes the URL to the actual session. The early handoff then encounters a different URL or session key: takeSubscription either forces a reconnect immediately or leaves events buffered until the ten-second timeout forces one. This adds an unnecessary connection restart and discards buffered delivery on supported name-link navigation. Keep targets with slugCandidate on ordinary startup until the existing route owner resolves their identity.

AGENTS.md reference: ui/AGENTS.md:L16-L16

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping the bounded route-guess behavior here deliberately: if the existing route owner resolves a different session or URL, the early handoff is retired and ordinary startup reconnects. A possible extra reconnect for a name-shaped literal is an accepted fallback; the transport does not add a second route resolver or cache. I clarified the source comment and PR description so they no longer imply that every literal candidate is already an exact identity. Short-ID references continue on ordinary startup.

@steipete
steipete enabled auto-merge (squash) October 27, 2026 08:38
@clawsweeper clawsweeper Bot added the clawsweeper:intake:feature Preliminary submission classification; full source review pending. label Oct 27, 2026
@steipete
steipete disabled auto-merge October 27, 2026 08:42
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 27, 2026
@clawsweeper

clawsweeper Bot commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR starts the Gateway connection and initial transcript subscription before evaluating the Control UI renderer.

Example: Open Chat on desktop with the synthetic 100 ms network profile.

  • Before: Chromium median readiness was 982.4 ms.
  • After: The reported original-base median was 856.9 ms.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful measured direction, with synthetic transport proof and three confirmed repairs before merge.
Proof confidence 🦐 gold shrimp (3/6) The ordinary contributor-proof gate does not apply to this maintainer-authored PR; inspected screenshots and reported production-bundle measurements exercise synthetic browser startup, while live Gateway authentication remains outside their demonstrated scope.
Patch quality 🦪 silver shellfish (2/6) 3 actionable review findings remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Opening a chat serializes application evaluation ahead of Gateway connection and transcript loading.
Reason: The maintainer-authored direction is approved, and the reported cross-engine measurements support meaningful readiness gains without a new user option or protocol.

Merge readiness

⛔ Needs changes before merge - 3 items remain

Keep open for focused repair: this maintainer-authored optimization has clear value, but the patch is not ready to merge.

Priority: P2
Reviewed head: d38608a0fc8c3eb2fb5e8b2087045cce2b937ff2

Before merge

  • Exclude unresolved display-name links from early startup (P2) - For /chat/roboclaw/deploy-monitor, the parser returns a literal target with slugCandidate, so this guard starts a subscription for the guessed key. The existing route loader can resolve that name to another session and canonical URL. The handoff then either rejects the changed URL immediately or leaves events buffered until its ten-second timeout reconnects the client. Exclude slugCandidate targets until the route owner resolves their identity, preserving the ordinary startup path promised by this PR.
  • Migrate the remaining warm-boot snapshot test consumer (P2) - Removing this re-export leaves bootstrap.warm-boot.test.ts importing the old module and spying on clearStoredChatSnapshots at line 197. All three parameterized account-retirement cases now fail before exercising their contract; exact-head CI records the missing-property error. Point that consumer at session-snapshot-invalidation.ts, as the updated prewarm suite already does, while retaining its account-cleanup assertions.
  • Update the chunking test to locate its group by identity (P2) - Inserting this group first changes groups[0] from the stable-chunk group to the connection group. The existing snapshot-prewarming test still treats that position as the stable group, so its database predicate fails at line 401 in exact-head CI. Find the intended group by its contract rather than its array position and preserve the database-isolation and priority assertions.

Findings

  • [P2] Exclude unresolved display-name links from early startup — ui/src/app/early-gateway.ts:25-26
  • [P2] Migrate the remaining warm-boot snapshot test consumer — ui/src/pages/chat/session-snapshot-invalidation.runtime.ts:1-4
  • [P2] Update the chunking test to locate its group by identity — ui/config/control-ui-chunking.ts:440-442

Tests

  • Missing end-to-end proof: The supplied browser benchmark uses synthetic Gateway transport; unresolved name-link navigation and base-red/head-green coverage for the confirmed repairs are not shown.
Agent review details

How this fits together

The browser entry resolves connection settings, starts the existing Gateway client, and transfers its subscription and buffered events to the application and chat pane.

flowchart LR
  A[Browser document] --> B[Startup settings]
  B --> C[Existing Gateway client]
  C --> D[Bounded event handoff]
  A --> E[Deferred application renderer]
  D --> E
  E --> F[Chat subscription and transcript]
Loading

Technical review

Best possible solution:

Keep the existing client and subscription coordinator, exclude unresolved name links from early startup, and migrate the remaining test consumers.

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

Source establishes the premature name-link admission, and exact-head CI independently records both broken test consumers; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The small entry and bounded handoff address the serialized startup work using existing transport owners; the inspected extractions preserve their implementations without adding another authentication or subscription policy.

Full review comments:

  • [P2] Exclude unresolved display-name links from early startup — ui/src/app/early-gateway.ts:25-26
    For /chat/roboclaw/deploy-monitor, the parser returns a literal target with slugCandidate, so this guard starts a subscription for the guessed key. The existing route loader can resolve that name to another session and canonical URL. The handoff then either rejects the changed URL immediately or leaves events buffered until its ten-second timeout reconnects the client. Exclude slugCandidate targets until the route owner resolves their identity, preserving the ordinary startup path promised by this PR.
    Confidence: 0.99
  • [P2] Migrate the remaining warm-boot snapshot test consumer — ui/src/pages/chat/session-snapshot-invalidation.runtime.ts:1-4
    Removing this re-export leaves bootstrap.warm-boot.test.ts importing the old module and spying on clearStoredChatSnapshots at line 197. All three parameterized account-retirement cases now fail before exercising their contract; exact-head CI records the missing-property error. Point that consumer at session-snapshot-invalidation.ts, as the updated prewarm suite already does, while retaining its account-cleanup assertions.
    Confidence: 1
  • [P2] Update the chunking test to locate its group by identity — ui/config/control-ui-chunking.ts:440-442
    Inserting this group first changes groups[0] from the stable-chunk group to the connection group. The existing snapshot-prewarming test still treats that position as the stable group, so its database predicate fails at line 401 in exact-head CI. Find the intended group by its contract rather than its array position and preserve the database-isolation and priority assertions.
    Confidence: 1

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 60aaedd81245.

Provenance checked

  • Application entry, browser admission, and static frame keeps the original intent (f3464c7: Paint the static chat frame before application assets finish while preserving stylesheet and mount recovery.)
  • Startup settings and document-specific connection ownership keeps the original intent (feat(ui): add standalone operator approval links #103698: Standalone documents remain bound to their serving Gateway without overwriting the full application's saved connection.)
  • Warm-boot retirement keeps the original intent (9764de1: Keep cached work usable during connection failures while retiring rejected account-scoped admission.)
  • Pre-hello transcript subscription keeps the original intent (f8afddd: Queue the selected transcript behind connect using the existing coordinator and Gateway authorization checks.)
  • Route preload asset selection keeps the original intent (6b80e1a: Keep URL-only assets out of eager document module hints; the PR extends that distinction to plugin stylesheet metadata.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm --dir ui test src/api/gateway-boot.node.test.ts src/pages/chat/chat-early-gateway.test.ts src/app/bootstrap.warm-boot.test.ts src/app/control-ui-chunking.test.ts
  • pnpm tsgo:ui
  • pnpm tsgo:test:ui
  • pnpm ui:build
  • pnpm ui:check-performance

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 368b9dc adds ui/src/app/bootstrap-warm-boot.ts:33 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 368b9dc52b98; files: ui/src/app/bootstrap-warm-boot.ts)

PR surface

Source +433, Tests +436, Docs +11, Other +73. Total +953 across 29 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 18 690 257 +433
Tests 4 438 2 +436
Docs 1 11 0 +11
Config 0 0 0 0
Generated 0 0 0 0
Other 6 100 27 +73
Total 29 1239 286 +953

Labels

Label changes:

  • add P2: This is a useful startup optimization with a bounded route regression and focused test-consumer repairs.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: This is a useful startup optimization with a bounded route regression and focused test-consumer repairs.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 27, 2026, 4:48 AM ET / 08:48 UTC.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9abdb1ccbe

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread ui/src/main.ts Outdated
Comment on lines +13 to +15
void (early ? early.transport.client.initialConnectSent : Promise.resolve())
.then(() => import("./main.runtime.ts"))
.then(({ startControlUi }) => startControlUi(initial, early));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Let warm reloads render before the connect request is sent

On a warm reload of an exact chat link, if the Gateway connection stalls before delivering its challenge (for example, a blackholed connection during a network outage), initialConnectSent remains pending until the early transport's ten-second timeout stops the client. Because the renderer import now waits for that receipt, the cached shell, conversation, and drafts cannot appear during those ten seconds, even when all assets and retained data are available locally. Previously, bootstrapApplication admitted the warm boot and restored those views independently of the handshake. Keep warm-cache rendering independent of this network-dependent receipt, while retaining the early connection optimization.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ddea67a. The credential owner now exposes its existing boot-record admission, and admitted cached reloads skip the network-dependent renderer wait. The matching warm-reload test withholds the first challenge, proves cached shell/transcript/draft restoration before connect on one socket, then releases the challenge and verifies reconciliation. It fails on the old path and passes with the fix; cold startup retains the early-connect ordering.

@steipete
steipete merged commit 4420648 into main Oct 27, 2026
135 of 136 checks passed
@steipete
steipete deleted the solid2/w-boot-early-subscribe branch October 27, 2026 11:40
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 28, 2026
* perf(ui): overlap chat startup with the Gateway connection

Adopt the existing authenticated transport and initial subscription after a bounded event handoff. Preserve live event ordering, foreground ownership, and normal reconnect recovery while the renderer loads.

* perf(ui): ratchet measured boot sizes and use owned listeners

* perf(ui): pin final measured boot budgets

* fix(ui): preserve startup errors through early handoff

* test(ui): preserve window events in reload fixture

* fix(ui): retain retryable admission during early handoff

Preserve the existing protocol retry and its error receipt until the app attaches. Hold every startup descriptor in the stream fixture, and label the two recovery send waits for targeted CI diagnostics. Keep the startup ratchet at the final measured size.

* docs(ui): clarify early route guess fallback

* perf(ui): ratchet integrated startup size to measurement

* fix(ui): preserve early observer across history changes

* fix(ui): restore cached views before Gateway challenge
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 ci:full Keep ordinary native-locale CI selection on the next PR run. docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant