Skip to content

fix(gateway): own standalone MCP App request lifetimes - #119388

Merged
steipete merged 2 commits into
openclaw:mainfrom
tzy-17:fix/mcp-app-standalone-fetch-timeout
Aug 28, 2026
Merged

steipete merged 2 commits into
openclaw:mainfrom
tzy-17:fix/mcp-app-standalone-fetch-timeout

Conversation

@tzy-17

@tzy-17 tzy-17 commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

A standalone MCP App could report a timeout even when catalog discovery and tool execution each completed within the server's request budget. The browser applied one derived deadline to the combined operation, then invited a retry while the backend could still complete the original call.

The initial view-load hang was already fixed by #119276. This rewrite preserves that 30-second bound and fixes the remaining operation-lifetime defect. Thanks @tzy-17 for identifying the multi-stage problem. The signed commit retains Co-authored-by: 唐梓夷0668001293 <[email protected]>.

Blame traces the operation timer to #119276, authored by Peter Lee (@xialonglee) and merged by Dallin Romney (@RomneyDa) on August 10, 2026, in f502607. A later HEAD-metadata repair carried the same timer serialization forward. Stable-release inclusion has not been established.

Why This Change Was Made

The browser owns the App request lifetime; the managed runtime owns each upstream RPC budget. This removes the derived whole-operation timer and propagates actual cancellation through fetch, HTTP disconnect and the existing request context. Cancelling one catalog waiter does not cancel discovery shared with other callers. Typed request IDs and retirement-before-abort prevent late results from settling a replacement request.

One document-lifecycle owner handles active, graceful-teardown, suspended and closed states. App-requested teardown retains authorized cleanup RPCs until acknowledgment or the existing first one-second deadline. Terminal navigation closes work immediately. Persisted-document recovery reloads through canonical ticket validation without reviving a closed heap or replaying operations. Retired bootstrap and response-body completions cannot overwrite the live UI.

The asynchronous catalog-wait helper also keeps authorization-time cancellation inside Promise.all's promise ownership, preventing synchronous argument evaluation from orphaning another rejection. No global rejection suppression is added.

User Impact

Valid composed operations finish without an artificial browser timeout; graceful App shutdown can save state before unmounting. Cancellation stops this caller's wait and reaches managed requests, but cannot undo server side effects. History recovery starts a fresh App, resets transient state and does not retry interrupted work. Expired tickets require a fresh App link.

No new configuration, dependency, SDK field, protocol, persistent storage or authorization bypass is introduced. Initial loading remains bounded at 30 seconds; individual RPC deadlines and the public runtime timeout getter remain intact. The serialized host is executable browser code, not a persistent-state schema or migration.

Evidence

Before: real Chromium, the actual Gateway, official App SDK and a synthetic MCP stdio server reproduced the defect on the unmodified baseline. With a ten-second per-RPC budget, catalog listing took 8.009 seconds and tool execution 8.008 seconds, each once. The browser timed out after 15.117 seconds; the server wrote success 0.963 seconds later. Warm and shorter composed controls passed. Baseline run.

Before: synthetic standalone App reports an operation timeout after 15.117 seconds

After: the complete candidate Chromium run passed 2/2 native tests, controller/wrapper exit 0. Catalog8s+call8s completed visibly in 16.069 seconds, with one listing and one successful tool call; warm8s and catalog8s+call1s controls completed in 8.146 and 9.052 seconds. Candidate run retained 63 integrity-checked artifacts. The linked lease workflow may appear cancelled following external cleanup; its actual native/controller/wrapper results were successful. This is distinct from required exact-head CI.

After: the synthetic standalone App displays one successful composed operation after 16.069 seconds

Both official App teardown callbacks completed exactly one cleanup-save RPC before the captured App frame detached. All five cancellation/recovery scenarios completed with fresh-call controls, including transport cancellation, no late browser settlement and an independent catalog waiter. Ordinary Back/Forward recorded fresh document time origins, pageshow.persisted=false, no-store responses and one correlated successful fresh tool call. These are real Gateway/HTTP/stdio/official-App flows with a source-mounted Control UI component and synthetic data—not a full dashboard/model turn or installed-package test.

Authentic owner regressions failed before repair; the final two-file Gateway suite passed 53/53. Coverage includes actual HTTP disconnect/partial-upload cases, serialized-host lifecycle, cleanup, typed IDs, shared catalog waits and retired bodies. The async-authorization regression uses the real handler with a synthetic close event, not a TCP disconnect; its corrected plain-async runtime reproduced the orphan without suppressing global rejection handlers. Canonical owning types, lint and guards passed.

Both fresh full-candidate reviews completed with no findings. Published head cd8784239784d76ec743da300fc9f521330327f9 contains the rebased repair and a separate diagnostic-helper fix. All six MCP production owners and browser assertions remain unchanged from the live-tested candidate. The helper uses Playwright's immediate rendered-text API instead of a lint suppression, without adding a wait or weakening an assertion; its text and metadata samples are not atomic.

Fresh published-head proof: CI 33146017570 completed successfully. The dedicated real-Gateway MCP job ran the complete conformance file: 2/2 passed, bridge 12.324 seconds, composed-operation/cancellation 40.730 seconds, total 98.44 seconds. Its actual target and harness checkout was synthetic merge cb522be4468c92b7683f708495103c318bef2920, combining this published head with main 60dc0203cd35614c2273cede8d1c8193c3b1e75a; it was not a direct detached-head run. The fetched merge object has the expected parents and 18/19 candidate files byte-identical; the remaining assertion baseline exactly preserves the CI base plus this PR's original deletion. All runtime, test and diagnostic-helper bytes match. The PR check snapshot is 231 passed, 42 conditional skips, no failures or pending checks; the required CI gate and both dependency detector/guard checks passed. Native preparation passed without changing the published head. The normal pinned squash merge completed on August 28, 2026, at 06:33:50 UTC: a29e5c9a312f90a6d10643ded834a76b2dc4e863. The landed tree preserves all 18 non-baseline candidate files byte-for-byte; the assertion baseline is the complete landed parent baseline minus the original standalone entry. The entire landed tree was verified against that expected merge context, and Git's terminal-trailer parser confirms the original contributor credit exactly once.

The previous CI run exposed three separate failures: the unrelated UI selector issue is fixed by #131541; this helper change fixes the suppression inventory failure (focused inventory: 4/4 passed); and the updater's hidden child-process failure was not reproduced by a subsequent complete 87-test Linux updater-file run. That 87-test result does not reproduce or waive the original full shard. The prior dependency detector's HTTP 500 is retained separately, not relabelled as candidate success.

Earlier candidate failures remain recorded: attempt 1 failed two fixture assertions; attempt 2 passed the bridge test but failed a history-navigation wait. Repairs bind observations to the actual frame, verify a new document when reopening, and use supported browser defaults for history. No product timeout, cache header, retry or assertion was relaxed.

Independent source-blind validation reports 6 passed, 0 failed, 1 blocked. Supplemental recorded frames resolve standalone model-denial/resource-body observations; only expiry-specific causal evidence remains blocked. Combined native and independent source-aware evidence was accepted for the changed repair and unchanged authorization boundary.

Playwright 1.62.1 does not support BFCache restoration and documents possible navigation timeouts/desynchronization when enabled. Ordinary history and serialized-owner page-event regressions are not live BFCache/Safari proof. See the Playwright navigation limitation.

The latest completed ClawSweeper review, reviewed at 06:02 UTC on this head, raised one changelog-policy P2. Disposition: retained under explicit maintainer direction. The user's instructions require a changelog entry for this user-facing fix and contributor credit, overriding the generic release-only policy; this is not a version release or artifact publication. The exact-head behavior/proof request and Rank-up move are addressed by the public full-file Gateway/Chromium job and successful full CI linked above. The optional additional detailed trace upload is skipped: no new raw traces or media are uploaded, and the existing before/after images retain their historical v7a identity. Direct SDK inspection, real managed transport execution and independent source reviews cover the runtime contract. The +92 production lines remain bounded to the six request/lifecycle owners while deleting the old timer, inline host and timeout projection. The detected 'serialized state' is executable browser closure/test fixture code, not persistent-store or schema change. Earlier lease-snapshot advice is superseded by removing the invalid composed timer; the historical raw-query artifact finding remains rejected, with its original exit1 preserved. No duplicate re-review was requested for this proof-only update.

Production +451/-359 (net +92); tests/support +2412/-687; guard tooling/baseline +2/-3; docs/changelog +5. Pure moves inflate raw churn. Retained production growth establishes request, document and graceful-cleanup ownership while removing the old timer, handler-wrapper path and private timeout projection.

Scoped follow-ups: Control UI remote WebSocket cancellation, native adapters without ambient request cancellation, upstream SDK numeric-zero cancellation, and remove-first dashboard integration. The fixture exercises public teardown before DOM removal. A separate hook follow-up is recorded: a retained REBASE_HEAD can select the pre-commit sequencer shortcut after a completed rebase; this exact helper passed an explicit formatter check. This PR is merged; no post-squash runtime run is claimed beyond the exact-head CI and source-parity evidence above.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: XS labels Aug 5, 2026
@tzy-17
tzy-17 marked this pull request as ready for review August 5, 2026 00:48
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. labels Aug 5, 2026
@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 28, 2026, 2:02 AM ET / 06:02 UTC.

ClawSweeper review

What this changes

This PR gives standalone MCP App browser requests their own HTTP lifetime, propagates cancellation into managed MCP calls without stopping shared catalog refreshes, and expands lifecycle and conformance coverage.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⛔ Blocked until stronger real behavior proof is added - 4 items remain

Keep open: the patch has one introduced, repairable policy defect and lacks verified exact-head real-behavior proof; no merged replacement was established.

Priority: P1
Reviewed head: cd8784239784d76ec743da300fc9f521330327f9

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation follows the reviewed owner boundaries, but it needs the changelog cleanup and exact-head real behavior evidence.
Proof confidence 🦐 gold shrimp (3/6) Needs stronger real behavior proof before merge: The PR body describes real earlier-candidate behavior, but exact-head Gateway/Chromium conformance output or an inspectable artifact was not available for verification. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: The PR body describes real earlier-candidate behavior, but exact-head Gateway/Chromium conformance output or an inspectable artifact was not available for verification. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 5 items Introduced policy defect: The introduced changelog bullet is release-owned material; the applicable ClawSweeper policy says normal repairs must keep release-note context in the PR body or squash message rather than edit CHANGELOG.md.
Cancellation ownership: The Gateway creates a request controller, watches client disconnect, revalidates the ticket immediately before privileged work, and avoids a response after cancellation.
Shared-refresh isolation: The operation layer races only the departing caller against the session catalog promise, preserving the shared catalog producer for other callers.
Findings 1 actionable finding [P2] Remove the release-owned changelog entry
Security None None.

How this fits together

Standalone MCP Apps run inside a browser shell served by Gateway. The shell validates a ticketed view, invokes session MCP tools and resources through Gateway, and returns results or cancellation to the App.

flowchart LR
A[Standalone App window] --> B[Gateway HTTP request]
B --> C[Ticket and view validation]
C --> D[MCP App operation]
D --> E[Session MCP runtime]
E --> F[MCP server]
F --> G[Result or cancellation]
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: The PR body describes real earlier-candidate behavior, but exact-head Gateway/Chromium conformance output or an inspectable artifact was not available for verification. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Remove the release-owned changelog entry (P2) - This introduced release-note bullet edits CHANGELOG.md, which the applicable policy reserves for releases. Keep the user-facing release context in the PR body or squash message and remove this line.
  • Resolve merge risk (P1) - Existing standalone Apps change cancellation and restored-page lifecycle behavior; exact-head Gateway/Chromium conformance evidence is still needed before merge.
  • Resolve merge risk (P1) - The introduced production code is net +92 lines; the added lifecycle ownership and stale-completion guards are plausible justification, but should remain bounded to this owner surface.

Findings

  • [P2] Remove the release-owned changelog entry — CHANGELOG.md:72
Agent review details

Security

None.

PR surface

Source +1076, Tests +741, Docs +5, Other -1. Total +1821 across 19 files.

View PR surface stats
Area Files Added Removed Net
Source 9 1435 359 +1076
Tests 5 1428 687 +741
Docs 2 5 0 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 3 2 3 -1
Total 19 2870 1049 +1821

Review metrics

Metric Value Why it matters
Production versus test delta production +451/-359 (net +92); tests/test support +2412/-687 (net +1725); docs/tooling/changelog +7/-3 The production growth implements request/document lifecycle ownership and cancellation guards, while most introduced volume is conformance coverage and test support.

Stored data model

Persistent data-model change detected: serialized state: src/gateway/mcp-app-standalone-host.ts, serialized state: ui/src/test-helpers/mcp-app-conformance-fixture.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Complete the focused repair and proof (recommended)
    Remove the added release-owned changelog bullet and attach exact-head redacted real Gateway/Chromium conformance evidence before merging.

Technical review

Best possible solution:

Remove the release-owned changelog entry and publish redacted exact-head Gateway-plus-Chromium conformance output that demonstrates the intended request lifecycle.

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

Yes in source: a catalog refresh followed by a valid tool request previously used one complete-operation deadline; this review did not execute the failing flow.

Is this the best way to solve the issue?

Yes for the runtime path: retain session-owned per-RPC budgets while making the browser HTTP caller own cancellation; the changelog entry must be removed before merge.

Full review comments:

  • [P2] Remove the release-owned changelog entry — CHANGELOG.md:72
    This introduced release-note bullet edits CHANGELOG.md, which the applicable policy reserves for releases. Keep the user-facing release context in the PR body or squash message and remove this line.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.9

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 23a681efa6fc.

Labels

Label justifications:

  • P1: The PR addresses standalone App operations that can otherwise remain visibly stalled during a valid catalog-refresh-plus-RPC flow.
  • merge-risk: 🚨 compatibility: The patch changes cancellation, teardown, and restored-page behavior for existing standalone MCP Apps.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The PR body describes real earlier-candidate behavior, but exact-head Gateway/Chromium conformance output or an inspectable artifact was not available for verification. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

Acceptance criteria:

  • [P1] git diff --check.

What I checked:

  • Introduced policy defect: The introduced changelog bullet is release-owned material; the applicable ClawSweeper policy says normal repairs must keep release-note context in the PR body or squash message rather than edit CHANGELOG.md. (CHANGELOG.md:72, bbbc8c30bf14)
  • Cancellation ownership: The Gateway creates a request controller, watches client disconnect, revalidates the ticket immediately before privileged work, and avoids a response after cancellation. (src/gateway/mcp-app-standalone.ts:350, bbbc8c30bf14)
  • Shared-refresh isolation: The operation layer races only the departing caller against the session catalog promise, preserving the shared catalog producer for other callers. (src/gateway/mcp-app-operations.ts:100, bbbc8c30bf14)
  • Documented contract: The docs specify a 30-second initial load, per-request server budgets, cancellation propagation, bounded teardown, and reload after restored history. Public docs: docs/cli/mcp.md. (docs/cli/mcp.md:957, bbbc8c30bf14)
  • Current-main limitation: The checkout’s promisor clone could not materialize some current-main objects because its configured remote could not resolve, so current-main equivalence was not independently inspected. (23a681efa6fc)

Likely related people:

  • steipete: Peter Steinberger authored the current request-lifetime rewrite and the relevant introduced Gateway code is attributed to that commit. (role: recent area contributor; confidence: high; commits: bbbc8c30bf14; files: src/gateway/mcp-app-standalone.ts, src/gateway/mcp-app-standalone-host.ts)
  • xialonglee: The merged standalone-fetch timeout repair is adjacent historical work on the same MCP App surface. (role: prior standalone-host contributor; confidence: medium; commits: f50260764af1; files: src/gateway/mcp-app-standalone.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Remove the release-owned changelog entry.
  • Attach redacted exact-head Gateway and Chromium conformance output or artifact showing the repaired request lifecycle.

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 (4 earlier review cycles)
  • reviewed 2026-08-26T01:23:00.084Z sha d5dc1ac40b9f3bad183cf44715c27b53db9c23ae :: needs real behavior proof before merge. :: [P1] Persist the server timeout with the view | [P1] Remove the fixed two-phase operation bound
  • reviewed 2026-08-26T02:05:42.733Z sha d5dc1ac40b9f3bad183cf44715c27b53db9c23ae :: needs real behavior proof before merge. :: [P1] Persist the server timeout on the view lease
  • reviewed 2026-08-28T04:00:02.363Z sha 624aae3b227fef91e942c7ca70af4882ac558e12 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-28T04:26:08.865Z sha e2ee974c2b08b064424bdd95111417ec600520d1 :: needs real behavior proof before merge. :: none

@tzy-17

tzy-17 commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

Fix for ClawSweeper P2 finding + proof

Finding addressed: "Keep the deadline active through JSON body consumption"

Root cause: The initial fetchWithDeadline helper used .finally() to clear the timer, but fetch() resolves when response headers arrive - before response.json() reads the body. A gateway that sends headers then stalls its body would still hang the MCP App UI indefinitely.

Fix: Refactored to a callback-based withFetchDeadline that wraps the entire fetch-and-consume lifecycle:

const withFetchDeadline = async <T>(
  input: string,
  init: RequestInit,
  consume: (response: Response) => Promise<T>,
): Promise<T> => {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), MCP_APP_FETCH_TIMEOUT_MS);
  try {
    const response = await fetch(input, { ...init, signal: controller.signal });
    return await consume(response);
  } finally {
    clearTimeout(timer);
  }
};

The AbortController signal stays active from fetch() through response.json(). The timer is only cleared in finally after consume(response) completes or throws.

Regression test proof

Added two tests to src/gateway/mcp-app-standalone.test.ts:

  1. "aborts during stalled body consumption after the deadline" - mocks fetch to resolve headers immediately but stall .json() until the abort signal fires. Advances fake timers to 29,999ms (still pending), then past 30,000ms (abort fires). Verifies the promise rejects with "aborted", proving the timer covers body consumption.

  2. "clears the timer after successful body consumption" - verifies no unhandled abort fires after a successful body read.

Test output

node scripts/run-vitest.mjs src/gateway/mcp-app-standalone.test.ts

 ?  gateway-core  ../../src/gateway/mcp-app-standalone.test.ts (11 tests) 167ms

 Test Files  1 passed (1)
      Tests  11 passed (11)

Head SHA: aa2f3401

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 5, 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 repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@tzy-17

tzy-17 commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

P2 finding fixed: withFetchDeadline now wraps the full fetch-and-consume lifecycle (timer cleared in finally after consume(response) returns, not after fetch() resolves). Real behavior proof added to PR body: real-timer script with 200ms deadline shows fixed version aborts stalled body at 203ms while old buggy pattern hangs past 600ms. Two regression tests added (stalled body abort + timer cleanup), 33/33 tests pass across 3 projects.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. P2 Normal backlog priority with limited blast radius. labels Aug 5, 2026
@tzy-17

tzy-17 commented Aug 6, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

P1 fixed: Derive operation deadlines from the MCP server budget

  • The gateway now carries the owning server's requestTimeoutMs (from peekCatalog) into the view payload as operationTimeoutMs
  • The browser-side host uses operationTimeoutMs + 5s grace for operation fetches (tools/call, resources/read, etc.)
  • The initial view load keeps its fixed 30s budget (view metadata only, not tool results)
  • A valid 30–60s MCP operation is no longer aborted in the UI while runtime.callTool continues server-side

P2 fixed: Execute the generated standalone shell in the deadline test

  • Replaced the duplicated withFetchDeadline test helper with execution of the actual serialized runStandaloneMcpAppHost.toString() shell extracted from the handler's HTML response
  • Tests now use new Function(bootstrap)() with stubbed browser APIs (document, location, fetch, etc.), following the Telegram Mini App timeout test pattern
  • The deadline tests cannot drift from the shipped browser artifact

Acceptance criteria verified:

  • node scripts/run-vitest.mjs src/gateway/mcp-app-standalone.test.ts — 33/33 passed across 3 projects (incl. 2 serialized-shell deadline tests)
  • node scripts/run-vitest.mjs src/agents/mcp-transport-config.test.ts — 10/10 passed (MCP timeout contract)
  • npx oxlint — 0 warnings, 0 errors
  • npx oxfmt --check — all correct

Head SHA: b5a4b4be4c4

@clawsweeper

clawsweeper Bot commented Aug 6, 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 repository_dispatch).
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 added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Aug 6, 2026
@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Aug 7, 2026
@tzy-17

tzy-17 commented Aug 7, 2026

Copy link
Copy Markdown
Contributor Author

P1 fix: persist operation timeout on the view lease + real browser proof

Finding addressed: "Persist the operation timeout with the view (P1)"

Root cause: peekCatalog() is cache-only and can be invalidated after the view lease is created (failures, listChanged events, disposal). When the standalone host reread the catalog at view-load time, a server configured above 60s got the 60s fallback. The browser then aborted a valid long-running operation at 65s while runtime.callTool continued server-side up to the configured budget — inviting duplicate side effects on retry.

Fix: Capture the owning server's requestTimeoutMs on the McpAppViewLease at creation time (fetchMcpAppView already ran readResource → await getCatalog(), so the snapshot is populated). The standalone host serializes that stable value instead of rereading the volatile catalog.

The snapshotted value is config-derived and stable for the session lifetime — it matches the budget callTool uses server-side (session.requestTimeoutMs), so the browser deadline correctly tracks the server-side budget even after catalog invalidation.

Files changed:

  • src/agents/mcp-ui-resource.ts — added operationTimeoutMs?: number to McpAppViewLease; snapshot in fetchMcpAppView
  • src/gateway/mcp-app-standalone.ts — read view.operationTimeoutMs instead of runtime.peekCatalog()?.servers[view.serverName]?.requestTimeoutMs

Regression tests

  1. src/agents/mcp-ui-resource.test.ts — "snapshots the server requestTimeoutMs on the view lease at creation time": proves the timeout is captured at view creation and remains stable after peekCatalog() returns null (catalog invalidation).

  2. src/gateway/mcp-app-standalone.test.ts — "keeps the snapshotted operation timeout after catalog invalidation": proves the standalone host serializes the snapshotted value (90_000) when peekCatalog() returns null, not the 60s fallback.

Real browser-to-Gateway proof

Served the actual serialized runStandaloneMcpAppHost shell (extracted from handleMcpAppStandaloneHttpRequest's HTML response) from a real HTTP server and loaded it in Chrome.

Stalled-response trace (timeout fires):

  • Server: view endpoint sent 200 + headers, then withheld the body indefinitely.
  • Browser loaded the real shell, fetched /__openclaw__/mcp-app/view.
  • After 30s, the real withFetchDeadline AbortController fired:
    [error] net::ERR_ABORTED http://127.0.0.1:18999/__openclaw__/mcp-app/view
        at withFetchDeadline (http://127.0.0.1:18999/__openclaw__/mcp-app:87:26)
        at runStandaloneMcpAppHost (http://127.0.0.1:18999/__openclaw__/mcp-app:260:6)
    
  • Server log confirmed: view endpoint STALLED (headers sent, body withheld)

Recovery trace (successful operation, timer cleared):

  • Server: view endpoint returned a complete 172-byte JSON payload.
  • Browser loaded the shell, fetched the view, consumed the body successfully.
  • No ERR_ABORTED on the view fetch — the timer was cleared in the finally block after body consumption.
  • Server log confirmed: view endpoint returned complete payload (172 bytes)

Test output

node scripts/run-vitest.mjs src/gateway/mcp-app-standalone.test.ts
 gateway-core  ../../src/gateway/mcp-app-standalone.test.ts (12 tests) 1070ms
 Test Files  1 passed (1)
      Tests  12 passed (12)

node scripts/run-vitest.mjs src/agents/mcp-ui-resource.test.ts
 agents  src/agents/mcp-ui-resource.test.ts (11 tests) 1038ms
 Test Files  1 passed (1)
      Tests  11 passed (11)

node scripts/run-vitest.mjs src/agents/mcp-transport-config.test.ts
 agents  src/agents/mcp-transport-config.test.ts (10 tests) 556ms
 Test Files  1 passed (1)
      Tests  10 passed (10)

Static checks: oxlint 0 warnings/errors, oxfmt --check all correct, tsgo clean (only unrelated src/media/fetch.ts errors from a separate working-tree change).

Head SHA: a0edd43839d

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 7, 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 repository_dispatch).
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 added proof: sufficient ClawSweeper judged the real behavior proof convincing. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 7, 2026
@clawsweeper clawsweeper Bot added the status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. label Aug 7, 2026
@tzy-17

tzy-17 commented Aug 7, 2026

Copy link
Copy Markdown
Contributor Author

Addressing the [P1] Cover catalog refresh in the operation deadline finding — pushed in commit d5dc1ac.

Root cause

The P1 finding is correct: a single browser operation request can span two server-side phases that each consume up to requestTimeoutMs:

  1. Catalog rebuild — executeMcpAppOperation -> requireCallableTool -> runtime.getCatalog() (src/gateway/mcp-app-operations.ts:103). When the catalog is invalidated (invalidateCatalog() in agent-bundle-mcp-runtime.ts:427), the next getCatalog() awaits loadCatalog(), which issues listTools per server with timeout: requestTimeoutMs. callTool itself also calls getCatalog() first (line 1030).
  2. Upstream call — runtime.callTool issues client.callTool(..., { timeout: session.requestTimeoutMs, signal }) (agent-bundle-mcp-runtime.ts:1043).

So the worst-case server-side work for one browser request is 2 * requestTimeoutMs, but the previous deadline was operationTimeoutMs + 5s (one budget plus grace). A valid long-running call would be aborted in the UI while callTool continued server-side — recreating the duplicate-side-effect risk this PR is meant to prevent.

Fix

Double the operation deadline so the browser request covers the full server-side lifecycle:

const OPERATION_TIMEOUT_PHASES = 2;
const operationDeadlineMs =
  OPERATION_TIMEOUT_PHASES * (payload?.operationTimeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS) +
  OPERATION_TIMEOUT_GRACE_MS;

The initial view load keeps its fixed 30s budget (it only fetches view metadata, not tool results). The previous a0edd43 attempt (snapshotting requestTimeoutMs on the view lease) was reverted because it only fixed the peekCatalog() fallback-to-60s case, not the multiplier.

Verification

Regression test covers catalog rebuild plus upstream call in the operation deadline via the serialized shell executes the actual serialized runStandaloneMcpAppHost shell (not a reimplementation), drives it through a real tools/call over a stalled POST fetch, and asserts:

  • at 95_000ms (the old single-budget deadline of 90_000 + 5_000) the operation is NOT aborted
  • at 185_000ms (the doubled lifecycle deadline of 2 * 90_000 + 5_000) the operation IS aborted with -32000 "aborted"
✓ gateway-core  ../../src/gateway/mcp-app-standalone.test.ts (12 tests) 182ms
 Test Files 1 passed (1)
      Tests 12 passed (12)

The test fails on the pre-fix formula (aborts at 95s) and passes on the doubled formula (aborts at 185s), confirming it locks in the lifecycle coverage.

Static checks: oxlint 0 warnings/0 errors; oxfmt --check all correct; tsgo produces no new errors in the changed files (the two pre-existing cache: "no-store" RequestInit errors on lines 368/536 are unchanged by this PR). Sibling src/agents/mcp-transport-config.test.ts (10 tests) still passes — the MCP timeout contract is intact.

This also resolves the Resolve merge risk (P2) item, since the merge-risk scenario (browser aborting a still-valid server-side operation) is the same lifecycle gap.

@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. and removed merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Aug 19, 2026
@steipete steipete self-assigned this Aug 27, 2026
@steipete
steipete force-pushed the fix/mcp-app-standalone-fetch-timeout branch from d5dc1ac to 624aae3 Compare August 28, 2026 03:51
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui scripts Repository scripts agents Agent runtime and tooling size: XL and removed size: M labels Aug 28, 2026
@steipete
steipete force-pushed the fix/mcp-app-standalone-fetch-timeout branch from 624aae3 to e2ee974 Compare August 28, 2026 04:11
@steipete steipete changed the title fix(mcp-app): bound standalone host fetches with timeout fix(gateway): own standalone MCP App request lifetimes Aug 28, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 28, 2026
Keep initial loading and individual MCP requests bounded without applying
a derived single-request timeout to composed App operations. Carry caller
cancellation through the HTTP request owner, isolate shared catalog waits,
and preserve bounded graceful cleanup before terminal document teardown.

Retire stale document/bootstrap responses and observe asynchronous catalog
rejections without changing authorization, public SDK contracts, or retry
behavior. Add serialized-owner regressions and real Chromium conformance.

Rewrites openclaw#119388 while preserving the contributor's report and credit.

Co-authored-by: 唐梓夷0668001293 <[email protected]>
@steipete
steipete force-pushed the fix/mcp-app-standalone-fetch-timeout branch from e2ee974 to cd87842 Compare August 28, 2026 05:51
@steipete
steipete merged commit a29e5c9 into openclaw:main Aug 28, 2026
279 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 28, 2026
* fix(gateway): own standalone MCP App request lifetimes

Keep initial loading and individual MCP requests bounded without applying
a derived single-request timeout to composed App operations. Carry caller
cancellation through the HTTP request owner, isolate shared catalog waits,
and preserve bounded graceful cleanup before terminal document teardown.

Retire stale document/bootstrap responses and observe asynchronous catalog
rejections without changing authorization, public SDK contracts, or retry
behavior. Add serialized-owner regressions and real Chromium conformance.

Rewrites openclaw#119388 while preserving the contributor's report and credit.

Co-authored-by: 唐梓夷0668001293 <[email protected]>

* test(ui): preserve rendered MCP App diagnostics without suppression

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: 唐梓夷0668001293 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants