Repository navigation
Run real Leaf agents on the website - #460
Conversation
leaf-agent
left a comment
There was a problem hiding this comment.
Two blockers on the production path, plus one narrower delivery gap. The Python and worker gates are green here: uv run pytest tests/test_website_server.py tests/test_interact_session.py (150 passed), npm run typecheck --prefix worker, npm test --prefix worker (48 passed). tests/test_render_controls.py::test_the_ring_reading_distinguishes_element_marks_from_focus failed in my run on mark-vs-focus ring colour, which this diff does not touch.
The container never trusts the interception CA, so no model call can leave it. interceptHttps = true is what routes HTTPS through outboundByHost, and it is the only thing that swaps the dummy credential for the real one — but @cloudflare/containers' own README says of that flag: "The container must trust the Cloudflare-provided CA certificate at /etc/cloudflare/certs/cloudflare-containers-ca.crt." Dockerfile.website adds nothing for it. On the deployed Worker the Codex task's TLS handshake to api.openai.com is against the proxy's certificate, so it fails verification and the hosted agent never gets a turn. A local round-trip wouldn't catch this, because interception doesn't run there. Details inline.
legacy: True raises the effective floor above the one pyproject.toml declares. The kwarg only exists in websockets 17.1; pyproject.toml states websockets>=15 and requires-python = ">=3.10", and uv.lock resolves 16.1.1 for Python 3.10. Verified against 16.1.1: connect("ws://127.0.0.1:1", ..., legacy=True) raises TypeError: create_connection() got an unexpected keyword argument 'legacy'. The unix:// path swallows it, so only the loopback ws:// App Server endpoint breaks — but that is the endpoint check_app_server_endpoint exists to admit. Details inline.
accept_codex_delivery acknowledges past events it deliberately did not deliver. prepare_codex_delivery narrows the batch from unacknowledged(...) to the intersection with activity.obligations, then acknowledge(page, max(expected)) moves the cursor to the batch's highest seq. activity.py excludes widget actions from obligations by design ("widget actions can instead be settled by the authored document"), and unacknowledged includes user actions, report, and error. So a reader who presses a widget and then comments has the action permanently acknowledged without ever reaching the task, while the detached adapter's _capture_pages delivers the same log position in full. If the filter is only meant to drop events the deterministic rate-limit and startup-failure replies already settled, keying on that settlement rather than on obligations would leave the two hosts reading one cursor the same way.
leaf-agent
left a comment
There was a problem hiding this comment.
The three findings from my last review are closed. I confirmed the first against the pinned artifact rather than the docs: @openai/[email protected]'s Linux binary carries CODEX_CA_CERTIFICATE in its http-client/src/custom_ca.rs path and loads it into the rustls root store, so the env var reaches Codex's own HTTP client without touching the system store. legacy is gone and the loopback ws:// App Server case passes on the installed websockets. The delivery filter now keeps unsettled widget actions.
Two new points on the hosted delivery path, and one design question.
A retried start Codex task step tells the reader the agent failed on a turn that actually started. /_leaf/agent/start checks agent_event_pending but, unlike /_leaf/agent/turn, not agent_event_thread — so it re-enters attach for an event this container already delivered. By then accept_codex_delivery has advanced the page cursor, so prepare_codex_delivery computes an empty batch and raises the page has no Leaf input to deliver. The handler's exception boundary turns that into a 500, which askContainer classifies as retryable; three retries later the workflow's catch appends GENERATION_FAILURE_REPLY. The reader is told "I couldn't generate a reply just now" while the hosted task is revising the page. Only one lost start response is needed to reach it — container cold start, App Server launch, and thread/start all sit under the same two-minute step timeout. Suggestion inline.
The embedded follower drops the throttle the detached observer has. WebsiteCodexHost._follow_turn calls _set_stream_activity on every update AppServerEvents.read returns, and item/agentMessage/delta returns one per token delta. AppServerObserver._read guards exactly these methods with STREAM_THROTTLED_METHODS and STREAM_UPDATE_INTERVAL; without it each delta takes _locked_codex_pages and rewrites status.json, contending with the same page transaction lock the reader's own POST /api/event needs. Detail inline.
Design question for you, not a finding. The per-IP brake still counts one unit per reader message, but a unit is no longer a single 400-token call in the Worker — it is a full agent turn that can edit, validate, and re-render the page. On top of that, outboundByHost injects the real OPENAI_API_KEY into any container-originated POST /v1/responses, and the task runs danger-full-access with approvalPolicy: never over page content the developer instructions themselves call untrusted, so a curl --cacert /etc/cloudflare/certs/cloudflare-containers-ca.crt loop from inside the container reaches that route too. The credential stays out of the container either way, so the exposure is spend, not disclosure — but nothing downstream of the start caps it. Worth either a stated ceiling or an explicit decision that the container's own lifetime is the ceiling.
Unrelated to the code: #459 is open over the same codex.py delivery surface and its description states that it makes the detached adapter the sole Codex carrier, which this PR's embedded host contradicts. Whichever lands second will need that claim reconciled.
Gates I ran on this head: uv run pytest tests/test_interact_session.py tests/test_website_server.py (151 passed), npm run typecheck --prefix worker, npm test --prefix worker (48 passed).
# Conflicts: # skills/leaf/references/host-codex.md # skills/leaf/references/internals/session-lifetime.md
leaf-agent
left a comment
There was a problem hiding this comment.
The merge resolution in 8a7224c reconciles this host with main's frozen-delivery model cleanly, and both findings from my last review are closed: /start now reads agent_event_thread before re-entering attach, and project_app_server_activity gives the embedded follower the same throttle the detached observer has. The outbound model:${ctx.containerId} bucket is a real answer to the spend question I raised, so I'm not restating it.
Two findings, both on what the reader's banner says while the hosted agent works. They share a cause: the embedded host writes agent state in App Server's vocabulary, and the activity projection reads Leaf's.
Every accepted hosted delivery reads as picked up and dropped. accept_codex_delivery calls page.open_turn(session_id), discards the claim turn it returns, and records the pickup with App Server's turn["id"] instead. canonical_activity builds handling from item.get("delivery_turn") == present.get("claim_turn"), and claim_turn is the secrets.token_hex(8) open_turn mints — so the two are never equal, every hosted interaction falls into left_in_old_turn, and the fold stamps dropped = True. session.py's direct-delivery path passes reading.transaction.open_turn(...)'s return, and hooks.py passes claim.get("turn"); this is the one carrier that passes something else. Reproduced on this head: one comment, prepare_codex_delivery, accept_codex_delivery("hosted-thread", "app-server-turn-1") gives kind=picked_up, dropped=True, counts.handling=0 — the banner tells the reader their message was left behind in a turn that is at that moment handling it. Suggestion inline; with it the same fixture gives kind=handling, dropped=False, and tests/test_website_server.py tests/test_interact_session.py stay green at 149 passed, so nothing pins the current reading.
The embedded host holds no wait lease, so the page never reads as listening. present["listening"] is wait_is_live(page_dir, active), a flock on the waiter lease, and nothing in worker/server.py takes one — the container serves pages from WebsitePageHandler rather than through leaf server start or leaf wait. Two consequences on the hosted path. stream_current requires listening, so the per-item detail _follow_turn writes is dropped before it reaches the banner: on the same fixture, status.json carries stream.detail = "Running leaf version check ." while the projection returns detail="". And after the agent finishes and does what CODEX_INSTRUCTIONS tells it — leaf status <page> waiting, never idle — the fold has no branch left and returns kind=away, so the instruction written to keep the session live reads to the reader as an agent that walked away. Detail inline.
Gates on this head: uv run pytest tests/test_website_server.py tests/test_interact_session.py (149 passed), npm run typecheck --prefix worker, npm test --prefix worker (50 passed).
leaf-agent
left a comment
There was a problem hiding this comment.
Both findings from my last review are closed — the pickup names Leaf's claim turn, and the container now holds the task's wait lease, so the same fixture that read picked_up/dropped now reads handling, and stream_current reaches the banner. One finding remains on that seam, in the other direction: the claim turn the pickup names is re-minted on every delivery.
A reader who comments while the agent is working sees the first comment marked "Picked up · turn ended" while the same Codex turn is steering on it. prepare_codex_delivery calls page.close_turn(session_id) unconditionally, so accept_codex_delivery's page.open_turn(session_id) always finds turn_closed stamped and mints a fresh secrets.token_hex(8) turn rather than returning the live one. The earlier pickup's delivery_turn then no longer equals present["claim_turn"], so canonical_activity moves it out of handling into left_in_old_turn and stamps dropped = True, and acknowledgmentFace in living-margin.js renders that receipt as Picked up · turn ended. The ordinary route reaches it: every reader event runs its own runAgentWorkflow, so a comment posted during an active turn goes /turn → ready → /start → attach → prepare + accept, and session-lifetime.md states that App Server treats that second turn/start as steering for the turn already running — the first comment is being handled at the moment its receipt says its turn ended.
Reproduced on this head by delivering two comments in sequence: counts reads {handling: 1, picked_up: 1} and the first interaction carries dropped: True. With the close_turn line dropped it reads {handling: 2, picked_up: 0} and neither interaction is flagged, while uv run pytest tests/test_website_server.py tests/test_interact_session.py stays at 150 passed either way — so nothing currently pins the reading. Suggestion inline. If that closure is there to cover the window between prepare and a turn/start that fails, the same result follows from having the acceptance restore the turn the delivery closed instead of minting a new one; either shape wants a case, since the projection is the only thing that says so.
Gates on this head: uv run pytest tests/test_website_server.py tests/test_interact_session.py (150 passed).
leaf-agent
left a comment
There was a problem hiding this comment.
The turn boundary reads correctly on the two statuses the new test covers, and the removal of the unconditional close_turn is the right place to have moved it: two comments delivered in sequence into an active task now read {handling: 2, picked_up: 0} with the claim turn unchanged, and prepare_codex_delivery no longer decides a boundary only the carrier can see. One finding on the third branch.
A hosted turn that ends in an error leaves that page's agent permanently unreachable, and every later reader message answers "I couldn't generate a reply just now". ThreadStatus has four variants at the pinned @openai/[email protected] — notLoaded, idle, systemError, active (ThreadStatus.ts) — so systemError is what the new elif raises on. It is reachable on the ordinary path: a turn that ends in EventMsg::Error (a model call that exhausts its retries against the outbound handler, a 429 from the per-container model limiter, a dropped stream) runs thread_watch_manager.note_system_error(...) in bespoke_event_handling.rs, which sets has_system_error on the thread's runtime facts, and loaded_thread_status then reports SystemError for a thread that is loaded and not running.
The state is sticky, and the only thing that clears it is the action this branch refuses: note_turn_started is the sole writer of runtime.has_system_error = false in thread_status.rs — Codex's own system_error_sets_idle_flag_until_next_turn test pins exactly that. So the next reader message resumes, handle_pending_thread_resume_request reports the stored status, attach raises, and because resumed is already True the raise propagates instead of falling back to _start_thread. /start answers 500, askContainer classifies it retryable, three retries hit the same stored status, and the workflow's catch appends GENERATION_FAILURE_REPLY. Nothing in the loop ever starts the turn that would clear the flag, so the page is answered by the fallback for the rest of the container's life. Before this commit the same task recovered on its own, because the delivery started a turn unconditionally.
systemError and idle want the same handling: neither is running a turn, so the Leaf claim turn should close and the next turn/start opens a new one — and on systemError that start is also the recovery. Suggestion inline collapses the branch to that. notLoaded rides along safely: after a cold resume it isn't reported (resume_thread_from_history calls upsert_thread before reading the status), and if it ever were, turn/start would fail on its own terms rather than wedging the page. CLAUDE.md's Stage section is the shape argument as well as the behavioural one — "Add a guard only for a reachable condition with a useful response" — and the response here is the one state the page cannot leave.
Worth carrying into the two places that describe the rule: session-lifetime.md now says an idle task closes the preceding turn, which under the suggestion reads as any task that is not active; and the new parametrization is the natural place for a third case, since ("systemError", True) is what would have failed here.
Gates on this head: uv run pytest tests/test_interact_session.py tests/test_website_server.py (152 passed), uv run pytest tests/test_interact_server.py (96 passed).
… times out (#467) `ci` on `main` went red at [c811958](c811958) when `Measure the bundled release in Chrome` timed out waiting for `body[data-lf-presented]` ([run 34296622586](https://github.com/max-sixty/leaf/actions/runs/34296622586)). Rerunning that same job at that same commit passed, and printed the ordinary profile — presentation at 1212 ms on `/`, 1033 ms on `/examples/design-decision/`, 2151 ms on the frozen gallery revision. So the merge did not break the served site: one page stalled once, 25× past its usual cost, and then the evidence was gone. It was gone because the gate keeps none. The failure the run recorded is Playwright's own `Locator.wait_for: Timeout 30000ms exceeded`, which names neither the page that stalled nor how far its startup got, and `verify-site-local.sh` prints the Worker's log only when the server never answers `curl` at all — a browser-side failure discards it. Reproducing was the only route left, and 36 loads of the same three pages against the same built release did not reproduce it. This makes the next occurrence answer the question this one could not. `PROFILE_SCRIPT` already records each startup stamp as it lands, so the stamps standing at the timeout separate the two ways [`startPage`](https://github.com/max-sixty/leaf/blob/c8119589ac5652661d3e8efa06a8399e03c3e779/skills/leaf/assets/leaf.js#L155-L192) can stall: a widget upgrade that never settled leaves no stamp, while a first state read that never answered leaves `upgraded` standing alone. The wait now raises that reading with the page's URL and any browser errors already collected, and the shell prints the Worker's log beside it, since a stalled request is a fact about both halves. The distinction is worth having because the two have different fixes. A first state read that never answers is a reachable end state today: `readState` treats a *failed* fetch as a complete offline answer and presents on it, but the `fetch` carries no deadline, so a response that neither arrives nor errors leaves the page unpresented with no retry behind it — for a reader on a stalled connection as much as for this gate. Whether that read should have a deadline, and what it should be, is a product decision this change deliberately does not make. ## Verification `uv run pytest tests` (934 passed, 6 skipped); `uv run pre-commit run --files` over the four changed files; and `scripts/verify-site.py` driven against a local `wrangler dev` over the built release, where all three pages presented and the run proceeded to the container-activation checks. The new unit test covers the message this change exists to produce; the timeout branch that builds it was exercised directly against a stub page. <details><summary>Why the merge is not the cause</summary> [#460](#460) passed the same step on its own head in 24 s, and `main` at [be6be02](be6be02) passed it too; the squash merge of the two is the first commit where this step has ever failed, which is what made a regression the obvious first reading. Against it: the same commit's rerun is green, the presentation costs and byte counts in that rerun match the pre-merge run to within noise, and nothing in `#460`'s runtime surface reaches presentation — its only change under `skills/leaf/assets/` is one banner sentence. `wrangler dev` also awaits container-image preparation before it starts the local server, so the heavier website image `#460` introduces cannot be competing with the browser once `curl` has answered. </details> --------- Co-authored-by: leaf-agent <[email protected]>
## Summary - register the website container's OpenAI outbound handler through Cloudflare's inherited setter, so real Codex requests receive the deployed credential - settle each accepted Leaf delivery against its exact page turn, preserving real replies while surfacing failed or incomplete agent turns - let edge-missing revision, version, and media files fall through only to an identified active reader's container, so a private revision can become the live document without anonymous allocation - require the production secret explicitly and make the deployed-site gate prove exactly one real agent edit, published revision, reply, and rendered result ## Production diagnosis The agent routes introduced in #460 accepted comments and started turns, but the model requests returned 401 in Cloudflare. The replacement `leaf.page site` key succeeds against the same Responses API directly. The production bundle instead preserved `static outboundByHost`, which shadowed the Containers SDK's inherited registration setter and left the handler registry empty; assigning the handler after the class definition registers it with the SDK. ## Validation - `uv run pytest tests` — 944 passed - `npm test --prefix worker` — 57 passed - `npm run typecheck --prefix worker` - `pre-commit run --all-files` > _This was written by Codex on behalf of max-sixty_
This turns each website reader’s private copy into a real mutable Leaf session rather than a website-specific reply bot. The existing Worker still owns routing, workflow retries, abuse limits, and per-reader isolation; its container now starts or resumes a pinned Codex App Server task rooted at the canonical page directory. Reader events enter that task through Leaf’s ordinary immutable
leaf-deliverypayload, and the shipped Leaf plugin owns page edits, validation, revisions, replies, and waiting state.The container is the outer tool sandbox because nested bubblewrap namespaces are unavailable there. Public egress is denied except for
POST /v1/responses, where a trusted Worker outbound handler replaces a dummy container credential with the real secret. Codex reads Cloudflare’s runtime interception CA through its supported custom-CA setting, so TLS terminates at that handler without putting the real credential in the container. One Cloudflare-native limiter allows 20 task starts per source IP per minute and, under a separate key, 20 model calls per reader container per minute.The embedded host now uses the same queue-only delivery primitive as the detached Codex adapter: it freezes one permanent payload, keeps transport state in a separate mutable queue record, records pickup against Leaf’s claim turn before acknowledging input, and resumes the same Codex task for later events. App Server's resumed task status supplies the turn boundary: active tasks steer new input into the standing Leaf turn, while any non-active task closes it before the next delivery opens another. This also lets a task in
systemErrorrecover through the nextturn/start, as Codex intends. The host holds that task’s waiter lease for the container host’s lifetime, while streamed activity uses App Server’s task and turn IDs, so the browser reports handling, live work, and listening through Leaf’s canonical projection. Lost/startresponses return the recorded task instead of starting a duplicate. Definitively failed startup retries settle the triggering event with a deterministic reply and retire only the unaccepted queue record; the immutable payload remains readable by a turn whose acceptance raced the failed response. Both App Server carriers share one throttled activity projection, and delivery retains earlier unsettled widget actions while excluding reader input already settled by a fallback.The page directory and Codex session still live on the reader container’s ephemeral disk. This is enough for a real Leaf editing loop during that container’s lifetime; durable website sessions still require external page-directory and task storage. The production image is roughly 1 GB, and deployed cold-start latency and resource use remain to be measured.
Validation:
uv run pytest tests(934 passed);npm run typecheck --prefix worker;npm test --prefix worker(50 passed);npm run build --prefix worker(37 pages);pre-commit run --all-files; production dependency audit; production Docker image build; a Python 3.10 / websockets 16.1.1 loopback App Server check; and a browser round-trip in which a comment produced a validated revision and anchored reply.