Repository navigation
Add PasClaw Browser: WebView2 tabs with an embedded agent per tab - #604
Conversation
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
There was a problem hiding this comment.
💡 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".
| 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); |
There was a problem hiding this comment.
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 👍 / 👎.
| 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; |
There was a problem hiding this comment.
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 👍 / 👎.
| CanClose := TDialogServiceSync.MessageDialog( | ||
| 'PasClaw is still working in a tab. Close anyway?', | ||
| TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], | ||
| TMsgDlgBtn.mbNo, 0) = mrYes; |
There was a problem hiding this comment.
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
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
What this is
A desktop browser,
browser-desktop/PasclawBrowser.dproj, where every tab is aTWebBrowseron 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
TPasClawAgentcomponent, against your ownPASCLAW_HOME. No gateway to start, no port to open. Memory, distilled facts andAGENTS.mdare 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.
TPasClawAgentis one-per-process (its constructor raisesEPasClawInstanceon a second live instance), so the form owns one agent with the six tools and two hooks registered once against aTSwitchingBridge. 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
browser_pageoffsetbrowser_findbrowser_navigateback/forward/reload; waits for the loadbrowser_clickbrowser_fillinput/changeso React-style pages noticebrowser_evalMutating 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-safeSetCurrent/Shutdown, fails with a named error when no tab is current or the app is closing), andUnwrapJsString, which strips the one JSON quoting layer WebView2 adds to completion values.\uXXXXgoes throughUnicodeString+UTF8Encodeso it is right on both compilers, with surrogate pairs handled.PasClaw.Browser.Tools— the sixTPasClawTooldescendants above. Elements are addressed bydata-pc-handlestamps; 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) andTConfirmMutationHook.PasClaw.Browser.Session—TBrowserSessionwith JSON save/load.uBrowserMain+.fmx,.dpr,.dproj— the FMX form:TTurnWorker(the one thread turns run on),TFmxBridgewith a refcountedTEvalWaiterso a WebView2 callback that fires after the timeout never touches a freed event,TBrowserTabwiring WebView2, address bar, transcript, input and its own bridge;WindowsEngineis set beforeParent.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.
FormDestroytherefore 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 andoffset, 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,UnwrapJsStringincludingéand a surrogate pair, and the switching bridge (no current tab fails and reaches no tab; a tool built once follows the current tab; afterShutdownevery call fails at once andSetCurrentis ignored).make lint-browser-shape—scripts/check-browser-shape.py, fails the build ifWindowsEngineis assigned afterParentor never assigned on aTWebBrowser. This is the bugdesktop/once shipped.testaggregate. Fullmake teston 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:
Known limits
EvaluateJavaScriptcall inTFmxBridge.Evalis the line most likely to need an overload spelled differently for your Delphi version. Delphi 11+ is required for the result-returning overload.docs/browser-plan.mdis the design note, updated to point atbrowser-desktop/and to record the review correction.🤖 Generated with Claude Code
https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6