Skip to content

Fix browser timeout propagation for local actions and CLI commands - #39277

Closed
lampten wants to merge 5 commits into
openclaw:mainfrom
lampten:fix/browser-timeout-abort-forwarding
Closed

lampten wants to merge 5 commits into
openclaw:mainfrom
lampten:fix/browser-timeout-abort-forwarding

Conversation

@lampten

@lampten lampten commented Mar 8, 2026 •

Copy link
Copy Markdown

AI-assisted: yes (Codex).
Testing: focused regression tests + pnpm build; pnpm check is still blocked by unrelated pre-existing repo failures.

Summary

Describe the problem and fix in 2–5 bullets:

  • Problem: local browser.request timeouts only stopped the caller; the in-process Playwright work kept running, and several browser CLI subcommands also overrode the parent browser --timeout with hardcoded defaults.
  • Why it matters: once a slow type / click / snapshot path timed out, later interactive browser requests could degrade into more timeouts against the same attached session, and users could not reliably tune CLI timeout behavior.
  • What changed: propagate timeout/abort through local browser dispatch, thread req.signal through browser route handlers and Playwright helpers, force-disconnect the target CDP session when an action/snapshot is aborted, and make browser CLI timeout resolution consistent (--timeout-ms > parent browser --timeout > fallback default).
  • What did NOT change (scope boundary): this does not add new browser capabilities, new timeout flags, or change the remote browser request protocol beyond honoring the existing timeout/abort semantics.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

User-visible / Behavior Changes

  • Timed out local browser actions/snapshots now abort more cleanly instead of leaving the attached Playwright/CDP target stuck for follow-up requests.
  • Parent browser --timeout now applies consistently across browser CLI subcommands unless a more specific --timeout-ms flag is provided.

Security Impact (required)

  • New permissions/capabilities? (Yes/No) No
  • Secrets/tokens handling changed? (Yes/No) No
  • New/changed network calls? (Yes/No) No
  • Command/tool execution surface changed? (Yes/No) No
  • Data access scope changed? (Yes/No) No
  • If any Yes, explain risk + mitigation:

Repro + Verification

Environment

  • OS: Linux arm64 (Raspberry Pi host for the live repro) and local Linux dev environment for source validation
  • Runtime/container: Node.js workspace via pnpm
  • Model/provider: N/A
  • Integration/channel (if any): local browser gateway; original end-to-end repro came through Telegram
  • Relevant config (redacted): attached Chromium session (attachOnly: true), persistent openclaw profile, local CDP endpoint, local gateway websocket

Steps

  1. Attach OpenClaw to a persistent Chromium/CDP session and confirm browser status, browser tabs, and browser snapshot succeed.
  2. Run an interactive browser action such as browser act kind=type ... --submit on Gemini or browser act kind=click ... on http://example.com/.
  3. Observe the timeout/abort path and then retry follow-up browser actions against the same attached tab/session.

Expected

  • Timed out browser work should abort cleanly, and follow-up actions should still be able to reuse the session.
  • Parent browser CLI timeouts should flow through to subcommands unless explicitly overridden.

Actual

  • Before this change, the caller timed out first while the local Playwright work could continue in the background, which left later interactive requests prone to more timeouts.
  • Several browser CLI subcommands kept using hardcoded timeout defaults even when browser --timeout was set.

Evidence

Attach at least one:

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Human Verification (required)

What you personally verified (not just CI), and how:

  • Verified scenarios: the equivalent runtime hotfix was exercised end-to-end against a live attached Chromium session on Raspberry Pi (Gemini snapshot + type --submit, plus example.com click flows), and the source changes were covered by focused regression tests plus pnpm build.
  • Edge cases checked: local gateway timeout forwarding, route-level signal propagation for actions and snapshots, abort-triggered Playwright disconnect/recovery, parent CLI browser --timeout precedence, and explicit subcommand --timeout-ms override behavior.
  • What you did not verify: full pnpm check is still blocked by unrelated pre-existing tsgo errors in other packages/extensions, and I did not do a new cross-platform browser matrix beyond the reproduced Linux arm64 attach-only flow.

Compatibility / Migration

  • Backward compatible? (Yes/No) Yes
  • Config/env changes? (Yes/No) No
  • Migration needed? (Yes/No) No
  • If yes, exact upgrade steps:

Failure Recovery (if this breaks)

  • How to disable/revert this change quickly: revert this PR/commit; the behavior is isolated to browser timeout propagation, abort handling, and CLI timeout resolution.
  • Files/config to restore: the touched browser gateway, browser route/helper, and browser CLI files in this PR.
  • Known bad symptoms reviewers should watch for: aborted browser actions unexpectedly dropping a healthy session, or CLI browser subcommands ignoring an explicit parent timeout again.

Risks and Mitigations

List only real risks for this PR. Add/remove entries as needed. If none, write None.

  • Risk: force-disconnecting the Playwright/CDP target on abort could drop transient in-flight browser state for that target.
    • Mitigation: the disconnect is only triggered for aborted work, is scoped to the current target, and is preferable to leaving the session wedged for follow-up requests.
  • Risk: users who implicitly relied on subcommand hardcoded defaults may notice the parent browser --timeout now taking effect.
    • Mitigation: explicit per-command --timeout-ms still wins, and the new precedence matches the documented/top-level CLI behavior.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime cli CLI command changes size: XL labels Mar 8, 2026
@lampten lampten changed the title [AI-assisted] Browser: propagate local action aborts and honor CLI timeout forwarding Fix browser timeout propagation for local actions and CLI commands Mar 8, 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: 8d86ac2da7

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +36 to +39
await forceDisconnectPlaywrightForTarget({
cdpUrl: opts.cdpUrl,
targetId: opts.targetId,
reason: "abort browser action",

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.

P1 Badge Scope abort disconnects to the current target

This abort path now runs for most act/snapshot operations, but forceDisconnectPlaywrightForTarget tears down the shared Playwright connection for the entire cdpUrl (it clears global cached state in src/browser/pw-session.ts), not just the provided targetId. In concurrent usage (multiple tabs/channels on one profile), a timeout in one request can now drop unrelated in-flight requests, which is a new cross-request regression introduced by this wrapper.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Good catch. I tightened this so forceDisconnectPlaywrightForTarget() first does the target-local Runtime.terminateExecution, and it only tears down the shared cached Playwright/CDP connection when that connection is effectively single-page. In multi-page shared sessions it now returns after the target-local terminate, so an abort on one tab no longer drops unrelated tabs/requests on the same cdpUrl.

Comment on lines +47 to +49
normalizeTimeoutMs(params?.explicitMs) ??
parseParentTimeoutMs(opts) ??
normalizeTimeoutMs(params?.fallbackMs)

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 Preserve fallback timeouts when parent timeout is defaulted

resolveBrowserRequestTimeoutMs prefers opts.timeout before fallbackMs, but the browser CLI always defines --timeout with a default of 30000 (src/cli/gateway-rpc.ts), so these new fallback values are effectively never used in normal CLI runs. That silently changes default behavior for commands that previously had shorter fail-fast timeouts (for example status/tabs), causing them to wait the global 30s unless users explicitly override timeout.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Good catch. I now carry the top-level --timeout source into BrowserParentOpts and ignore it when it is still Commander's implicit default. That preserves command-specific fallbacks (status, tabs, etc.) while still letting an explicit parent browser --timeout override them. I also added regression coverage in src/cli/browser-cli-shared.test.ts and src/cli/browser-cli-manage.timeout-option.test.ts.

@greptile-apps

greptile-apps Bot commented Mar 8, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes two related problems: (1) local browser actions/snapshots that timed out only stopped the caller while the underlying Playwright/CDP work kept running, and (2) browser CLI subcommands used hardcoded timeout defaults instead of respecting the parent browser --timeout flag. The changes propagate AbortSignal from the gateway through route handlers down to individual Playwright helpers, add a forceDisconnectPlaywrightForTarget call when an action or snapshot is aborted, and introduce resolveBrowserRequestTimeoutMs to provide consistent explicit > parent > fallback timeout resolution across all CLI subcommands.

Key observations:

  • The abort flow is well-structured: withTimeout in the gateway creates an AbortController, the signal is threaded through dispatcher.dispatch into runAbortablePlaywrightAction/runAbortableSnapshotWork, and the Playwright target is force-disconnected when the abort fires. Tested by new focused unit tests for click/snapshot abort and gateway local-timeout.
  • runAbortablePlaywrightAction (in pw-tools-core.interactions.ts) and runAbortableSnapshotWork (in pw-tools-core.snapshot.ts) are functionally identical except for the disconnect reason string — this duplication is a maintenance risk that should be addressed through a shared helper.

Confidence Score: 5/5

  • Safe to merge. The abort propagation and timeout resolution logic is sound and well-tested.
  • This PR is safe to merge. The core abort-handling pattern is correct: Promise.race, guard flags (completed/abortTriggered), listener cleanup, and workPromise rejection suppression all work properly. The new test suite covers critical abort paths (click abort, snapshot abort, gateway timeout). The timeout resolution follows a sensible explicit > parent > fallback precedence. One minor code maintenance concern remains: the near-identical abort helpers across two modules should eventually be consolidated to reduce duplication, but this is a style issue that doesn't affect functionality.
  • src/browser/pw-tools-core.interactions.ts and src/browser/pw-tools-core.snapshot.ts for the duplicated abort helper (addressable in a follow-up refactor).

Last reviewed commit: 8d86ac2

Comment on lines +25 to +83
async function runAbortablePlaywrightAction<T>(
opts: TargetOpts & { signal?: AbortSignal },
work: () => Promise<T>,
): Promise<T> {
const signal = opts.signal;
if (!signal) {
return await work();
}

const abortReason = () => signal.reason ?? new Error("aborted");
const disconnect = async () => {
await forceDisconnectPlaywrightForTarget({
cdpUrl: opts.cdpUrl,
targetId: opts.targetId,
reason: "abort browser action",
}).catch(() => {});
};

if (signal.aborted) {
await disconnect();
throw abortReason();
}

let completed = false;
let abortTriggered = false;
let abortListener: (() => void) | undefined;
const abortPromise: Promise<never> = new Promise((_, reject) => {
abortListener = () => {
if (completed || abortTriggered) {
return;
}
abortTriggered = true;
void disconnect().finally(() => reject(abortReason()));
};
signal.addEventListener("abort", abortListener, { once: true });
});

if (signal.aborted) {
abortListener?.();
}
if (abortTriggered) {
return await abortPromise;
}

const workPromise = work().finally(() => {
completed = true;
});

try {
return await Promise.race([workPromise, abortPromise]);
} catch (err) {
void workPromise.catch(() => {});
throw err;
} finally {
if (abortListener) {
signal.removeEventListener("abort", abortListener);
}
}
}

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.

runAbortablePlaywrightAction here and runAbortableSnapshotWork in pw-tools-core.snapshot.ts (lines 29-87) are functionally identical—the only difference is the reason string passed to forceDisconnectPlaywrightForTarget. Any future fix or enhancement to the abort logic (such as adding guards or refining the disconnect timing) would need to be applied in both places, creating a maintenance burden.

Consider extracting this into a shared runAbortableTargetWork<T>(opts, work, reason) helper—perhaps in pw-session.ts or a new pw-tools-core.abort.ts—and re-using it from both modules.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/browser/pw-tools-core.interactions.ts
Line: 25-83

Comment:
`runAbortablePlaywrightAction` here and `runAbortableSnapshotWork` in `pw-tools-core.snapshot.ts` (lines 29-87) are functionally identical—the only difference is the `reason` string passed to `forceDisconnectPlaywrightForTarget`. Any future fix or enhancement to the abort logic (such as adding guards or refining the disconnect timing) would need to be applied in both places, creating a maintenance burden.

Consider extracting this into a shared `runAbortableTargetWork<T>(opts, work, reason)` helper—perhaps in `pw-session.ts` or a new `pw-tools-core.abort.ts`—and re-using it from both modules.

How can I resolve this? If you propose a fix, please make it concise.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@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: ce0c5f2fe4

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +274 to +278
if (!isRetryableNavigateError(err)) {
throw err;
}
// Extension relays can briefly drop CDP during renderer swaps/navigation.
// Force a clean reconnect, then retry once on the refreshed page handle.

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 Stop retrying navigation after request abort

When the request signal aborts during page.goto, runAbortableSnapshotWork disconnects Playwright, which makes goto fail with a retryable "browser/page closed" error. This catch block then unconditionally runs the reconnect+retry path, so a timed-out /navigate request can still complete a background navigation after the caller has already received a timeout. Add an opts.signal?.aborted guard before retrying so aborted requests do not mutate tab state after timeout.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Agreed. I added an abort guard before the retry path (and again after the reconnect helper) so a timed-out /navigate request now exits instead of doing a background reconnect+goto. I also added a regression test in src/browser/pw-tools-core.snapshot.navigate-guard.test.ts that aborts during the first goto and verifies we do not issue the retry navigation.

@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: 4a9ec65793

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

return;
}
abortTriggered = true;
void disconnect().finally(() => reject(abortReason()));

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.

P1 Badge Reject abort race before waiting on disconnect

This abort branch waits for disconnect() to finish before rejecting, so cancellation is delayed by CDP cleanup latency. Because Promise.race([workPromise, abortPromise]) is still running during that delay, a near-complete action can resolve first and the timed-out request still executes in the background (e.g., click/type/navigate mutating tab state after the caller already received a timeout). Reject immediately when the signal aborts and run disconnect in parallel/fire-and-forget so abort reliably wins once raised.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Agreed. I changed both abort helpers so abort now rejects immediately and runs the disconnect cleanup in the background instead of awaiting cleanup before rejecting. That makes the abort side win the race once the signal is raised, even if CDP cleanup is slow. I also added regression coverage in src/browser/pw-tools-core.interactions.abort.test.ts and src/browser/pw-tools-core.snapshot.abort.test.ts that holds disconnect cleanup open and verifies the action/snapshot still rejects instead of resolving.

@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: 013f82842d

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/browser/pw-session.ts Outdated
Comment on lines +682 to +685
await tryTerminateExecutionViaCdp({ cdpUrl: normalized, targetId }).catch(() => {});
const pages = await getAllPages(cur.browser).catch(() => []);
if (pages.length > 1) {
return;

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 Fall back to disconnect when target termination fails

This early return skips shared Playwright disconnect for any multi-page session even if the target-local termination just failed (the error is swallowed on the previous line), so aborted requests can keep running in the background and still mutate page state. That is especially likely on relays where target attach/terminate is unsupported, and it defeats the new abort cleanup path for those environments.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in 8b7a5ee. tryTerminateExecutionViaCdp() now reports whether target-local termination actually succeeded, and multi-page sessions only skip the shared Playwright disconnect on success. If attach/terminate is unsupported or fails, we now fall back to the disconnect path instead of silently doing nothing. Added regression coverage in src/browser/pw-session.abort-fallback.test.ts.

Comment thread src/cli/browser-cli-shared.ts Outdated
Comment on lines +38 to +39
if (opts.timeoutSource === "default") {
return undefined;

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 Keep implicit 30s timeout for no-fallback browser requests

Dropping opts.timeout whenever the option source is default makes resolveBrowserRequestTimeoutMs return undefined for callers that do not provide a fallback timeout (for example browser start/stop paths), so browser.request no longer carries timeoutMs. In those cases the gateway-side dispatch timeout is disabled and node-side invoke timeout is not enforced, allowing work to continue after the CLI transport timeout expires.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in 8b7a5ee. callBrowserRequest() now falls back to the parsed parent CLI timeout when there is no browser-specific explicit or fallback timeout, so browser.request.timeoutMs still carries the implicit 30s on paths like browser start/stop. Added regression coverage in src/cli/browser-cli-shared.call.test.ts.

@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: 8b7a5ee953

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/browser/pw-session.ts
}
// Also clear `connecting` so the next call does a fresh connectOverCDP
// rather than awaiting a stale promise.
connecting = null;

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 Avoid clearing active connect promise after async checks

forceDisconnectPlaywrightForTarget now awaits target-termination/page-count work before resetting globals, but connecting = null still runs unconditionally afterward. In the abort/retry path, another request can begin a fresh connectBrowser() during those awaits and set a new in-flight connecting promise; this line then wipes that live promise even when cached has already moved off cur, allowing concurrent callers to start duplicate CDP connects instead of coalescing on the same reconnect.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I agree this is a narrower reconnect-coalescing race, but I am leaving it out of this PR to keep the change scoped to timeout/abort correctness. The current behavior could allow duplicate reconnect attempts in that window, but it does not reopen the user-visible regression this PR fixes (requests continuing to mutate tab state after timeout/abort). I would rather handle any cached/connecting reshaping as a separate follow-up.

@lampten

lampten commented Mar 8, 2026

Copy link
Copy Markdown
Author

Superseded by #40305.

v2026.3.7 landed the overlapping pw-session refactor in a075baba8, so this branch now conflicts heavily with main. I re-opened the remaining bugfix on top of current main in a narrower PR that keeps the focus on local browser timeout/abort propagation without reintroducing the old pw-session conflict set.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes gateway Gateway runtime size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant