Skip to content

Add PasClaw Browser: WebView2 tabs with an embedded agent per tab - #604

Merged
FMXExpress merged 2 commits into
mainfrom
claude/browser
Oct 17, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/browser

Conversation

@FMXExpress

@FMXExpress FMXExpress commented Sep 22, 2026 •

Copy link
Copy Markdown
Owner

What this is

A desktop browser, browser-desktop/PasclawBrowser.dproj, where every tab is a TWebBrowser on the Edge/WebView2 engine with a PasClaw chat beside it. The chat can read the page you are looking at and change it.

The agent is the in-process TPasClawAgent component, against your own PASCLAW_HOME. No gateway to start, no port to open. Memory, distilled facts and AGENTS.md are shared with the CLI and web UI because the agent is built from the same config.

Each tab is its own session. The history handed to the agent for a turn is that tab's history and nothing else, and every message is stamped with that tab's current page and selection, so "what is this about?" costs no tool call. Sessions persist under PASCLAW_HOME/workspace/browser/<tab-id>.json.

One agent, one turn at a time. TPasClawAgent is one-per-process (its constructor raises EPasClawInstance on a second live instance), so the form owns one agent with the six tools and two hooks registered once against a TSwitchingBridge. A single worker thread runs tabs' turns in FIFO order, pointing the switching bridge at the sending tab before each turn and clearing it after. A tab that sends while another tab's turn is running is queued and its status line says so.

Not to be confused with the existing browser/ directory, which is the opposite thing (PasClaw's CLI running inside a browser tab via container2wasm). That directory is untouched.

Tools the agent gets

tool
browser_page read-only URL, title, selection, page as text or as an outline of headings/links/fields with handles; 24 KB cap with offset
browser_find read-only CSS selector or visible text → elements with handles
browser_navigate mutating a URL, or back / forward / reload; waits for the load
browser_click mutating click by handle
browser_fill mutating set a field via the prototype setter, firing input/change so React-style pages notice
browser_eval mutating arbitrary JavaScript, the escape hatch

Mutating calls go through a confirm gate: Yes once, Yes to All for that host until the app closes, No (the model is told, so it asks what you'd like instead). The gate refuses outright if no asker is wired. A per-tab checkbox turns it off.

Layout

  • PasClaw.Browser.Bridge — IBrowserBridge (Eval/Navigate/CurrentURL/CurrentTitle), TSwitchingBridge (thread-safe SetCurrent/Shutdown, fails with a named error when no tab is current or the app is closing), and UnwrapJsString, which strips the one JSON quoting layer WebView2 adds to completion values. \uXXXX goes through UnicodeString + UTF8Encode so it is right on both compilers, with surrogate pairs handled.
  • PasClaw.Browser.Tools — the six TPasClawTool descendants above. Elements are addressed by data-pc-handle stamps; a handle is validated (h\d+) before it can reach a selector.
  • PasClaw.Browser.Hooks — TPageContextHook (stamps page + selection onto the last user message, idempotent) and TConfirmMutationHook.
  • PasClaw.Browser.Session — TBrowserSession with JSON save/load.
  • uBrowserMain + .fmx, .dpr, .dproj — the FMX form: TTurnWorker (the one thread turns run on), TFmxBridge with a refcounted TEvalWaiter so a WebView2 callback that fires after the timeout never touches a freed event, TBrowserTab wiring WebView2, address bar, transcript, input and its own bridge; WindowsEngine is set before Parent.

Shutdown

Closing the window mid-turn winds down rather than tearing down: the switching bridge is shut so further page calls fail immediately, queued turns are dropped and told so, the window stays open with a status line, and the turn's completion closes it once the worker is idle. FormDestroy therefore always joins an idle worker and frees the agent, then the tabs. A second close while waiting offers to save sessions and halt, the one exit that is safe from inside a provider call that will not return.

Tests

Nothing in CI can compile the FMX form, so everything that can be wrong in an interesting way lives below it in FPC-compilable units:

  • make test-browser-tools — src/tests/browser_tools_tests.pas, 11 groups against a fake bridge that recognises and records the script it is handed. Covers argument validation, the cap and offset, handle validation, the React-aware fill, the context stamp applied once and only once, the confirm gate (deny / allow once / remember host / refuse without an asker), a UTF-8 round-trip through a real temp file, UnwrapJsString including é and a surrogate pair, and the switching bridge (no current tab fails and reaches no tab; a tool built once follows the current tab; after Shutdown every call fails at once and SetCurrent is ignored).
  • make lint-browser-shape — scripts/check-browser-shape.py, fails the build if WindowsEngine is assigned after Parent or never assigned on a TWebBrowser. This is the bug desktop/ once shipped.
  • Both are in the test aggregate. Full make test on the first commit: 39 passes, 0 make errors.

Each guard was negative-tested (cap removed, handle check removed, gate opened, escape decoding reverted to Chr, the switching bridge's closing check removed) and each failed on the assertion that owns it.

Review fixes (second commit)

Codex raised three P1s on the first cut, all in the FMX glue, all fixed:

  • One agent per tab raised on the second tab. Now one agent, a tested switching bridge, and a serialising worker (above).
  • Eval event freed under a pending callback. Now a refcounted waiter captured by the callback closure.
  • "Close anyway" freed everything under a live turn. Now the wind-down described above; destruction only ever happens with the worker idle.

Known limits

  • Compiled blind. The form has not been through a Delphi compiler here. The EvaluateJavaScript call in TFmxBridge.Eval is the line most likely to need an overload spelled differently for your Delphi version. Delphi 11+ is required for the result-returning overload.
  • One turn at a time across tabs. Top frame only; cross-origin iframes are invisible. Windows only.
  • Closed tabs are not reopened automatically yet; their session files remain.

docs/browser-plan.md is the design note, updated to point at browser-desktop/ and to record the review correction.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6

A desktop browser (browser-desktop/) where each tab pairs a TWebBrowser
on the Edge/WebView2 engine with a PasClaw chat that can read and change
the page. The agent is TPasClawAgent, in-process, one per tab, so there
is no gateway to run and no port to open; memory, facts and AGENTS.md
are shared with the CLI and web UI through the same config.

Layers, from the bottom:

- PasClaw.Browser.Bridge: IBrowserBridge (Eval / Navigate / CurrentURL /
  CurrentTitle) plus UnwrapJsString, which removes the one JSON quoting
  layer WebView2 adds to completion values, decoding \uXXXX through
  UnicodeString + UTF8Encode so it is correct on both compilers and
  handles surrogate pairs.
- PasClaw.Browser.Tools: six TPasClawTool descendants (browser_page,
  browser_find, browser_navigate, browser_click, browser_fill,
  browser_eval). Elements are addressed by data-pc-handle stamps; a
  handle is validated before it reaches a selector; page text is capped
  at 24 KB with an offset; fill goes through the prototype setter and
  fires input/change so React-style pages notice.
- PasClaw.Browser.Hooks: TPageContextHook stamps the current page and
  selection onto each user message once; TConfirmMutationHook gates the
  mutating tools behind a Yes / Yes-to-all-for-host / No prompt and
  refuses when no asker is wired.
- PasClaw.Browser.Session: TBrowserSession, persisted as JSON under
  PASCLAW_HOME/workspace/browser/<id>.json, one per tab.
- uBrowserMain (+ .fmx), PasclawBrowser.dpr/.dproj: the FMX form, with
  TFmxBridge marshalling Eval to the UI thread and a UI-thread deadlock
  guard, tabs, per-tab agent wiring and the confirm dialog. Delphi 11+,
  Windows. Compiled blind: no Delphi in CI.

Everything below the form compiles under FPC and runs in make test:
src/tests/browser_tools_tests.pas (10 groups against a fake bridge) via
the new test-browser-tools target, and scripts/check-browser-shape.py
via lint-browser-shape, which fails the build if WindowsEngine is set
after Parent or never set, the bug desktop/ once shipped.

The unrelated browser/ directory (container2wasm) is untouched; the plan
in docs/browser-plan.md is updated to point at browser-desktop/.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6

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

Copy link
Copy Markdown

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: dc852e181d

ℹ️ 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 browser-desktop/uBrowserMain.pas Outdated
ones the CLI and web UI use. What is per-tab is the history, the
tools' bridge, and the hooks' bridge -- which is what makes the agent
act on THIS page and remember THIS conversation. *)
FAgent := TPasClawAgent.Create(nil);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Reuse one agent instead of constructing one per tab

Creating a second tab constructs another TPasClawAgent, but that class's constructor explicitly raises EPasClawInstance whenever another agent is live because MCP and skills use process-global state. Consequently, clicking “+ Tab” while the initial tab exists raises an uncaught exception, so the advertised multi-tab workflow cannot work without sharing one agent, removing the singleton constraint, or otherwise serializing agent ownership.

Useful? React with 👍 / 👎.

Comment thread browser-desktop/uBrowserMain.pas Outdated
Comment on lines +221 to +230
if Done.WaitFor(TimeoutMs) <> wrSignaled then
begin
Err := Format('script did not complete within %d ms', [TimeoutMs]);
Exit;
end;
{ One layer of JSON quoting off, per the bridge contract. }
Value := UnwrapJsString(Res);
Result := True;
finally
Done.Free;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep the eval event alive after a timeout

When a script exceeds TimeoutMs, this method exits and frees Done, but the WebView callback registered above remains pending and later executes Done.SetEvent. A slow script that eventually completes after the 10-second tool timeout therefore calls through a freed TEvent, causing a use-after-free on the UI thread; the callback needs lifetime-safe shared state or cancellation rather than freeing its event while it can still fire.

Useful? React with 👍 / 👎.

Comment thread browser-desktop/uBrowserMain.pas Outdated
Comment on lines +668 to +671
CanClose := TDialogServiceSync.MessageDialog(
'PasClaw is still working in a tab. Close anyway?',
TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo],
TMsgDlgBtn.mbNo, 0) = mrYes;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Join or cancel active tasks before allowing shutdown

If the user selects Yes in this dialog, destruction proceeds while the untracked TTask.Run from SendMessage can still be inside FAgent.ChatHistory. FormDestroy then frees every tab, agent, bridge, and control that the task and its queued callbacks reference, creating races and use-after-free crashes specifically on the “Close anyway” path; shutdown must cancel/join those tasks or remain blocked until they finish.

Useful? React with 👍 / 👎.

…shutdown

Three review findings on the first cut, all in the FMX glue, all fixed
by moving the interesting part down into the FPC-tested layer where a
test can hold it.

One agent. TPasClawAgent is one-per-process (EPasClawInstance on a
second live instance), so creating one per tab meant "+ Tab" raised.
Now the form owns the one agent, registers the six tools and two hooks
once against a new TSwitchingBridge (PasClaw.Browser.Bridge), and runs
turns on a single worker thread that points the switching bridge at the
sending tab before ChatHistory and clears it after. A tab that sends
while another's turn is running is queued and its status says so. The
switching bridge is tested: no current tab fails with a named error and
reaches no tab; a tool built once follows whichever tab is current; after
Shutdown every call fails at once and SetCurrent is ignored. The closing
check was negative-tested by removing it, which failed on the assertion
that names it.

Eval lifetime. The per-call TEvent was freed on timeout while WebView2's
completion callback could still fire and set it. The event now lives in
a refcounted TEvalWaiter captured by the callback closure, so the last
holder frees it and a late callback is a harmless no-op.

Shutdown. "Close anyway" used to let FormDestroy free tabs, agent and
bridges under a live turn. Closing now winds down: the switching bridge
is shut so further page calls fail immediately, queued turns are dropped
and told so, the window stays open with a status line, and RunTurn's
completion closes it once the worker is idle. FormDestroy therefore
always joins an idle worker and frees agent then tabs in that order. A
second close while waiting offers to save sessions and halt, the one
exit that is safe from inside a provider call that will not return.

Also: a tab's session is appended only when its turn returns, so a
dropped or failed turn leaves no half-exchange in the saved history;
queued UI work is tagged with the worker thread so it is discarded with
it; the confirm dialog brings the asking tab forward first.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
@FMXExpress
FMXExpress merged commit 2d0a625 into main Oct 17, 2026
FMXExpress pushed a commit that referenced this pull request Oct 17, 2026
Covers what landed since v0.1.4: the PasClaw Browser (#604) and the
memory tiers / nightly maintenance / backup-restore / background cheap
tier work (#606). VersionFallback, the installer default and its
documented value, and the .dproj FileVersion / ProductVersion / Release
all move together; `make lint-version` agrees. Changelog entries added
for both PRs in docs/changelog.md and the README mirror.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant