From 6a76aec94170e34b2a15eafb80c016f4bb34c5cc Mon Sep 17 00:00:00 2001 From: meh Date: Thu, 5 Nov 2026 04:23:55 +0700 Subject: [PATCH 1/4] Update project source --- apps/gui/src/agent_proxy.rs | 77 ++-- docs/TODO.md | 743 ------------------------------------ scripts/blitz-control.sh | 6 +- 3 files changed, 49 insertions(+), 777 deletions(-) delete mode 100644 docs/TODO.md diff --git a/apps/gui/src/agent_proxy.rs b/apps/gui/src/agent_proxy.rs index 04eee643..20c7d52a 100644 --- a/apps/gui/src/agent_proxy.rs +++ b/apps/gui/src/agent_proxy.rs @@ -13,11 +13,11 @@ use agency_proxy_protocol::{ use agent_abstraction::{Decision, Event, Outcome}; use serde::Serialize; use std::{ - fs::OpenOptions, + io::Read, path::{Path, PathBuf}, process::{Command, Stdio}, sync::{ - Arc, + Arc, Mutex as StdMutex, atomic::{AtomicU8, AtomicU64, Ordering}, }, time::Duration, @@ -25,6 +25,7 @@ use std::{ use tokio::sync::Mutex; static RUN_SEQUENCE: AtomicU64 = AtomicU64::new(1); +const MAX_PROXY_OUTPUT_BYTES: usize = 16 * 1024; #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(u8)] @@ -600,32 +601,17 @@ impl AgencyProxy { )?; } } - let output_path = self.socket_path.with_file_name("agency-proxy.log"); - let captured = OpenOptions::new() - .create(true) - .write(true) - .truncate(true) - .open(&output_path) - .ok(); let mut command = Command::new(&binary); command .arg("--socket") .arg(&self.socket_path) - .stdin(Stdio::null()); + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); if let Some(path) = std::env::var_os("PATH") { command.env("PATH", path); } - if let Some(stderr) = captured { - command.stdout( - stderr - .try_clone() - .map_or_else(|_| Stdio::null(), Stdio::from), - ); - command.stderr(Stdio::from(stderr)); - } else { - command.stdout(Stdio::null()).stderr(Stdio::null()); - } - let child = match command.spawn() { + let mut child = match command.spawn() { Ok(child) => child, Err(error) => { return Err( @@ -633,6 +619,13 @@ impl AgencyProxy { ); } }; + let captured_output = Arc::new(StdMutex::new(Vec::new())); + if let Some(stdout) = child.stdout.take() { + drain_proxy_output(stdout, captured_output.clone()); + } + if let Some(stderr) = child.stderr.take() { + drain_proxy_output(stderr, captured_output.clone()); + } // Watch the child so its death is *observed* rather than inferred. // // The handle used to be dropped right here. Nothing could then wait on @@ -657,7 +650,7 @@ impl AgencyProxy { Err(_) => nagoya::sleep(Duration::from_millis(50)).await, } } - Err(self.record_failure(proxy_startup_failure(&output_path, &self.socket_path))) + Err(self.record_failure(proxy_startup_failure(&captured_output, &self.socket_path))) } fn connection_state(&self) -> ConnectionState { @@ -869,14 +862,39 @@ fn watch_proxy_child( .ok() } -fn proxy_startup_failure(output_path: &Path, socket_path: &Path) -> String { +fn drain_proxy_output(mut stream: R, output: Arc>>) +where + R: Read + Send + 'static, +{ + let _ = std::thread::Builder::new() + .name("agency-proxy-output".into()) + .spawn(move || { + let mut chunk = [0_u8; 1024]; + loop { + let Ok(read) = stream.read(&mut chunk) else { + break; + }; + if read == 0 { + break; + } + let Ok(mut output) = output.lock() else { + break; + }; + let remaining = MAX_PROXY_OUTPUT_BYTES.saturating_sub(output.len()); + output.extend_from_slice(&chunk[..read.min(remaining)]); + } + }); +} + +fn proxy_startup_failure(output: &StdMutex>, socket_path: &Path) -> String { let base = format!( "AgencyProxy did not become ready at {}", socket_path.display() ); - let Ok(output) = std::fs::read_to_string(output_path) else { + let Ok(output) = output.lock() else { return base; }; + let output = String::from_utf8_lossy(&output); let output = output.trim(); if output.is_empty() { base @@ -1384,7 +1402,7 @@ mod tests { use std::collections::BTreeMap; use std::path::Path; use std::process::{Command, Stdio}; - use std::sync::Arc; + use std::sync::{Arc, Mutex as StdMutex}; use std::sync::atomic::{AtomicU8, Ordering}; #[test] @@ -1561,14 +1579,9 @@ mod tests { #[test] fn startup_failure_includes_the_sidecars_captured_error() { - let dir = - std::env::temp_dir().join(format!("agency-proxy-startup-error-{}", std::process::id())); - std::fs::create_dir_all(&dir).expect("create temp directory"); - let output = dir.join("agency-proxy.log"); - std::fs::write(&output, "could not bind socket: operation not permitted\n") - .expect("write captured output"); + let output = StdMutex::new(b"could not bind socket: operation not permitted\n".to_vec()); - let message = proxy_startup_failure(&output, &dir.join("runtime.sock")); + let message = proxy_startup_failure(&output, Path::new("runtime.sock")); assert!(message.contains("did not become ready")); assert!(message.contains("operation not permitted")); } diff --git a/docs/TODO.md b/docs/TODO.md deleted file mode 100644 index ceaddd97..00000000 --- a/docs/TODO.md +++ /dev/null @@ -1,743 +0,0 @@ -# TODO: what to work on, and what is still research - -> **New here, or resuming after a compaction?** There may be an untracked -> `docs/HANDOVER.md` beside this file, written at the end of a working session -> and deliberately not committed: it holds machine-local paths and in-flight -> state. Read it if it is there. This file is the item list; that one is the -> operating manual. - -Written 2026-08-11. A high-level index. Every line points at the document that carries the -evidence, the line numbers and the caveats. **Read the linked doc before acting on an -item**, because several of these carry ordering constraints that are not obvious from a -one-line summary. - -Everything produced on 2026-08-11 is source reading, not measurement. Each of those docs -says so at the top. `performance.md` remains the only measured document, and its -2026-08-11 addendum records what a source review added and where it qualified the earlier -numbers. - -## First: the inspector's 80% of a core does not reproduce - -This section used to say the inspector cost 80% of a core, on the strength of -one pair of readings: 0.00s of CPU over 10s wall without `blitz-inspector`, -8.04s with it. **Re-measured on 2026-08-12 after 0.6.0, it does not reproduce, -and the build is not the variable.** - -| what was run | idle CPU over 10s wall | -| --- | --- | -| 0.6.0, `--features blitz-runtime` | 0.13s, 1.3% of a core | -| 0.6.0, `--features blitz-inspector` | 0.09s, 0.9% | -| the same, under the bundle's pinned `LSEnvironment` | 0.03s, 0.3% | -| **the 0.5.51 binary the 8.04s came from** | **0.14s, 1.4%** | - -Same machine, same store, same project open, both binaries executed directly -rather than through Finder. The 0.5.51 build in -`target/release/bundle/macos/AgencyZero.app` is the one the figure was taken -from, and today it reads 1.4%. - -Nothing walks it back up. After six control clients attach and hang up, 1.0%. -After six page downs, after scrolling the transcript, after paging through -Settings: 0.9% to 1.4%. Over ten minutes of uptime with the app driven between -every reading, it stays between 0.7% and 1.6% while RSS drifts 665MB to 679MB. -The harness is [`scripts/perf/idle-cpu.sh`](../scripts/perf/idle-cpu.sh), in the -four modes above: - -```sh -scripts/perf/idle-cpu.sh once target/release/az-gui -scripts/perf/idle-cpu.sh clients target/release/az-gui 6 -scripts/perf/idle-cpu.sh after-use target/release/az-gui -scripts/perf/idle-cpu.sh soak target/release/az-gui 10 -``` - -It takes two `ps -o time=` reads a known interval apart, runs the binary under -the same environment the bundle pins, refuses to start when the store is -already locked, and refuses to report a number for a process that failed to -take the store. Two readings were once taken from an app that had never -started. - -So one of these is true, and which one decides whether there is any work here: - -1. The control-server fix - ([izumo 6173d83](https://github.com/pathscale/izumo)) - closed it after all. A hung-up peer returned the same transport error - forever and every client that ever disconnected left a task spinning. The - note that "with the fix in, the 8.04s stands" was written from a binary - built off a warm target dir whose dependency graph resolved ps-blitz at - **two revisions** — the graph CI could not compile at all (see agencyzero - PR 141). What that binary contained is not knowable now. -2. The cost belongs to a state the app only reaches with a human at it, which - nothing above walks into. - -**Do not turn the feature off**, and do not spend a session on item 1's three -old leads until the number is seen again. The next move is the owner's: when -`az-gui` is next above a few percent, leave it running and say so, and take the -reading with `idle-cpu.sh`'s method rather than `ps %cpu`, which is a lifetime -average and was the source of the original alarm. - -## Every item, by number - -One table so a number can be looked up without knowing which section owns it. -The detail stays in the sections below; this is an index, not a second copy. - -| # | Item | State | -|---|---|---| -| 1 | `log-phase-times` off the base dependency | done 2026-08-11 | -| 2 | Bound the streaming tail block | done 2026-08-11 | -| 3 | `vmmap`/`heap` on a live instance | half done | -| 4 | Make Stylo snapshots updatable | open | -| 5 | Clamp animation-driven redraw to a lower cadence | open | -| 6 | mimalloc as the global allocator | open, re-scoped to memory | -| 7 | Fix the Taffy cache: A/B 0.12.2 against 0.13.0 | half done | -| 8 | Honest snapshot flags, then narrow the restyle hints | gated on 4, 7 | -| 9 | Narrow `ALL_DAMAGE` on the mutation paths | gated on 7 | -| 10 | Batch pending invalidations | open | -| 11 | Cache the bezier paths | partly, re-scoped | -| 12 | Damage regions, stages 0 to 3 | gated on 1, 20 | -| 13 | Count the whole-document taffy cache clears | **closed 2026-08-12, premise false** | -| 14 | `BLITZ_PRESENT_MODE=mailbox` | **closed 2026-08-12, measured worse** | -| 15 | Pass Stylo a thread pool | open | -| 16 | Enable `blitz-dom/parallel-construct` | open, amended by 19 | -| 17 | Heavy read-only Tauri commands off the window thread | open, **now measured** | -| 18 | Renderer on its own thread | gated on 17 | -| 19 | Genet's shaping pre-pass, all four parts | amends 16 | -| 20 | A paint-list IR between layout and the renderer | prerequisite of 12, 18 | -| 21 | Research: a script-engine seam | open | -| 22 | W1: assert the engine's resolved features | open, highest of 22 to 26 | -| 23 | W2: assert instrumentation is absent from release | **now false by choice, see below** | -| 24 | W3: assert one copy of each pivotal crate | open | -| 25 | W4: assert no local `[patch]` reaches a shipped build | open, near-missed 2026-08-12 | -| 26 | W5: assert a target-aware native-dependency inventory | open | -| 27 | Stable, unique component IDs as the QA control contract | open, after typography migration | - -### Item 27: stable component IDs, enforced statically and live - -Accessible names describe controls to people; they are not unique identities -and can change with translation or state. Every QA-addressable public component -root must instead receive an explicit, stable HTML `id`. Compound parts derive -their IDs from that root, and repeated rows derive them from durable record IDs, -never array positions or visible titles. - -This is complete only when all of the following land together: - -1. PathScale/UI component props require and forward the root ID. -2. AgencyZero supplies stable IDs at every interactive call site. -3. Static lint rejects missing IDs, duplicate literal IDs, and index-derived - IDs. -4. Blitz exposes the DOM ID separately from its ephemeral numeric node handle. -5. ps-qa accepts exact `#id` selectors and migrates action manifests away from - accessible-name lookup. -6. The live inventory fails duplicate resolved IDs, covering dynamic values a - static pass cannot prove unique. - -Names remain accessibility assertions and discovery output. They are not the -primary automation selector once this migration is complete. - -Item 13 was measured on 2026-08-12 and **closed**: there is no whole-document -clear left to count. `resolve.rs` clears one node, not the tree. On a 186-node -transcript, an idle resolve computes nothing and a resolve carrying one -streamed token computes 3 nodes, clears 3 caches and hits cache 61 times in 64, -at 720us against 315us idle. Items 7 to 12 are therefore not gated behind a -catastrophic invalidation, and the worry that "0.27ms per keystroke describes -only resolves that do not reconstruct" does not hold. Reproduce with -`cargo test -p blitz-tests --test streaming_token_cost --features counters -- ---nocapture`; the magnitude still wants re-measuring against the real document, -which is 4,000 nodes rather than 186. - -Item 14 was measured on 2026-08-12 and **closed without shipping**: three -unpaced runs each, first discarded, `mailbox` against `fifo` gave 107.3 and -117.5 fps against 116.7 and 120.1, with 5 and 4 missed refreshes against 2 and -1. FIFO is equal or better on every column, and the predicted drop in -`missed_refreshes` went the other way. Items 15, 16 and 17 were said to be -gated on it; they are not gated on anything now, but their measurements are -still taken under FIFO, which is what ships. - -Item 23 is deliberately violated as of 2026-08-12: release bundles now build -`--features blitz-inspector`, unstripped, because two defects this week were -invisible until a crash report and a `sample` could name a function of ours. -The cost is real and accepted: `log-phase-times` rides that feature, so a -timing taken from a release build now contains its own instrument. Constraint 2 -below therefore stands rather than being retired. - -Item 17 was measured on 2026-08-14, against a copy of the real Experimental -profile (247 projects, five open tabs), with the tab-load instrumentation now in -`workspace.tsx`. The reads are synchronous `#[tauri::command]` functions, so they -run on the window thread: dispatch overlaps freely, up to 37 in flight at once, -but execution is one at a time in issue order. The same `list_items` call took -**27ms issued first and 347ms issued third**, and the last project's fetch -finished at **547ms** against the first one's **35ms**. Sharing that queue were -`list_quota` at **1186ms**, `check_for_update` at 940ms and `claude_usage` at -722ms, all network-bound, all ahead of store reads a visible tab was waiting on. - -The cheap half of the fix shipped with the measurement: boot now issues the -active tab's reads first, which took that tab's fetch from 473ms to **56ms**. It -does not make the work concurrent, it just stops the tab someone is looking at -being last in line. The expensive half is item 17 proper, and the numbers above -are the case for it. - -Two more from the same run, neither yet addressed: - -- `reconcile` of 2,422 messages costs **237ms** on the main thread, the largest - single frontend cost in a cold load. -- Boot waits for every open project before reporting ready, so one heavy tab - delays four light ones. Loading the active tab, going ready, then filling the - rest in the background is the obvious shape; it needs care around - `drainEventBuffer`, since an event for a project that has not hydrated yet - must not be dropped. - -### Item 17: plain `async` is the wrong shape, measured 2026-08-14 - -Converting the eleven synchronous per-project reads to `async fn` was tried and -reverted. It does move them off the window thread, and it made things worse: -`list_items` went from 10.8ms average to 52.5ms, with the min/max spread still -at 3.3x. - -The reason is in the same table. Tauri runs `async` commands on its async -runtime, and that is where the slow network commands already live: -`list_quota` averages 1118ms and has been seen at 5048ms, `check_for_update` -906ms, `claude_usage` 657ms, `discover_chat_imports` 396ms. Cheap store reads -moved there stop queueing behind each other and start queueing behind -multi-second network calls instead. - -So the fix is not `async`, it is a pool that is not shared with the network: -`spawn_blocking` with the `Arc` cloned out of `State`, or an explicit -reader pool. Whichever is chosen, the check is the spread rather than the -average, because the average hides which end of the queue a call landed in. - -Two other things the table surfaced and neither is the renderer: - -- `ProjectPanel` issues six further per-project commands beyond the seven in - `fetchProject`: `get_project_verbosity`, `get_io_persist`, `get_checkpoints`, - `get_project_notes`, `get_project_concise`, `list_approval_rules`, each around - 17ms. Four panes make that 24 extra round trips. One `get_project_panel` - would make it four. -- `list_quota` calls `proxy.account_usage()`, which is the endpoint recorded - elsewhere as dead. It costs seconds per call and runs twice at startup. - -## Three constraints that govern the order - -1. **The Taffy layout cache gates almost every speed number.** Style is 167 microseconds - against 18 ms of layout per keystroke. Anything promising milliseconds waits on - [layout-caching-prior-art.md](layout-caching-prior-art.md). -2. ~~**Instrumentation currently ships in release builds**~~ **Fixed 2026-08-11**, item 1. - `log-phase-times` is on `blitz-inspector` (`apps/gui/Cargo.toml:53`) and the base - `blitz-dom` line carries only `system-fonts, parallel-construct`. Numbers taken before - that date still sit inside the old baseline; numbers taken after do not. -3. **Engine changes reach neither app until they are published.** Corrected 2026-08-25: - this repository no longer builds ps-blitz from a pinned git rev. `apps/gui/Cargo.toml` - takes the **published** `ps-blitz-dom ^0.3.0-beta.6`, exactly as chuzz does. So an - engine fix in `~/code/ps-blitz` reaches *neither* app until it is released; the local - checkout is at `0.3.0-beta.7`. Budget a release for every ENGINE item. - -## Resume here - -Paused 2026-08-11 for one short unrelated project, and **still paused as of 2026-08-25**: -the intervening two weeks went to QA/button-audit and side-panel work, not to this. Nothing -in A, B or C below was started. This is where the performance workstream picks up, in this -order, and each line already has its measurement — see "Done, 2026-08-11" below for what -produced them. - -**B is the gate.** Every remaining figure was measured against a baseline taken while the -app burned 76% of a core, on a bench that paced itself at 60Hz. Until B is redone, any A/B -you run compares against fiction. - -**A. Why a scrollport clip costs ~110us.** The largest measured item left. Clip and -opacity layers are 44% of the frame, and within that the count is not the cost: a -background clip is about 0.8us, a scrollport clip about 110us, and the ~30 remaining ones -are worth **2.5ms of a 7.4ms frame**. Two candidates, and they need separating before -anything is designed: - - 1. Whether vello allocates an intermediate render target per clip rather than using a - scissor rect for an axis-aligned rectangle. A vello question. - 2. Whether nested scrollports re-clip regions an ancestor already clipped. Ours, and - cheap to answer now that `layers_by_site` is on the `[blitz-frame]` line. - -**B. Re-baseline everything unpaced.** Every frame-rate figure recorded before step 10 of -[allocations-plan.md](allocations-plan.md) came through a harness pacing itself at 60Hz. -The millisecond phase timings survive; the frame rates and `missedRefreshes` counts do -not. Until this is redone the workstream's own baseline is wrong. `BENCH_PACE=0`, three -runs, discard the first. - -**C. The two deferred items, both re-scoped by measurement.** Path caching (item 11) is -now judged against an 8.33ms frame rather than a 40ms one, which is the whole reason it -was deferred rather than dropped. mimalloc (item 6) is a **memory** experiment aimed at -the 78MB of empty-but-resident malloc regions, not a speed one. - -**Explicitly not next:** the Boa concatenation. Arithmetic puts it at ~30ms across a -50,000-character reply against the 2.3s the parse cost, and it cannot be measured outside -the app. Leave it until something measures it there. - -**Two loose ends from that session**, neither performance work but both mine: - -- Roughly 220 characters of `abcdefg…` typed into one of the five open project drafts in - the real store, while testing the composer through `blitz-bench type`. -- Five UI-reachable commands with no Rust implementation — `resolveModeration` (5 - callsites), `cancelTask`, `setProjectModerator`, `setProjectStatus`, `reorderProjects` — - which `selectApi()` routes to the mock. Inferred from the routing table, never confirmed - live. `forkProject` is a sixth with no callsites and is simply dead. - -## Do next - -| # | Item | Detail | -|---|---|---| -| 1 | ~~Move `log-phase-times` off the base `blitz-dom` dependency onto `blitz-inspector`.~~ **Done** 2026-08-11, `apps/gui/Cargo.toml:33`. | [allocations.md](allocations.md) | -| 2 | ~~Bound the streaming tail block: split prose on blank lines in `extractProseStructures`.~~ **Done** 2026-08-11, along with the incremental parse that followed it. See "Done" below before re-issuing this. | [js-engine-big-problem.md](js-engine-big-problem.md) | -| 3 | **Half done, and re-measured 2026-08-25.** ~~`vmmap`/`heap` on a live instance~~ done twice: 855MB on 0.5.25, and **2.4GB on 0.8.30 after 7.5h uptime, with `MALLOC_SMALL` at 1.3G resident / 1.1G dirty**. Small live allocations are the whole story and they have more than doubled. Still open: distinct versus total attribute values on a tree. | [allocations.md](allocations.md), [blink-what-we-can-learn.md](blink-what-we-can-learn.md) section 7 | -| 4 | Make Stylo snapshots updatable (`document.rs:1258`). A correctness fix, and it unblocks the invalidation work. | [style-invalidation-we-already-ship.md](style-invalidation-we-already-ship.md) | -| 5 | **Partial.** Animation-driven redraw now distinguishes idle, CSS-only (15fps), and interactive (30fps) pacing, with interval tests in `blitz-shell/src/window.rs`. Still open: remeasure the shipped 0.6.4 stack with `BENCH_PACE=0`, confirm input-driven frames bypass the slow cadence, and record idle/active CPU plus frame-tail results. | [animation-gap.md](animation-gap.md) | -| 6 | **Re-scoped down by the 2026-08-25 measurement.** Try mimalloc as the global allocator. One line, measure, keep or drop — but the 78M of empty-but-resident regions it was aimed at is **28.6M** on the current build, against 1.3G of *live* small allocations. An allocator redistributes those; it does not remove them. Do it for the churn, not for the footprint. | [allocations.md](allocations.md) | - -Items 1 to 6 are independent of each other and of the layout cache. - -## Then, in order - -| # | Item | Gated on | Detail | -|---|---|---|---| -| 7 | Fix the Taffy cache: A/B 0.12.2 against 0.13.0, then port Yoga's validity heuristics and Chromium's LRU shape upstream | item 1 | [layout-caching-prior-art.md](layout-caching-prior-art.md) | -| 8 | Honest snapshot flags, then narrow the restyle hints | items 4 and 7 | [style-invalidation-we-already-ship.md](style-invalidation-we-already-ship.md) | -| 9 | Narrow `ALL_DAMAGE` on the mutation paths | item 7 | [dom-optimized-updates-for-solidjs.md](dom-optimized-updates-for-solidjs.md) | -| 10 | Pending invalidations: batch instead of invalidating at the mutation site | none, but composes with 12 | [blink-what-we-can-learn.md](blink-what-we-can-learn.md) section 2 | -| 11 | Cache the bezier paths (`render.rs:518`, the standing TODO) | none | [GPUI-and-zng-what-we-should-learn.md](GPUI-and-zng-what-we-should-learn.md) | -| 12 | Damage regions, stages 0 to 3 | item 1 for a clean baseline | [partial-paint.md](partial-paint.md) | - -The full DOM-side breakdown, with per-item verification steps and sizes, is -[TODO-dom-related-work.md](TODO-dom-related-work.md). - -## For the next micro release - -- ~~**The app burns ~76% CPU while completely idle.**~~ **Fixed 2026-08-12**, and - the diagnosis above was wrong in an instructive way. It is not the frontend, - and no attribute write is involved: `blitz-shell`'s `about_to_wait` set - `ControlFlow::WaitUntil` for each animation frame and, when there was no next - frame, left the control flow alone because `Wait` is the default. It is the - default and it is not what the loop is still set to: the last animation - frame's `WaitUntil` stays in force with a deadline already past, so the loop - wakes immediately and keeps waking with nothing to do. - - Two `ps -o time=` reads 15s apart, twice on two separately built binaries: - **11.45s of CPU over 15s wall before, 1.17s after — 76.3% against 7.8%.** - - Why it survived so long: there is nothing to see. `sample` on the busy process - puts the entire main thread inside the run loop, 1327 of 5071 samples in - `__CFRunLoopDoTimers` and ~800 in `mk_timer_arm`, with **no frame of layout, - style, paint or script anywhere on the stack**. Every profile of the *app* - came back empty, which read as "it must be the frontend". A stripped release - binary made it worse, since even the engine frames were `???`. - -- **Text spills past its container.** **Now reproducible, with a numeric - fingerprint**, against the real document via the debug driver. It is one bug, - not the several it looks like: overflowing inline content is **centred on its - container instead of start-aligned**, so it hangs off *both* sides of every - clipped box — tab labels, message bodies, code spans. - - Measured 2026-08-12, 40 offending elements in one session, the clearest: - - ``` - SPAN (no class) w=873 x=702 - BUTTON min-w-0 flex-1 ... text-left truncate w=230 x=1023 - ``` - - Span centre 1138.5, button centre 1138. The span should start at the parent's - left edge and be clipped by `truncate`; instead it starts 321px to its left. - The button explicitly carries `text-left`, and the alignment call in - `blitz-dom/src/layout/inline.rs:637` already passes - `align_when_overflowing: false`, so the centring is coming from somewhere - other than the `text-align` this code reads. **That is the next thing to - find**, and the reproduction is: attach the driver, walk `div,p,span`, and - report any element whose rect is wider than its parent's. - - Supersedes the previous entry here, which said this was not reproducible - synthetically and recorded two refuted mechanisms. Both refutations stand; - neither was the cause. - -## Two benchmarks to build, from real shape - -The owner's design: one for the project chat, one for settings, with the text -anonymized to gibberish preserving **length and shape**. Captured from the live -0.5.35 instance so the fixtures have a target to hit: - -| surface | nodes | role histogram | -| --- | --- | --- | -| project chat | 4,350 | generic 3,119, button 528, presentation 385, option 158 | -| settings | 4,506 | generic 3,256, button 534, presentation 389, option 158 | - -`agency-tools` (formerly and still referred to as `wt-tools`) reads the store -read-only and is safe while the GUI is open: `list-messages --bodies` gives the -length distribution the gibberish should match. - -**Do not capture a baseline until the idle CPU loop above is fixed**, or the -benchmark bakes a 30fps idle spin into its own numbers. - -## Recorded bugs, not yet investigated - -- **Transcript text runs under the turn header.** Seen on 0.5.34, 2026-08-11: the first - lines of a message render beneath the sticky `Turn N · tokens · cost` pill instead of - clearing it, so they are unreadable. The transcript carries `pt-14` - ([TranscriptPane.tsx:565](../apps/gui/frontend/src/features/project/TranscriptPane.tsx)), - which is presumably meant to reserve that space, so the question is whether the header - is taller than the reserve or is positioned outside the flow. - - A second artefact in the same screenshot: a lighter vertical band down the right of the - message bubble, roughly the width of a scrollbar gutter. Whether the two share a cause - is unknown. - - **Observed in a screenshot only.** Nothing here has been measured against the live box - tree, and a screenshot cannot tell a layout fault from a paint fault. Read the geometry - with `blitz-bench layout` before designing anything, or this becomes another session - spent on a plausible mechanism the tests then refute. - -## Open research - -Questions that are not yet decisions. Each has a document arguing a position; none has a -measurement behind it. - -- **What a frame would cost with quads as primitives rather than paths.** GPUI has no - damage regions at all and does not need them. That is a live alternative to item 12 and - belongs in its stage 0. [GPUI-and-zng-what-we-should-learn.md](GPUI-and-zng-what-we-should-learn.md) -- **Whether damage should be derived by comparison rather than from flags.** WebRender - rebuilds per-tile dependency lists every frame and diffs them, which removes the - stale-pixel failure mode by construction. It would change item 12's stage 1 before it is - built. [webrender-good-design-to-review.md](webrender-good-design-to-review.md) -- **Where the 819 MB and 3.9 GB actually go.** Candidate list exists, attribution does not. - Item 3 is the first move. [allocations.md](allocations.md) -- **Whether the renderer should keep a full-repaint model.** Decided against WebRender for - concrete reasons; the alternatives are damage regions or cheaper frames. - [why-not-webrender.md](why-not-webrender.md) -- **Renderer process isolation.** zng runs the renderer in a separate process with respawn - and a liveness watchdog. We already spawn a sidecar for the agent, and - [xpc-sidecar.md](xpc-sidecar.md) is the design that was never built. - [GPUI-and-zng-what-we-should-learn.md](GPUI-and-zng-what-we-should-learn.md) section 4 -- **JavaScript engine.** Boa has no rope strings, which is one of six passes in the - streaming quadratic. Brimstone has cons strings, is unpublished and self-describes as not - production ready. Revisit when that changes; do not act now. - [js-engine-big-problem.md](js-engine-big-problem.md) - -## Measured, 2026-08-25: the memory number has more than doubled - -`vmmap -summary` against the owner's running System instance, az-gui **0.8.30**, pid -31507, ~7.5h uptime. Read-only, so it did not disturb the process. - -| Region | Resident | Dirty | -|---|---|---| -| `MALLOC_SMALL` | **1.3G** | 1.1G, plus 407.5M swapped | -| `owned unmapped (graphics)` | 458.5M | 458.5M | -| `MALLOC_LARGE` | 86.9M | 86.9M | -| `IOSurface` | 56.4M | 56.4M | -| `MALLOC_LARGE (empty)` | 28.6M | 28.6M | -| `IOAccelerator (graphics)` | 17.7M | 10.5M | - -Physical footprint **2.4G**, peak 2.4G, against the 855MB recorded on 0.5.25. - -Three things this changes, all of them corrections to what is written above and in -[allocations.md](allocations.md): - -- **`MALLOC_SMALL` is the entire memory story, and it grew from 552M to 1.3G.** The old - reading's conclusion holds and is now much stronger. -- **"GPU-side only 67M" was wrong**, because `owned unmapped (graphics)` was not in that - accounting. GPU-side is ~533M. Vello's `ResourcePool` is still not the leading term, so - the conclusion drawn from the old number survives, but the margin is far narrower than - recorded and the pool deserves a second look if the small-allocation work lands. -- **The mimalloc item loses most of its stated justification.** It was scoped against 78M - of empty-but-resident regions; that figure is **28.6M** now. The 1.3G is *live* small - objects, and an allocator redistributes those rather than removing them. The win has to - come from allocating fewer or sharing them. - -This is uptime-sensitive: 7.5h on the System instance against a fresh one on 0.5.25, so -part of the growth is retention over a session rather than a per-build regression. That -distinction is itself worth a measurement — same build, fresh versus aged — before -attributing it. - -## Done, 2026-08-12 - -Two engine defects, both found the same way and neither by reading source: get -the process to say what it is doing, then read it. - -- **The experimental boot crash.** `--features experimental` died about two - seconds after `boot: ready` on 7 launches in 10, with `SIGSEGV`, `SIGBUS`, an - out-of-bounds index inside stylo's calc resolver and once a stack overflow. - One cause: a `calc()` reaches taffy as a raw pointer into the node's - `ComputedValues`, and the renderer cached the taffy style across restyles that - carry no relayout damage. Recolouring an element recomputes every descendant - that inherits from it, the old arc drops, and layout resolves freed memory. - Fixed in ps-blitz `87abcc1c` with a test that fails without it. Shipped 0.6.2. - - **macOS had been writing the answer to `~/Library/Logs/DiagnosticReports/` the - whole time.** One report is a write into az-gui's own read-only mapping, which - ends the "bad CSS value" reading immediately. Read those first, next time. - -- **The 76% idle spin.** See "For the next micro release" above. One line in - `blitz-shell`'s `about_to_wait`. - -**Every performance number recorded before today was taken on a machine where -this app was burning 76% of a core in the background, on the same window -thread.** The phase timings, the 8.33ms frame, the keystroke figures: all of -them. Item B's re-baseline is no longer bookkeeping. - -## Done, 2026-08-11 - -Appended as the work landed. Everything here is measured unless it says otherwise, which -is the difference between this section and the rest of this document. - -### Against the list above - -| # | Item | State | -|---|---|---| -| 1 | `log-phase-times` off the base dependency | **Done.** On `blitz-inspector` now. The `strings` check suggested for it is the weaker evidence: a bare `Resolve(` survives in both builds, so counting it alone reads as a failed removal. The call site is `#[cfg]`-gated, so the code is not compiled rather than compiled and cheap. [allocations-plan.md](allocations-plan.md) step 1 | -| 2 | Split prose on blank lines | **Done, and it was not the fix.** See "the streaming parse" below. | -| 3 | `vmmap`/`heap` on a live instance | **Half done.** 855MB resident, `MALLOC_SMALL` 552M, everything GPU-side 67M — which rules out vello's `ResourcePool` as the main cause. The distinct-versus-total attribute-value half is not done. [allocations-plan.md](allocations-plan.md) step 3 | -| 6 | mimalloc | Not started. Re-scoped by the above to a **memory** experiment, not a speed one: 78M of empty-but-resident malloc regions is the claim. | -| 7 | A/B taffy 0.12.2 against 0.13.0 | **Half done.** Bumped to 0.13.0 and the suite is green; the A/B measurement is not taken. Four call sites changed, one of them an upstream correctness fix: `grid_template_areas` now carries its own row and column counts, because a row of only `.` cells belongs to the template but to no area. | -| 11 | Cache the bezier paths | **Partly, and re-scoped.** Three per-element `BezPath` builds removed from paint. Caching stays deferred: the measurement below says clipped area is the cost, not path count. | - -### The streaming parse: 142x, measured - -`splitBlocks` was quadratic and now is not. Doubling the reply used to cost 4x and now -costs 2x; a 40KB reply spent 2348ms in the parse and now spends 16.4ms. `bun run bench` -reproduces it. Every prefix of every test body must parse identically to a full reparse, -across a fence spanning a blank line, a table, a list and an unterminated fence. - -The directive scan had the same shape and got the same treatment: only the last line is -searched, which is exact rather than a heuristic because a directive is a line. 105.9ms to -17.3ms at 40KB, and since 16.4 of that 17.3 is the parse underneath, the scan itself went -from about 90ms to about 1ms. - -**That closes the streaming quadratic.** What remains is the Boa concatenation, and -arithmetic puts it at roughly 30ms spread across a 50,000-character reply — about one -percent of the 2.3 seconds the parse cost. Leave it alone: the change it would need is -`MessageBody` and the directive scan consuming chunks across four files, and it cannot even -be measured from the test suite, because Node's V8 has cons strings and Boa does not. - -Two corrections came out of building it, both recorded in -[js-engine-big-problem.md](js-engine-big-problem.md): - -- **Step 1 of that plan wins nothing.** Boa's `Array.prototype.join` collects a - `Vec` and makes one `js_string!` call into the same `concat_array` that `+` - uses, so holding the reply as `string[]` and joining costs exactly what concatenating - cost. It is slightly worse than neutral, and it breaks the character counter and four - emptiness checks. -- ~~Passes 4 to 6 were already bounded by the `` over `/\n{2,}/`.~~ **That was wrong, - and testing it is what showed it.** Remove the blank-line flush and the paragraph-identity - test fails: with the whole reply as one block, `sameBlock` fails on it, the memo hands the - outer `` a new object, and the row is torn down along with the inner `` and every - `

` in it — so the inner value-diff never runs. Item 2 does bound the DOM write. - -### Renderer, and a correction that invalidates earlier numbers - -- **Every fps figure in this repository described the benchmark, not the app.** - `blitz-bench scroll` paced itself at 60Hz and said so nowhere. Unpaced the app runs - **120.6 fps with zero missed refreshes** and an 8.33ms interval, which is one refresh - period. The millisecond phase timings are unaffected and stand; the frame rates and - "missing a refresh" counts do not. The bench now prints its pace above the numbers that - pace governs. [allocations-plan.md](allocations-plan.md) step 10 -- **Keystroke 21.55ms to 3.50ms.** A text input answers `scrollHeight` from its parley - editor instead of forcing a full `doc.resolve`, which was 89% of the cost of typing a - character. `layout:flush_from_script` left the profile rather than shrinking. -- **Scene layers 351 to 39.** 314 of them were `background-image: none` layers, which is - still one layer in CSS, each pushing a clip and allocating a path to draw nothing. -- **Layer count is not the cost; clipped area is.** Removing those 312 bought 0.26ms. - Removing the ~30 remaining bought 2.5ms. About 0.8us for a background clip against 110us - for a scrollport clip. That redirects item 12 and the whole layer question. - [allocations-plan.md](allocations-plan.md) step 9 - -### Engine correctness fixes, each with a failing-first test - -In `ps-blitz`, unpushed on `master`. - -- **Node leak**: box construction orphaned its anonymous blocks on every rebuild, +11 nodes - per resolve, 14 nodes to 22,353 in one session. -- **Textarea measured in device pixels**: CSS pixels went into parley, device pixels came - back out, so on a 2x display a textarea wrapped at half its box width and reported four - times its height. Every existing test built its viewport at scale 1.0, the one scale at - which the confusion cancels. -- **Scroll offsets never re-clamped** when content shrank, and **`focus_node_id` / - `mousedown_node_id` surviving node removal**, which explains a crash. - -### Known open, with a measurement: the composer's second line is invisible - -Stashed at the owner's request, but the mechanism is now measured rather than described, -via `blitz-bench layout` against a live 0.5.31. - -Typing 220 characters into the project composer, reading the boxes after each pass: - -| | y | height | -|---|---|---| -| textarea, empty | 767 | 24.4 | -| after ~100 chars | 743 | **24.4** | -| after ~220 chars | 719 | **24.4** | -| `Send` / `Attach` / `Expand`, throughout | **829** | 27.8 | - -The control row never moves, so the composer shell grew 48px — exactly two lines — while -the textarea's own box stayed one line tall. The gap between the textarea's bottom and the -controls went from 37.6px to 85.6px. Something computes the right height and reserves the -space; the textarea element does not receive it. - -That points at the `field.style.height` write in `resize()` -([Composer.tsx](../apps/gui/frontend/src/features/project/Composer.tsx)) rather than at -`scrollHeight`, since `setPromptHeight` clearly got a correct number. Next step is to read -the element's computed height against what `resize()` wrote, not to theorise further. - -### Tooling - -- **`scripts/local-delivery.sh quick`**: builds the frontend dist and `az-gui`, swaps the - binary into the existing bundle, re-signs. Under a minute against several. Default to it - while iterating; build a bundle only when asked. [driving-the-app.md](driving-the-app.md) -- **Benchmarks run on request**: `bun run bench` in `apps/gui/frontend`, excluded from the - default suite so CI cost is zero. - -## Reference: what each document covers - -| Document | Covers | -|---|---| -| [performance.md](performance.md) | the measurements, plus a 2026-08-11 addendum correcting and extending them | -| [allocations.md](allocations.md) | per-frame allocation, retention, the shipping instrumentation | -| [zero-copy-and-hot-paths.md](zero-copy-and-hot-paths.md) | the copy ledger across every boundary | -| [js-engine-big-problem.md](js-engine-big-problem.md) | the streaming quadratic, Boa versus Brimstone | -| [layout-caching-prior-art.md](layout-caching-prior-art.md) | Taffy versus Yoga, Chromium, Gecko, Servo, Slint, Masonry | -| [dom-optimized-updates-for-solidjs.md](dom-optimized-updates-for-solidjs.md) | mutation-path damage faults | -| [style-invalidation-we-already-ship.md](style-invalidation-we-already-ship.md) | the Stylo invalidation we override twice | -| [blink-what-we-can-learn.md](blink-what-we-can-learn.md) | Blink subsystem review, including DOM storage | -| [partial-paint.md](partial-paint.md) | damage regions, staged plan, prior art | -| [webrender-good-design-to-review.md](webrender-good-design-to-review.md) | WebRender's design, side by side | -| [why-not-webrender.md](why-not-webrender.md) | why it is not a dependency | -| [GPUI-and-zng-what-we-should-learn.md](GPUI-and-zng-what-we-should-learn.md) | primitives instead of paths, process isolation | -| [animation-gap.md](animation-gap.md) | what is missing, what is not, and the stopgaps | -| [TODO-dom-related-work.md](TODO-dom-related-work.md) | the DOM plan in full | -| [allocations-plan.md](allocations-plan.md) | the pre-existing allocation workstream plan | -| [blitz-performance-architecture.md](blitz-performance-architecture.md) | the design thesis all of this is tested against | -| [concurrency-todo.md](concurrency-todo.md) | what runs on the window thread, ours against Chromium, Gecko, Stylo and fastrender | -| [build-graph-witnesses.md](build-graph-witnesses.md) | asserting in CI that we build what we think we build | -| [concurrency-todo.md](concurrency-todo.md) | what runs on the window thread, ours against Chromium, Gecko, Stylo and fastrender | - -Chuzz has a parallel set at `chuzz/docs/`, including its own `TODO.md`. Items marked ENGINE -in either repository need landing in both trees, or the trees need converging first. - -## Concurrency, added 2026-08-12 - -Source review, not measurement. Full reasoning, the ours-against-theirs comparison with -line numbers, and the per-item verification steps are in -[concurrency-todo.md](concurrency-todo.md). Read it before acting on any line below: three -of these are one-line changes whose *measurement* has an ordering constraint, and one is a -research item that must start with a count rather than a fix. - -The finding behind all of it: with Blitz in process the window thread owns OS events, Boa, -style, layout, paint, `present` **and** every non-async Tauri command. Under WebKit those -lived in another process, so habits carried over from that build are mispriced. - -| # | Item | Gated on | Detail | -|---|---|---|---| -| 13 | **Count how often `resolve.rs:663` clears the whole document's taffy cache.** It fires when any inline layout is reconstructed, which reading the mutation paths suggests is every streaming token and every tab switch. If so it outranks everything else here, and the measured "0.27ms per keystroke" describes only resolves that do not reconstruct. | none | [concurrency-todo.md](concurrency-todo.md) B1 | -| 14 | **Set `BLITZ_PRESENT_MODE=mailbox`.** `AutoVsync` is FIFO and its `present` parks the window thread until vblank, so a 3ms frame still costs a refresh interval and input slips two frames. The renderer's own source says so; nothing sets it. **This blocks the measurement of 15, 16 and 17**, because under FIFO a main-thread saving does not show up in frame time. | none | [concurrency-todo.md](concurrency-todo.md) A1 | -| 15 | **Pass Stylo a thread pool** (`main.rs:95`, `StyleThreading::Parallel`). We link Firefox's parallel style traversal and run it sequentially, because `DocumentConfig` defaults to `Sequential` and its own doc comment says the opposite. The multi-document hazard the comment warns about does not apply: one document, no iframes, one resolving thread. | 14 | [concurrency-todo.md](concurrency-todo.md) A2 | -| 16 | **Partial.** `blitz-dom/parallel-construct` is enabled in `apps/gui/Cargo.toml`, so the existing rayon fan-out ships. Still open: a 0.6.4 on/off A/B for tab switching, shaping time, and RSS; item 19 also records the missing Genet pre-pass work rather than treating the feature flip as the complete optimization. | 14 | [concurrency-todo.md](concurrency-todo.md) A3 | -| 17 | **Move the heavy read-only Tauri commands off the window thread** with `#[tauri::command(async)]`. 34 of 97 commands are non-async and therefore execute between two frames of the UI they serve, including `list_messages`, `list_task_log` and a filesystem walk in `list_table_sizes`. Audit call-order dependence first; leave the cheap ones and the writers sync. | none, but audit before edit | [concurrency-todo.md](concurrency-todo.md) C1, C2 | -| 18 | **Decide whether the renderer moves to its own thread**, fastrender's model: UI thread does OS events and message passing, renderer worker does the pipeline. Needs a `Send` audit and interacts with the main-thread id checks in `izumo`. Compositor-style scroll is the item after it and composes with item 12. | 14, 17 measured | [concurrency-todo.md](concurrency-todo.md) D1, D2 | - -**Not on the list, with the reason:** parallel layout (no engine worth copying does it, and -our cost is cache behaviour, which is item 7); moving DOM teardown to a worker (Boa and -`blitz-dom` are deliberately single-threaded, so there is nothing separable to hand over); -anything from fastrender's multiprocess design (unimplemented there). - -## From the Genet review, added 2026-08-12 - -Source reading, not measurement, from Genet read at `main` on 2026-08-12. Each doc named -below carries a dated addendum at its bottom with the line numbers and the detail; the -dependency audit that decided the adoption question is at the end of this section. Genet is a Servo fork on our exact stack (Stylo, Taffy, parley, -vello), so where it disagrees with us that is evidence rather than opinion. - -**Two items above are amended rather than added to.** Item 16 is no longer a one-line -feature flip, and item 12 gains a prerequisite. - -| # | Item | Gated on | Detail | -|---|---|---|---| -| 19 | **Amends item 16.** Port the four parts of Genet's shaping pre-pass, not just the rayon call: split width-independent shaping from line breaking; add a threshold (theirs is 24 leaves, and our whole document is the chrome UI their comment says to keep serial); **skip `display: none` leaves**, which is most of what a tab switch reconstructs given nine retained tabs and may be worth more than the parallelism; add a `GENET_SHAPE_SERIAL`-style A/B switch. Their `map_init` also softens item 16's memory caveat: the font-context clone is per worker, not per item, and parley's `Collection` is shared. | 14 | [concurrency-todo.md](concurrency-todo.md) addendum | -| 20 | **A paint-list IR between layout and the renderer.** Genet emits a `GenetPaintList` and lowers it to a scene in a separate crate, GPU-free. We paint straight from the DOM into a vello `Scene` inside `View::redraw`, so there is no value to diff, send or test. **This is the missing prerequisite under three separate workstreams**: item 12's stages 1 and 2, concurrency item 18's renderer thread, and the "Stage rendering and carry change metadata forward" decision that has sat unbuilt in the architecture doc. Sequence it before item 12 rather than beside it. | 13, and a decision on IR shape | [partial-paint.md](partial-paint.md) addendum, [blitz-performance-architecture.md](blitz-performance-architecture.md) addendum | -| 21 | **Research: a script-engine seam, keeping Boa behind it.** Genet runs Boa, Nova and Piccolo through one `ScriptEngine` trait, with `Budget`/`PumpOutcome`/`eval_bounded`/`pump` making script cooperatively interruptible. That is also the yield point concurrency section 2.8 says we lack. **Not free**: they carry forks of both Boa and Nova to get weak reflector references, because engines disagree about GC handles. Build it only if a second engine is actually wanted. | none | [js-engine-big-problem.md](js-engine-big-problem.md) addendum | -| 22 | **W1: assert the engine's resolved features.** Compare `cargo tree -e features -i` output for `ps-blitz-dom`, `ps-blitz-script` and `ps-anyrender-vello` against a checked-in expectation, and fail the build on a diff. Highest value of the five: this is the check that would have caught `incremental` being absent, which cost a measured 13x, and it catches item 16 in reverse once `parallel-construct` is on. | none | [build-graph-witnesses.md](build-graph-witnesses.md) W1 | -| 23 | **W2: assert instrumentation is absent from release** and present in the inspector build (`log-phase-times`, `dom-stats`). Item 1 fixed the instance by moving the feature onto `blitz-inspector`; nothing stops it moving back. **Retires constraint 2 at the top of this file.** | none | [build-graph-witnesses.md](build-graph-witnesses.md) W2 | -| 24 | **W3: assert exactly one copy of each pivotal crate** (`stylo`, `ps-taffy`, `ps-anyrender`, `ps-anyrender-vello`, `wgpu`, `parley`, `boa_engine`). All seven are single copies as of 2026-08-12, so this is cheap while it is true and expensive after it breaks. `stylo` is the one that fails as a link error rather than a type error, because it declares `links = "servo_style_crate"`. | none | [build-graph-witnesses.md](build-graph-witnesses.md) W3 | -| 25 | **W4: assert no local `[patch]` path reaches a shipped build.** Aimed at the committed `taffy = "../ps-taffy"` path that HANDOVER calls the sharpest edge in the tree, and at the tracked `.cargo/config.toml` patch block that makes a local build silently different from a release one. | none | [build-graph-witnesses.md](build-graph-witnesses.md) W4 | -| 26 | **W5: assert a target-aware native-dependency inventory** for the macOS release target. Note the trap before writing it: `Cargo.lock` names 34 `-sys` crates including the whole GTK and WebKit stack, none of which macOS builds, so the naive lock grep returns 34 false positives and gets switched off within a week. It has to be `cargo tree --target`. | none | [build-graph-witnesses.md](build-graph-witnesses.md) W5 | - -**Items 22 to 26 are one class, not five unrelated checks.** We have hit "the build graph is -not what we believed" four times and recorded each separately: `blitz-dom/incremental` absent -and costing a measured 13x, `log-phase-times` shipping in release while being used to measure -it, `ps-anyrender-vello` reaching the app through `izumo` rather than where it -was looked for, and Genet's own fontconfig failure seen from outside. Genet asserts its -architecture mechanically instead, and its wasm target check would have replaced the entire -audit above with one command. The class, the prior art and the five traps are in -[build-graph-witnesses.md](build-graph-witnesses.md). None of the five is implemented. - -**Recorded, not actioned:** Genet vendors Taffy `=0.12.1` with three patches (float slot -width-fit, a float exclusion-band accessor, flex `order`) that touch no file `ps-taffy` -touches. Worth reading before either fork drifts, and before `float_layout` ever becomes -ours. Not a reason to bump; their pin is 0.12.1 and item 7's A/B against 0.13.0 is -unaffected. See the [layout-caching-prior-art.md](layout-caching-prior-art.md) addendum. - -**Negative result, recorded so it is not rediscovered:** Genet has not enabled Stylo's -parallel traversal either (`cascade.rs:374`, "Sequential (no rayon pool)"). Item 15 is -unexploited in both trees on the same stack. That is a reason to try it and a reason to -stop calling it a known win. - -### The dependency audit, and the adoption verdict - -The question that produced this section was whether Genet carries system or hidden C++ -dependencies. The answer is not one answer, which is why it is recorded rather than -summarised. - -**Method, and its limit.** Treeless shallow clone (`--depth 1 --filter=blob:none ---no-checkout`), 7.1 MB for 187,905 files, then per-file reads. **No `Cargo.lock` is -committed**, so the closure below is a manifest walk resolving `[workspace.dependencies]` -aliases to local paths, not a resolved graph. Feature unification can pull in what a -manifest walk misses, so treat it as a floor. A real `cargo tree` cannot be run today -because their build does not pass. - -**In-tree: clean.** Zero `.c/.cc/.cpp/.h/.m/.mm` files outside `tests/`, which is WPT and -is 186,173 of the 187,905 files. Three `build.rs` in the repository, none containing -`cc::`, `cmake`, `bindgen` or `Command::new`. - -**Pelt's closure: one C dependency.** `default-members = ["ports/pelt"]`, and that closure -is 60 local crates and 148 external. The only non-Rust build input is **`ring 0.17`**, via -`components/netfetcher` (`rustls` with `features = ["ring"]`, `ring` directly, plus `quinn` -and `h3`), which compiles C and per-architecture assembly. It is deliberate: their -`Cargo.toml:127` records removing `aws-lc-rs` to avoid "NASM-required C+asm crypto" and -names ring or `rustls-rustcrypto` as the replacements. Everything else that touches the -platform binds rather than builds (`windows`, `ash` which dlopens libvulkan, `libc`, -`mach2`, `dwrote` on Windows only, the AccessKit adapters, `arboard`). No HarfBuzz, -FreeType, fontconfig, SpiderMonkey, GStreamer or jemalloc. - -**The workspace: all of it comes back**, through two vestigial Servo islands. -`components/fonts` declares `harfbuzz-sys` with `features = ["bundled"]`, which compiles -vendored HarfBuzz C++, plus `freetype-sys`, `yeslogic-fontconfig-sys` and `dwrote`; it is -reached only by `components/shared/layout`, which `genet-layout` explicitly does not use -(its manifest carries the commented-out line `# layout_api = ... # EXPERIMENT: genet-layout -uses parley, not servo-fonts/layout-api`). Separately, `components/media/examples` is a -workspace member and depends on `servo-media-auto`, which selects `servo-media-gstreamer` -on x86_64 and aarch64, pulling `gstreamer-sys`, `glib-sys` and eleven more pkg-config -crates. - -**Their CI proves it rather than the audit asserting it.** `cargo check --workspace ---all-targets` on `ubuntu-latest` with no apt step has failed on every run since at least -2026-08-09, on `yeslogic-fontconfig-sys`'s build script panicking with "pkg-config exited -with status code 1", and the same log shows the GStreamer `-sys` family being downloaded on -the way there. Their `cargo check -p genet-layout --target wasm32-unknown-unknown` witness -is **skipped** because the workspace check fails first, so their no-native-deps proof is -currently unproven rather than passing. - -**Verdict.** The README's "entirely Rust" is true of the thing you would embed, apart from -ring, and false of the repository. **Do not depend on Genet**: one author, 0 stars, a -21,000-line layout engine against a moving WPT target, and a build that does not pass. Read -it for designs. - -**One hazard to record in case it ever matters.** Only one Stylo is allowed in a dependency -graph, because `stylo` declares `links = "servo_style_crate"` and `[patch]` cannot rename -its target. Genet solved it by renaming and publishing their fork as `genet-stylo`. We -reach stylo 0.20 through ps-blitz, so two Stylos in one binary is a link error at best. - -### What item 22 would be asserting - -Genet's `support/ci/check_dependency_cones.py` fails CI unless: `genet-extract`'s dependency -set is **exactly** `{layout_dom_api}`; its build-dependencies are empty and its -dev-dependencies are fixtures only; it never reaches `genet-layout`, `genet-render`, -`paint`, `paint_list_render`, `netrender` or `wgpu`; and no crate under `components/` -path-depends on anything under `ports/`. The wasm target check is the second witness. Note -that the cone check passes on every one of their red runs, which is the point: it catches -the class of error it is aimed at, and says nothing about the one they actually have. diff --git a/scripts/blitz-control.sh b/scripts/blitz-control.sh index b320dd2c..fe21764b 100755 --- a/scripts/blitz-control.sh +++ b/scripts/blitz-control.sh @@ -1,6 +1,7 @@ #!/usr/bin/env sh set -eu +set +x if [ "$(uname -s)" != "Darwin" ]; then echo "blitz-control.sh currently supports macOS only (it reads the descriptor with plutil)" >&2 @@ -70,10 +71,11 @@ case "$command" in esac driver_token=$(json_field "$descriptor" token) -session_response=$(/usr/bin/curl --silent --show-error --fail --max-time 5 \ +session_response=$(printf '%s' "{\"capabilities\":{\"alwaysMatch\":{\"blitz:token\":\"$driver_token\"}}}" \ + | /usr/bin/curl --silent --show-error --fail --max-time 5 \ -X POST "http://$driver_address/session" \ -H 'Content-Type: application/json' \ - --data "{\"capabilities\":{\"alwaysMatch\":{\"blitz:token\":\"$driver_token\"}}}") + --data-binary @-) session_id=$(/usr/bin/printf '%s' "$session_response" \ | /usr/bin/sed -n 's/.*"sessionId":"\([^"]*\)".*/\1/p') if [ -z "$session_id" ]; then From 87e753f01f5cfa21c0439c19920d4f26d84c95f5 Mon Sep 17 00:00:00 2001 From: meh Date: Thu, 5 Nov 2026 20:29:21 +0700 Subject: [PATCH 2/4] Update project source --- .github/workflows/release-experimental.yml | 27 +- .github/workflows/release.yml | 35 ++- Cargo.toml | 15 +- apps/blitz-preview/Cargo.toml | 17 +- apps/blitz-preview/src/main.rs | 205 ++++++++++++-- apps/gui/Cargo.toml | 14 +- apps/gui/src/main.rs | 298 ++++++++++++++++++++- docs/plans/native-ekojit-integration.md | 48 ++++ scripts/owner-build.sh | 2 +- 9 files changed, 601 insertions(+), 60 deletions(-) create mode 100644 docs/plans/native-ekojit-integration.md diff --git a/.github/workflows/release-experimental.yml b/.github/workflows/release-experimental.yml index 2f12cd82..1de11913 100644 --- a/.github/workflows/release-experimental.yml +++ b/.github/workflows/release-experimental.yml @@ -167,10 +167,14 @@ jobs: STORAGE_API_KEY: ${{ secrets.BUNNYCDN_STORAGE_API_KEY }} STORAGE_NAME: ${{ secrets.BUNNYCDN_STORAGE_NAME }} run: | + set +x + storage_request() { + { printf 'AccessKey: %s\n' "$STORAGE_API_KEY"; } | curl -H @- "$@" + } gunzip -t "$TARBALL" - curl -sS -X DELETE -H "AccessKey: $STORAGE_API_KEY" \ + storage_request -sS -X DELETE \ "https://storage.bunnycdn.com/$STORAGE_NAME/$CDN_DIR/AgencyZeroExperimental.app.tar.gz" || true - curl -sS --fail-with-body -X PUT -H "AccessKey: $STORAGE_API_KEY" \ + storage_request -sS --fail-with-body -X PUT \ -T "$TARBALL" \ "https://storage.bunnycdn.com/$STORAGE_NAME/$CDN_DIR/AgencyZeroExperimental.app.tar.gz" @@ -179,7 +183,11 @@ jobs: ZONE_API_KEY: ${{ secrets.BUNNYCDN_ZONE_API_KEY }} ZONE_ID: ${{ secrets.BUNNYCDN_ZONE_ID }} run: | - curl -sS --fail-with-body -X POST -H "AccessKey: $ZONE_API_KEY" \ + set +x + zone_request() { + { printf 'AccessKey: %s\n' "$ZONE_API_KEY"; } | curl -H @- "$@" + } + zone_request -sS --fail-with-body -X POST \ "https://bunnycdn.com/api/pullzone/$ZONE_ID/purgeCache" LOCAL=$(shasum -a 256 "$TARBALL" | cut -d' ' -f1) for attempt in 1 2 3 4 5 6; do @@ -201,12 +209,19 @@ jobs: ZONE_API_KEY: ${{ secrets.BUNNYCDN_ZONE_API_KEY }} ZONE_ID: ${{ secrets.BUNNYCDN_ZONE_ID }} run: | - curl -sS -X DELETE -H "AccessKey: $STORAGE_API_KEY" \ + set +x + storage_request() { + { printf 'AccessKey: %s\n' "$STORAGE_API_KEY"; } | curl -H @- "$@" + } + zone_request() { + { printf 'AccessKey: %s\n' "$ZONE_API_KEY"; } | curl -H @- "$@" + } + storage_request -sS -X DELETE \ "https://storage.bunnycdn.com/$STORAGE_NAME/$CDN_DIR/latest.json" || true - curl -sS --fail-with-body -X PUT -H "AccessKey: $STORAGE_API_KEY" \ + storage_request -sS --fail-with-body -X PUT \ -T latest-experimental.json \ "https://storage.bunnycdn.com/$STORAGE_NAME/$CDN_DIR/latest.json" - curl -sS --fail-with-body -X POST -H "AccessKey: $ZONE_API_KEY" \ + zone_request -sS --fail-with-body -X POST \ "https://bunnycdn.com/api/pullzone/$ZONE_ID/purgeCache" for attempt in 1 2 3 4 5 6; do diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f7ac9ca0..c2dc3e07 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -267,6 +267,10 @@ jobs: STORAGE_API_KEY: ${{ secrets.BUNNYCDN_STORAGE_API_KEY }} STORAGE_NAME: ${{ secrets.BUNNYCDN_STORAGE_NAME }} run: | + set +x + storage_request() { + { printf 'AccessKey: %s\n' "$STORAGE_API_KEY"; } | curl -H @- "$@" + } # A truncated or corrupt local build must never reach storage; after # this gate, any corruption seen at the edge is the CDN's doing. gunzip -t "$BUNDLE_DIR/AgencyZero.app.tar.gz" || { @@ -274,10 +278,10 @@ jobs: } upload() { local file="$1" dest="$2" attempt=1 code - curl -sS -X DELETE -H "AccessKey: $STORAGE_API_KEY" \ + storage_request -sS -X DELETE \ "https://storage.bunnycdn.com/$STORAGE_NAME/$dest" || true while [ "$attempt" -le 4 ]; do - code=$(curl -sS -X PUT -H "AccessKey: $STORAGE_API_KEY" \ + code=$(storage_request -sS -X PUT \ -T "$file" -o /dev/null -w '%{http_code}' \ "https://storage.bunnycdn.com/$STORAGE_NAME/$dest") case "$code" in @@ -301,11 +305,15 @@ jobs: ZONE_API_KEY: ${{ secrets.BUNNYCDN_ZONE_API_KEY }} ZONE_ID: ${{ secrets.BUNNYCDN_ZONE_ID }} run: | + set +x + zone_request() { + { printf 'AccessKey: %s\n' "$ZONE_API_KEY"; } | curl -H @- "$@" + } if [ -z "$ZONE_API_KEY" ] || [ -z "$ZONE_ID" ]; then echo "::error::BUNNYCDN_ZONE_API_KEY and BUNNYCDN_ZONE_ID are required: a versionless URL that is not purged serves the previous release forever." exit 1 fi - curl -sS --fail-with-body -X POST -H "AccessKey: $ZONE_API_KEY" \ + zone_request -sS --fail-with-body -X POST \ "https://bunnycdn.com/api/pullzone/$ZONE_ID/purgeCache" echo "purged pull zone $ZONE_ID" @@ -314,6 +322,10 @@ jobs: ZONE_API_KEY: ${{ secrets.BUNNYCDN_ZONE_API_KEY }} ZONE_ID: ${{ secrets.BUNNYCDN_ZONE_ID }} run: | + set +x + zone_request() { + { printf 'AccessKey: %s\n' "$ZONE_API_KEY"; } | curl -H @- "$@" + } LOCAL=$(shasum -a 256 "$BUNDLE_DIR/AgencyZero.app.tar.gz" | cut -d' ' -f1) for attempt in 1 2 3 4 5 6; do curl -sS -L -o edge.tar.gz "$CDN_BASE/AgencyZero.app.tar.gz" || true @@ -327,7 +339,7 @@ jobs: echo "attempt $attempt: edge has $REMOTE, want $LOCAL" if [ "$attempt" = 3 ]; then echo "::warning::edge still stale after purge; purging the zone again" - curl -sS --fail-with-body -X POST -H "AccessKey: $ZONE_API_KEY" \ + zone_request -sS --fail-with-body -X POST \ "https://bunnycdn.com/api/pullzone/$ZONE_ID/purgeCache" || true fi sleep 10 @@ -343,11 +355,18 @@ jobs: ZONE_API_KEY: ${{ secrets.BUNNYCDN_ZONE_API_KEY }} ZONE_ID: ${{ secrets.BUNNYCDN_ZONE_ID }} run: | - curl -sS -X DELETE -H "AccessKey: $STORAGE_API_KEY" \ + set +x + storage_request() { + { printf 'AccessKey: %s\n' "$STORAGE_API_KEY"; } | curl -H @- "$@" + } + zone_request() { + { printf 'AccessKey: %s\n' "$ZONE_API_KEY"; } | curl -H @- "$@" + } + storage_request -sS -X DELETE \ "https://storage.bunnycdn.com/$STORAGE_NAME/$CDN_DIR/latest.json" || true - curl -sS --fail-with-body -X PUT -H "AccessKey: $STORAGE_API_KEY" \ + storage_request -sS --fail-with-body -X PUT \ -T latest.json "https://storage.bunnycdn.com/$STORAGE_NAME/$CDN_DIR/latest.json" - curl -sS --fail-with-body -X POST -H "AccessKey: $ZONE_API_KEY" \ + zone_request -sS --fail-with-body -X POST \ "https://bunnycdn.com/api/pullzone/$ZONE_ID/purgeCache" # latest.json is the version record, so a stale edge copy here means @@ -363,7 +382,7 @@ jobs: echo "attempt $attempt: edge serves '$LIVE', want '$VERSION'" if [ "$attempt" = 3 ]; then echo "::warning::edge still stale after purge; purging the zone again" - curl -sS --fail-with-body -X POST -H "AccessKey: $ZONE_API_KEY" \ + zone_request -sS --fail-with-body -X POST \ "https://bunnycdn.com/api/pullzone/$ZONE_ID/purgeCache" || true fi sleep 10 diff --git a/Cargo.toml b/Cargo.toml index 26b4402a..2459f9ca 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ members = [ exclude = ["crates/wt-migrate/v2-reader"] [workspace.package] -version = "0.8.67" +version = "0.8.68" edition = "2024" publish = false @@ -33,17 +33,8 @@ worktable = "1.10.0-beta1" # Tauri stack, so agent/proxy builds never trigger a webview toolchain build. # Local debugging only, alongside the path overrides in apps/gui/Cargo.toml. -# `izumo` takes blitz-dom and blitz-script by path but blitz-shell -# and blitz-traits from git at the same rev. Cargo treats those as two distinct -# crates, so the same trait exists twice and `ScriptDocument` stops satisfying -# `Document`, which reads as eleven unrelated type errors inside a dependency -# nobody edited. Redirect the git source at the checkout the paths already use. -# Same reason as the ps-blitz patch below: a local checkout so the present mode -# can be switched at runtime. FIFO blocks the main thread in `present`, which -# stalls event handling for a whole refresh interval per frame. -# The hybrid backend takes `anyrender` from crates.io while the vello backend -# takes the patched git one, which gives two copies of the trait and a renderer -# that cannot satisfy it. Pin both to the same checkout. +# The Ekojit adapter and renderer crates must resolve from the same checkouts so +# the document and host traits have one identity throughout the graph. [profile.dev] # GUI diagnostics come from logs and backtraces. Generating full symbol tables # for WebKit and Tauri dependencies dominated clean local check time. diff --git a/apps/blitz-preview/Cargo.toml b/apps/blitz-preview/Cargo.toml index d9aaef35..ed950452 100644 --- a/apps/blitz-preview/Cargo.toml +++ b/apps/blitz-preview/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "agencyzero-blitz-preview" description = "Native Blitz and Boa preview shell for the AgencyZero frontend" -version = "0.5.0" +version = "0.5.1" edition = "2024" publish = false build = "build.rs" @@ -17,14 +17,17 @@ anyrender_vello_cpu = { package = "ps-anyrender-vello-cpu", version = "^0.16.0", # The ps-blitz line has to match izumo's: `izumo::set_document_factory` takes # a factory returning its own `ps-blitz-script` `ScriptDocument`, and a second # release line here would be a second, incompatible `ScriptDocument` type. -blitz-dom = { package = "ps-blitz-dom", version = "^0.4", features = ["system-fonts"] } -blitz-paint = { package = "ps-blitz-paint", version = "^0.4", features = ["scrollbars"] } -blitz-script = { package = "ps-blitz-script", version = "^0.4", features = ["system-fonts"] } -blitz-traits = { package = "ps-blitz-traits", version = "^0.4" } +blitz-dom = { package = "ps-blitz-dom", version = "^0.6.5", features = ["system-fonts"] } +blitz-paint = { package = "ps-blitz-paint", version = "^0.6.5", features = ["scrollbars"] } +blitz-script = { package = "ps-blitz-script", version = "^0.6.5", features = ["system-fonts"] } +blitz-script-ekojit = { package = "ps-blitz-script-ekojit", version = "^0.1.0", path = "../../../ekojit/crates/blitz-script-ekojit", features = ["system-fonts"] } +blitz-traits = { package = "ps-blitz-traits", version = "^0.6.5" } brotli = { version = "^8.0.4", default-features = false, features = ["std"] } png = { version = "^0.18.1", optional = true } tauri = { version = "^2.11.5", default-features = false, features = ["compression"] } -izumo = "^0.4" +izumo = "^0.6.5" +blitz-control-protocol = "^0.7.2" +serde_json = "1" url = "^2.5.8" # For `--offscreen`: the activation policy has to be set before any window @@ -50,7 +53,7 @@ capture = ["dep:anyrender_vello_cpu", "dep:png"] # `diagnosticsUnavailable`, which reads as a broken harness rather than a # missing feature. It is idle-cheap: the runtime flag still gates the work. default = ["diagnostics"] -diagnostics = ["izumo/diagnostics"] +diagnostics = ["izumo/diagnostics", "blitz-script-ekojit/debug-control"] [profile.release] codegen-units = 1 diff --git a/apps/blitz-preview/src/main.rs b/apps/blitz-preview/src/main.rs index 3296b4c1..85e8a9bc 100644 --- a/apps/blitz-preview/src/main.rs +++ b/apps/blitz-preview/src/main.rs @@ -3,7 +3,8 @@ // configuration now. use blitz_dom::Document; use blitz_dom::DocumentConfig; -use blitz_script::{DefaultScriptFetcher, FetchError, ScriptDocument, ScriptFetcher}; +use blitz_script::{DefaultScriptFetcher, FetchError, ScriptFetcher}; +use blitz_script_ekojit::{EkojitDocument, NativePageDefect, PageSource, TypedNativeGuest}; #[cfg(all(not(test), feature = "capture"))] use blitz_traits::shell::{ColorScheme, Viewport}; use brotli::Decompressor; @@ -11,6 +12,7 @@ use izumo::{builder, set_document_factory, set_runtime_trace}; #[cfg(not(test))] use std::fs::{self, OpenOptions}; use std::io::Read; +use std::sync::Arc; #[cfg(not(test))] use std::io::Write; #[cfg(not(test))] @@ -95,22 +97,186 @@ fn decompress_utf8(compressed: &[u8], label: &str) -> Result { Ok(decoded) } -fn create_document(url: &str) -> Result { +struct PreviewBlitzDocument { + document: EkojitDocument, + poll_hooks: Vec, +} + +impl PreviewBlitzDocument { + fn execute_scripts(&mut self) { + let _ = TypedNativeGuest::execute_scripts(&mut self.document); + } + + fn eval(&mut self, source: &str) { + let _ = self.document.eval_source(Arc::new(PageSource { + text: Arc::from(source), + url: Arc::from("preview:eval"), + })); + } + + fn eval_json(&mut self, source: &str) -> Result { + self.document.with_embedder_host(|host| host.eval_json(source)) + } + + fn external_script_urls(&self) -> Vec { + let inner = self.document.inner(); + inner.query_selector_all("script[src]").unwrap_or_default().into_iter() + .filter_map(|id| inner.get_node(id)) + .filter_map(|node| node.element_data()) + .filter_map(|element| element.attr(blitz_dom::LocalName::from("src"))) + .filter_map(|src| inner.url().join(src).ok()) + .collect() + } + + fn run_poll_hooks(&mut self, context: Option<&std::task::Context<'_>>) -> bool { + let mut hooks = std::mem::take(&mut self.poll_hooks); + let mut work = false; + for hook in &mut hooks { work |= hook(self, context); } + hooks.append(&mut self.poll_hooks); + self.poll_hooks = hooks; + work + } +} + +impl Document for PreviewBlitzDocument { + fn inner(&self) -> blitz_dom::DocGuard<'_> { Document::inner(&self.document) } + fn inner_mut(&mut self) -> blitz_dom::DocGuardMut<'_> { Document::inner_mut(&mut self.document) } + fn handle_ui_event(&mut self, event: blitz_traits::events::UiEvent) { + Document::handle_ui_event(&mut self.document, event) + } + fn poll(&mut self, context: Option>) -> bool { + let mut work = Document::poll(&mut self.document, context.as_ref().map(|cx| std::task::Context::from_waker(cx.waker()))); + work |= self.run_poll_hooks(context.as_ref()); work + } + fn poll_for_settle(&mut self, context: Option>, run_timers: bool) -> bool { + let mut work = Document::poll_for_settle(&mut self.document, context.as_ref().map(|cx| std::task::Context::from_waker(cx.waker())), run_timers); + work |= self.run_poll_hooks(context.as_ref()); work + } + fn prepare_teardown(&mut self) { Document::prepare_teardown(&mut self.document) } + fn dispose(self: Box) -> Arc { + let Self { document, .. } = *self; Box::new(document).dispose() + } + fn set_page_visible(&mut self, visible: bool) { Document::set_page_visible(&mut self.document, visible) } + fn freeze(&mut self) { Document::freeze(&mut self.document) } + fn finish_restore(&mut self) { Document::finish_restore(&mut self.document) } + fn resume(&mut self) { Document::resume(&mut self.document) } +} + +impl blitz_control_protocol::ControlScriptBackend for PreviewBlitzDocument { + fn dispatch_dom_event(&mut self, event: blitz_traits::events::DomEvent) { self.document.handle_dom_event(event); } + fn handle_pointer_move_to_node(&mut self, event: blitz_traits::events::BlitzPointerEvent, node: blitz_dom::NodeId) { + self.document.handle_pointer_move_to_node(event, node); + } + fn handle_ui_event_to_node(&mut self, event: blitz_traits::events::UiEvent, node: blitz_dom::NodeId) { + self.document.handle_ui_event_to_node(event, node); + } +} + +struct PreviewDocumentHost; + +fn preview_document(document: &dyn Document) -> Option<&PreviewBlitzDocument> { + (document as &dyn std::any::Any).downcast_ref() +} +fn preview_document_mut(document: &mut dyn Document) -> Option<&mut PreviewBlitzDocument> { + (document as &mut dyn std::any::Any).downcast_mut() +} + +impl izumo::DocumentHost for PreviewDocumentHost { + fn current_url(&self, document: &dyn Document) -> Option { Some(preview_document(document)?.inner().url().clone()) } + fn eval(&self, document: &mut dyn Document, source: &str) { + if let Some(doc) = preview_document_mut(document) { doc.eval(source); } + } + fn eval_json(&self, document: &mut dyn Document, source: &str) -> Result { + preview_document_mut(document).ok_or_else(|| String::from("unsupported preview document"))?.eval_json(source) + } + fn set_ipc_handler(&self, document: &mut dyn Document, handler: Box) { + struct IpcHandler(Box); + fn ipc_post_message( + realm: &mut blitz_script_ekojit::embedder::RealmHost<'_>, + args: &[blitz_script_ekojit::embedder::HostValue], + ) -> Result< + blitz_script_ekojit::embedder::HostValue, + blitz_script_ekojit::embedder::NativeFailure, + > { + if let Some(handler) = realm.state::("preview.ipc") + && let Some(blitz_script_ekojit::embedder::HostValue::Utf16(units)) = args.first() + { + (handler.0)(String::from_utf16_lossy(units)); + } + Ok(blitz_script_ekojit::embedder::HostValue::Undefined) + } + if let Some(doc) = preview_document_mut(document) { + let _ = doc.document.with_realm_host(|realm| { + realm.set_state("preview.ipc", std::rc::Rc::new(IpcHandler(handler)))?; + realm.register_intrinsic("__previewIpcPostMessage", 1, ipc_post_message) + }); + doc.eval("globalThis.ipc = { postMessage: function(msg) { __previewIpcPostMessage(String(msg)); } };"); + } + } + fn add_poll_hook(&self, document: &mut dyn Document, hook: izumo::DocumentPollHook) { + if let Some(doc) = preview_document_mut(document) { doc.poll_hooks.push(hook); } + } + fn service_debug_controller(&self, _document: &mut dyn Document, _controller: &mut blitz_script::DebugController, _animation_time: f64) -> bool { false } + fn agent(&self, document: &mut dyn Document, control: &mut blitz_control_protocol::in_process::DocumentControl, request: blitz_control_protocol::AgentControlRequest) -> blitz_control_protocol::DebugResponse { + match preview_document_mut(document) { + Some(doc) => control.agent(doc, request), + None => blitz_control_protocol::DebugResponse::Error(blitz_control_protocol::DebugError { code: "unsupportedDocument".into(), message: "document is not owned by the preview".into() }), + } + } + fn diagnostics(&self, _document: &mut dyn Document, _control: &mut blitz_control_protocol::in_process::DocumentControl, _request: blitz_control_protocol::DiagnosticsRequest) -> blitz_control_protocol::DebugResponse { + blitz_control_protocol::DebugResponse::Error(blitz_control_protocol::DebugError { code: "unsupportedRequest".into(), message: "preview diagnostics requests are unsupported".into() }) + } + fn diagnostic_batch(&self, document: &dyn Document, console_after: u64, errors_after: u64, limit: usize) -> blitz_script::DiagnosticBatch { + let empty = |next_sequence| blitz_script::DiagnosticStreamBatch { entries: Vec::new(), lost: 0, next_sequence }; + let Some(doc) = preview_document(document) else { return blitz_script::DiagnosticBatch { console: empty(console_after), errors: empty(errors_after) }; }; + let stream = |entries: Vec, after| { + let entries = entries.into_iter().filter(|entry| entry.sequence > after).take(limit.clamp(1, 1000)).collect::>(); + let next_sequence = entries.last().map_or(after, |entry| entry.sequence); + blitz_script::DiagnosticStreamBatch { entries, lost: 0, next_sequence } + }; + blitz_script::DiagnosticBatch { console: stream(doc.document.console_entries(), console_after), errors: stream(doc.document.runtime_errors(), errors_after) } + } +} + +fn create_document(url: &str) -> Result { trace("document factory entered"); let css = decompress_utf8(EMBEDDED_CSS_BROTLI, "CSS")?; trace("CSS Brotli decompression completed"); let html = EMBEDDED_SHELL_HTML.replacen(EMBEDDED_CSS_MARKER, &css, 1); - let config = DocumentConfig { - base_url: Some(url.into()), - ..DocumentConfig::default() - }; - let document = ScriptDocument::from_html(&html, config).with_fetcher(EmbeddedScriptFetcher); + let config = DocumentConfig { base_url: Some(url.into()), ..DocumentConfig::default() }; + let mut document = EkojitDocument::from_html(Arc::from(html), config, NativePageDefect::None).map_err(|error| error.to_string())?; + let _ = document.set_initial_script_budget(std::time::Duration::from_secs(60)); + let prelude = r#" + globalThis.setInterval = globalThis.setInterval || ((callback, delay, ...args) => { + const run = () => { callback(...args); timer = setTimeout(run, delay); }; + let timer = setTimeout(run, delay); return timer; + }); + globalThis.clearInterval = globalThis.clearInterval || globalThis.clearTimeout; + globalThis.requestIdleCallback = globalThis.requestIdleCallback || (callback => setTimeout(() => callback({didTimeout:false,timeRemaining:()=>0}), 1)); + globalThis.cancelIdleCallback = globalThis.cancelIdleCallback || globalThis.clearTimeout; + globalThis.ResizeObserver = globalThis.ResizeObserver || class { observe() {} unobserve() {} disconnect() {} }; + globalThis.IntersectionObserver = globalThis.IntersectionObserver || class { observe() {} unobserve() {} disconnect() {} takeRecords() { return []; } }; + globalThis.PerformanceObserver = globalThis.PerformanceObserver || class { observe() {} disconnect() {} takeRecords() { return []; } }; + globalThis.performance = globalThis.performance || (() => { const t0 = Date.now(); return { timeOrigin: t0, now: () => Date.now() - t0, mark: () => {}, measure: () => {}, getEntries: () => [], getEntriesByType: () => [], getEntriesByName: () => [], clearMarks: () => {}, clearMeasures: () => {} }; })(); + globalThis.CSS = globalThis.CSS || {}; globalThis.CSS.supports = globalThis.CSS.supports || (() => false); + globalThis.btoa = globalThis.btoa || (value => globalThis.Buffer ? Buffer.from(value, 'binary').toString('base64') : ''); + globalThis.atob = globalThis.atob || (value => globalThis.Buffer ? Buffer.from(value, 'base64').toString('binary') : ''); + globalThis.encodeURIComponent = globalThis.encodeURIComponent || encodeURI; + globalThis.decodeURIComponent = globalThis.decodeURIComponent || decodeURI; + globalThis.encodeURI = globalThis.encodeURI || (value => String(value)); + globalThis.decodeURI = globalThis.decodeURI || (value => String(value)); + "#; + let _ = document.eval_source(Arc::new(PageSource { + text: Arc::from(prelude), + url: Arc::from("preview:compatibility"), + })); + document.set_script_fetcher(EmbeddedScriptFetcher); trace("document parsing completed"); - Ok(document) + Ok(PreviewBlitzDocument { document, poll_hooks: Vec::new() }) } #[cfg(not(test))] -fn create_dist_document(dist: &std::path::Path, url: &str) -> Result { +fn create_dist_document(dist: &std::path::Path, url: &str) -> Result { fn asset_url<'a>(html: &'a str, attribute: &str) -> Result<&'a str, String> { let marker = format!("{attribute}=\""); let start = html @@ -181,12 +347,10 @@ fn create_dist_document(dist: &std::path::Path, url: &str) -> Result { let dist = std::path::PathBuf::from(dist); trace(&format!("preview dist: {}", dist.display())); - set_document_factory(move |url| create_dist_document(&dist, url)); + set_document_factory(move |url| create_dist_document(&dist, url).map(|doc| izumo::ApplicationDocument::new(Box::new(doc), Arc::new(PreviewDocumentHost)))); } - None => set_document_factory(create_document), + None => set_document_factory(|url| create_document(url).map(|doc| izumo::ApplicationDocument::new(Box::new(doc), Arc::new(PreviewDocumentHost)))), } #[cfg(test)] - set_document_factory(create_document); + set_document_factory(|url| create_document(url).map(|doc| izumo::ApplicationDocument::new(Box::new(doc), Arc::new(PreviewDocumentHost)))); trace("document factory configured"); let context = tauri::generate_context!("tauri.conf.json"); @@ -593,6 +757,11 @@ mod tests { document.eval("void 0"); document.poll(None); } + assert!( + document.document.runtime_errors().is_empty(), + "production workspace emitted runtime errors: {:?}", + document.document.runtime_errors() + ); document.inner_mut().resolve(0.0); let doc = document.inner(); diff --git a/apps/gui/Cargo.toml b/apps/gui/Cargo.toml index 9aa6a9ec..344b6ccd 100644 --- a/apps/gui/Cargo.toml +++ b/apps/gui/Cargo.toml @@ -26,6 +26,8 @@ blitz-runtime = [ "dep:blitz-control-protocol", "dep:blitz-dom", "dep:blitz-script", + "dep:blitz-script-ekojit", + "dep:blitz-traits", "dep:brotli", "dep:izumo", "dep:url", @@ -53,6 +55,8 @@ blitz-inspector = [ # on crates.io. chuzz never hit either, because it does not enable this. "blitz-dom/log-phase-times", "izumo/diagnostics", + "blitz-script-ekojit/system-fonts", + "blitz-script-ekojit/debug-control", ] # The lighter render pipeline, for measuring against the default Vello one. blitz-hybrid = ["blitz-inspector", "izumo/hybrid-renderer"] @@ -109,8 +113,8 @@ tauri = { version = "2", default-features = false, features = ["macos-private-ap # 0.1.0 the runtime's own feature forwards to `tauri` and `tauri-runtime`, so # naming it here agrees with that rather than being the only thing holding the # two sides together. -izumo = { version = "^0.4", optional = true, features = ["macos-private-api"] } -blitz-control-protocol = { version = "^0.5", optional = true } +izumo = { version = "^0.6.5", optional = true, features = ["macos-private-api"] } +blitz-control-protocol = { version = "^0.7.2", optional = true } # # The engine by version, not by branch. Same move `chuzz` made, for the same # reasons its manifest records. @@ -129,8 +133,10 @@ blitz-control-protocol = { version = "^0.5", optional = true } # that reads as `expected ScriptDocument, found ScriptDocument` with both types # naming one file. Local renderer work uses `.cargo/local-renderer.toml` through # `scripts/local-renderer.sh`, so the default exercises the published graph. -blitz-dom = { package = "ps-blitz-dom", version = "^0.4", features = ["system-fonts", "parallel-construct"], optional = true } -blitz-script = { package = "ps-blitz-script", version = "^0.4", features = ["system-fonts"], optional = true } +blitz-dom = { package = "ps-blitz-dom", version = "^0.6.5", features = ["system-fonts", "parallel-construct"], optional = true } +blitz-script = { package = "ps-blitz-script", version = "^0.6.5", features = ["system-fonts"], optional = true } +blitz-script-ekojit = { package = "ps-blitz-script-ekojit", version = "^0.1.0", path = "../../../ekojit/crates/blitz-script-ekojit", optional = true } +blitz-traits = { package = "ps-blitz-traits", version = "^0.6.5", optional = true } brotli = { version = "8.0.4", default-features = false, features = ["std"], optional = true } url = { version = "2.5.8", optional = true } tauri-plugin-updater = "2" diff --git a/apps/gui/src/main.rs b/apps/gui/src/main.rs index f962a072..14d6b09d 100644 --- a/apps/gui/src/main.rs +++ b/apps/gui/src/main.rs @@ -181,15 +181,305 @@ fn decompress_blitz_asset( } #[cfg(feature = "blitz-runtime")] -fn create_blitz_document(url: &str) -> Result { +struct AgencyBlitzDocument { + document: blitz_script_ekojit::EkojitDocument, + poll_hooks: Vec, +} + +#[cfg(feature = "blitz-runtime")] +impl AgencyBlitzDocument { + fn run_poll_hooks(&mut self, context: Option<&std::task::Context<'_>>) -> bool { + let mut hooks = std::mem::take(&mut self.poll_hooks); + let mut work = false; + for hook in &mut hooks { + work |= hook(self, context); + } + hooks.append(&mut self.poll_hooks); + self.poll_hooks = hooks; + work + } +} + +#[cfg(feature = "blitz-runtime")] +impl blitz_dom::Document for AgencyBlitzDocument { + fn inner(&self) -> blitz_dom::DocGuard<'_> { + blitz_dom::Document::inner(&self.document) + } + + fn inner_mut(&mut self) -> blitz_dom::DocGuardMut<'_> { + blitz_dom::Document::inner_mut(&mut self.document) + } + + fn handle_ui_event(&mut self, event: blitz_traits::events::UiEvent) { + blitz_dom::Document::handle_ui_event(&mut self.document, event) + } + + fn poll(&mut self, context: Option>) -> bool { + let mut work = blitz_dom::Document::poll(&mut self.document, context.as_ref().map(|cx| { + std::task::Context::from_waker(cx.waker()) + })); + work |= self.run_poll_hooks(context.as_ref()); + work + } + + fn poll_for_settle( + &mut self, + context: Option>, + run_timers: bool, + ) -> bool { + let mut work = blitz_dom::Document::poll_for_settle( + &mut self.document, + context.as_ref().map(|cx| std::task::Context::from_waker(cx.waker())), + run_timers, + ); + work |= self.run_poll_hooks(context.as_ref()); + work + } + + fn prepare_teardown(&mut self) { + blitz_dom::Document::prepare_teardown(&mut self.document) + } + + fn dispose(self: Box) -> Arc { + let Self { document, .. } = *self; + blitz_dom::Document::dispose(Box::new(document)) + } + + fn set_page_visible(&mut self, visible: bool) { + blitz_dom::Document::set_page_visible(&mut self.document, visible) + } + + fn freeze(&mut self) { + blitz_dom::Document::freeze(&mut self.document) + } + + fn finish_restore(&mut self) { + blitz_dom::Document::finish_restore(&mut self.document) + } + + fn resume(&mut self) { + blitz_dom::Document::resume(&mut self.document) + } +} + +#[cfg(all(feature = "blitz-runtime", feature = "blitz-inspector", unix))] +impl blitz_control_protocol::ControlScriptBackend for AgencyBlitzDocument { + fn dispatch_dom_event(&mut self, event: blitz_traits::events::DomEvent) { + self.document.handle_dom_event(event); + } + + fn handle_pointer_move_to_node( + &mut self, + event: blitz_traits::events::BlitzPointerEvent, + node: blitz_dom::NodeId, + ) { + self.document.handle_pointer_move_to_node(event, node); + } + + fn handle_ui_event_to_node( + &mut self, + event: blitz_traits::events::UiEvent, + node: blitz_dom::NodeId, + ) { + self.document.handle_ui_event_to_node(event, node); + } +} + +#[cfg(feature = "blitz-runtime")] +struct AgencyDocumentHost; + +#[cfg(feature = "blitz-runtime")] +fn agency_document(document: &dyn blitz_dom::Document) -> Option<&AgencyBlitzDocument> { + (document as &dyn std::any::Any).downcast_ref() +} + +#[cfg(feature = "blitz-runtime")] +fn agency_document_mut(document: &mut dyn blitz_dom::Document) -> Option<&mut AgencyBlitzDocument> { + (document as &mut dyn std::any::Any).downcast_mut() +} + +#[cfg(feature = "blitz-runtime")] +impl izumo::DocumentHost for AgencyDocumentHost { + fn current_url(&self, document: &dyn blitz_dom::Document) -> Option { + Some(blitz_dom::Document::inner(agency_document(document)?).url().clone()) + } + + fn eval(&self, document: &mut dyn blitz_dom::Document, source: &str) { + if let Some(doc) = agency_document_mut(document) { + let _ = doc.document.eval_source(Arc::new(blitz_script_ekojit::PageSource { + text: Arc::from(source), + url: Arc::from("agencyzero:eval"), + })); + } + } + + fn eval_json( + &self, + document: &mut dyn blitz_dom::Document, + source: &str, + ) -> Result { + agency_document_mut(document) + .ok_or_else(|| String::from("document is not owned by AgencyZero"))? + .document + .with_embedder_host(|host| host.eval_json(source)) + } + + fn set_ipc_handler( + &self, + document: &mut dyn blitz_dom::Document, + handler: Box, + ) { + struct IpcHandler(Box); + fn ipc_post_message( + realm: &mut blitz_script_ekojit::embedder::RealmHost<'_>, + args: &[blitz_script_ekojit::embedder::HostValue], + ) -> Result< + blitz_script_ekojit::embedder::HostValue, + blitz_script_ekojit::embedder::NativeFailure, + > { + if let Some(handler) = realm.state::("agencyzero.ipc") + && let Some(blitz_script_ekojit::embedder::HostValue::Utf16(units)) = args.first() + { + (handler.0)(String::from_utf16_lossy(units)); + } + Ok(blitz_script_ekojit::embedder::HostValue::Undefined) + } + if let Some(doc) = agency_document_mut(document) { + let _ = doc.document.with_realm_host(|realm| { + realm.set_state("agencyzero.ipc", std::rc::Rc::new(IpcHandler(handler)))?; + realm.register_intrinsic("__azIpcPostMessage", 1, ipc_post_message) + }); + let _ = doc.document.eval_source(Arc::new(blitz_script_ekojit::PageSource { + text: Arc::from( + "globalThis.ipc = { postMessage: function(msg) { __azIpcPostMessage(String(msg)); } };", + ), + url: Arc::from("agencyzero:ipc-install"), + })); + } + } + + fn add_poll_hook(&self, document: &mut dyn blitz_dom::Document, hook: izumo::DocumentPollHook) { + if let Some(doc) = agency_document_mut(document) { + doc.poll_hooks.push(hook); + } + } + + #[cfg(feature = "blitz-inspector")] + fn service_debug_controller( + &self, + _document: &mut dyn blitz_dom::Document, + _controller: &mut blitz_script::DebugController, + _animation_time: f64, + ) -> bool { + false + } + + #[cfg(all(feature = "blitz-inspector", unix))] + fn agent( + &self, + document: &mut dyn blitz_dom::Document, + control: &mut blitz_control_protocol::in_process::DocumentControl, + request: blitz_control_protocol::AgentControlRequest, + ) -> blitz_control_protocol::DebugResponse { + match agency_document_mut(document) { + Some(doc) => control.agent(doc, request), + None => blitz_control_protocol::DebugResponse::Error(blitz_control_protocol::DebugError { + code: "unsupportedDocument".into(), + message: "document is not owned by AgencyZero".into(), + }), + } + } + + #[cfg(all(feature = "blitz-inspector", unix))] + fn diagnostics( + &self, + _document: &mut dyn blitz_dom::Document, + _control: &mut blitz_control_protocol::in_process::DocumentControl, + _request: blitz_control_protocol::DiagnosticsRequest, + ) -> blitz_control_protocol::DebugResponse { + blitz_control_protocol::DebugResponse::Error(blitz_control_protocol::DebugError { + code: "unsupportedRequest".into(), + message: "AgencyZero's native page host does not implement diagnostics requests".into(), + }) + } + + #[cfg(all(feature = "blitz-inspector", unix))] + fn diagnostic_batch( + &self, + document: &dyn blitz_dom::Document, + console_after: u64, + errors_after: u64, + limit: usize, + ) -> blitz_script::DiagnosticBatch { + let empty = |next_sequence| blitz_script::DiagnosticStreamBatch { + entries: Vec::new(), + lost: 0, + next_sequence, + }; + let Some(doc) = agency_document(document) else { + return blitz_script::DiagnosticBatch { + console: empty(console_after), + errors: empty(errors_after), + }; + }; + let stream = |entries: Vec, after| { + let entries = entries.into_iter() + .filter(|entry| entry.sequence > after) + .take(limit.clamp(1, 1000)) + .collect::>(); + let next_sequence = entries.last().map_or(after, |entry| entry.sequence); + blitz_script::DiagnosticStreamBatch { entries, lost: 0, next_sequence } + }; + blitz_script::DiagnosticBatch { + console: stream(doc.document.console_entries(), console_after), + errors: stream(doc.document.runtime_errors(), errors_after), + } + } +} + +#[cfg(feature = "blitz-runtime")] +fn create_blitz_document(url: &str) -> Result { let css = decompress_blitz_asset(BLITZ_CSS_BROTLI, BLITZ_CSS_LEN, "CSS")?; let html = BLITZ_SHELL_HTML.replacen(BLITZ_CSS_MARKER, &css, 1); let config = blitz_dom::DocumentConfig { base_url: Some(url.into()), ..Default::default() }; - Ok(blitz_script::ScriptDocument::from_html(&html, config) - .with_fetcher(EmbeddedBlitzScriptFetcher)) + let mut document = blitz_script_ekojit::EkojitDocument::from_html( + Arc::from(html), + config, + blitz_script_ekojit::NativePageDefect::None, + ).map_err(|error| error.to_string())?; + let _ = document.set_initial_script_budget(std::time::Duration::from_secs(60)); + let prelude = r#" + globalThis.setInterval = globalThis.setInterval || ((callback, delay, ...args) => { + const run = () => { callback(...args); timer = setTimeout(run, delay); }; + let timer = setTimeout(run, delay); return timer; + }); + globalThis.clearInterval = globalThis.clearInterval || globalThis.clearTimeout; + globalThis.requestIdleCallback = globalThis.requestIdleCallback || (callback => setTimeout(() => callback({didTimeout:false,timeRemaining:()=>0}), 1)); + globalThis.cancelIdleCallback = globalThis.cancelIdleCallback || globalThis.clearTimeout; + globalThis.ResizeObserver = globalThis.ResizeObserver || class { observe() {} unobserve() {} disconnect() {} }; + globalThis.IntersectionObserver = globalThis.IntersectionObserver || class { observe() {} unobserve() {} disconnect() {} takeRecords() { return []; } }; + globalThis.PerformanceObserver = globalThis.PerformanceObserver || class { observe() {} disconnect() {} takeRecords() { return []; } }; + globalThis.performance = globalThis.performance || (() => { const t0 = Date.now(); return { timeOrigin: t0, now: () => Date.now() - t0, mark: () => {}, measure: () => {}, getEntries: () => [], getEntriesByType: () => [], getEntriesByName: () => [], clearMarks: () => {}, clearMeasures: () => {} }; })(); + globalThis.CSS = globalThis.CSS || {}; globalThis.CSS.supports = globalThis.CSS.supports || (() => false); + globalThis.btoa = globalThis.btoa || (value => globalThis.Buffer ? Buffer.from(value, 'binary').toString('base64') : ''); + globalThis.atob = globalThis.atob || (value => globalThis.Buffer ? Buffer.from(value, 'base64').toString('binary') : ''); + globalThis.encodeURIComponent = globalThis.encodeURIComponent || encodeURI; + globalThis.decodeURIComponent = globalThis.decodeURIComponent || decodeURI; + globalThis.encodeURI = globalThis.encodeURI || (value => String(value)); + globalThis.decodeURI = globalThis.decodeURI || (value => String(value)); + "#; + let _ = document.eval_source(Arc::new(blitz_script_ekojit::PageSource { + text: Arc::from(prelude), + url: Arc::from("agencyzero:compatibility"), + })); + document.set_script_fetcher(EmbeddedBlitzScriptFetcher); + Ok(izumo::ApplicationDocument::new( + Box::new(AgencyBlitzDocument { document, poll_hooks: Vec::new() }), + Arc::new(AgencyDocumentHost), + )) } /// Commands this build actually implements. @@ -1002,7 +1292,7 @@ const BUILD: BuildInfo = BuildInfo { /// that decide whether a rendering fix is present, so they go in the log where /// they are read without asking the app anything. fn resolved_highlights() -> String { - let wanted = ["ps-blitz-script", "ps-boa-engine", "izumo", "@pathscale/ui"]; + let wanted = ["ps-blitz-script", "ps-blitz-script-ekojit", "izumo", "@pathscale/ui"]; // `cargo tree` marks a crate it has already expanded with a trailing // `(*)`, so every package appears twice. Same version, no extra // information, and it makes the line read as though the graph were diff --git a/docs/plans/native-ekojit-integration.md b/docs/plans/native-ekojit-integration.md new file mode 100644 index 00000000..6db5510e --- /dev/null +++ b/docs/plans/native-ekojit-integration.md @@ -0,0 +1,48 @@ +# Native Ekojit integration requirements + +This records the integration boundary represented by the current GUI and +preview changes. It is a source review, not runtime acceptance. + +## Required wiring + +- Resolve `ps-blitz-script-ekojit` alongside the matching Blitz and Izumo + release line. Do not introduce duplicate renderer or script trait identities. +- Keep the application's `Document` adapter responsible for forwarding DOM + access, UI events, polling, settling, visibility, lifecycle, and teardown to + the native document. +- Preserve the host bridge for evaluation, JSON evaluation, IPC, current URL, + and poll hooks. Keep callbacks attached to the document that owns their + runtime state. +- Keep the deterministic preview's embedded asset fetcher and capture path + independent from the application's production asset loading. +- Declare Ekojit as a non-optional preview dependency while preview source + constructs its document unconditionally. The application may keep the + dependency optional because its `blitz-runtime` feature gates the integration. + +## Public dependency gate + +The current working-tree manifests resolve the native backend through a sibling +checkout. That package is not published, so a public clone cannot resolve the +dependency. This integration is preserved locally for review, but it is not +ready for a public PR until the dependency is available through a public source +and the manifest no longer relies on a repository-relative sibling path. + +## Remaining integration work + +- The GUI and preview host adapters currently return `unsupportedRequest` for + the diagnostics request surface. Their diagnostic batch methods expose only + the runtime's console and error entries, without lost-entry accounting. +- Both adapters currently return `false` from debug-controller servicing. + Confirm which control and diagnostics behaviors the consumer needs before + claiming full inspector parity. +- Review error propagation from runtime setup and IPC registration. Current + adapters intentionally discard some setup/evaluation results, so failures + may not reach the caller. +- Validate the actual supported feature combinations and the native GUI and + preview paths when runtime verification is authorized. + +## Exclusions + +Do not add statistical lexical identity, proxy learning, or benchmark-specific +behavior to this integration. Do not claim runtime acceptance from source +inspection alone. diff --git a/scripts/owner-build.sh b/scripts/owner-build.sh index 7d8c1a64..2d007134 100755 --- a/scripts/owner-build.sh +++ b/scripts/owner-build.sh @@ -80,7 +80,7 @@ if grep -q '^\[patch\.crates-io\]' Cargo.toml; then grep -A6 '^\[patch\.crates-io\]' Cargo.toml | sed 's/^/ /' fi -for crate in ps-blitz-script ps-boa-engine izumo; do +for crate in ps-blitz-script ps-blitz-script-ekojit izumo; do line="$(cargo tree -i "$crate" --depth 0 2>/dev/null | grep -v '^warning' | head -1 || true)" [ -n "$line" ] || fail "$crate is not in the dependency graph" printf ' %s\n' "$line" From 7cb6d2cb01c2c31f1545d7fcb46a4514407fe66a Mon Sep 17 00:00:00 2001 From: meh Date: Thu, 5 Nov 2026 21:26:41 +0700 Subject: [PATCH 3/4] Update project source --- Cargo.toml | 2 +- apps/gui/src/main.rs | 18 +++++++++++ apps/gui/src/projects.rs | 65 +++++++++++++++++++++------------------- 3 files changed, 53 insertions(+), 32 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 2459f9ca..34770321 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ members = [ exclude = ["crates/wt-migrate/v2-reader"] [workspace.package] -version = "0.8.68" +version = "0.8.69" edition = "2024" publish = false diff --git a/apps/gui/src/main.rs b/apps/gui/src/main.rs index 14d6b09d..defc14c4 100644 --- a/apps/gui/src/main.rs +++ b/apps/gui/src/main.rs @@ -1993,6 +1993,24 @@ async fn set_settings( patch: serde_json::Value, state: State<'_, AppState>, ) -> Result { + let object = patch + .as_object() + .ok_or_else(|| "settings patch must be an object".to_string())?; + const PROTECTED: &[&str] = &[ + "agentProxyBinary", + "defaultPermission", + "envPolicy", + "forwardProxyVars", + "blitzControlEnabled", + "agent_proxy_binary", + "default_permission", + "env_policy", + "forward_proxy_vars", + "blitz_control_enabled", + ]; + if object.keys().any(|key| PROTECTED.contains(&key.as_str())) { + return Err("security settings require a native owner-authorized path".to_string()); + } apply_settings_patch(patch, &state).await } diff --git a/apps/gui/src/projects.rs b/apps/gui/src/projects.rs index 82b4368e..343eee98 100644 --- a/apps/gui/src/projects.rs +++ b/apps/gui/src/projects.rs @@ -6239,33 +6239,8 @@ fn approval_signature(tool: &str, input: &serde_json::Value) -> String { }; if tool.eq_ignore_ascii_case("bash") { - // Sign on the real command, not the shell wrapper. Codex runs every - // command as `/bin/zsh -c ""`, so signing on the raw first word - // made it always `/bin/zsh`: one remembered "always allow" grant then - // matched *every* later command, including git push and git commit, and - // the owner was never prompted again. Unwrap the `-c` payload first, and - // tokenize with a real shell word-splitter (`shlex`) rather than - // whitespace, so a quoted argument does not split into a wrong word. - let raw = text("command"); - let words = shlex::split(raw) - .unwrap_or_else(|| raw.split_whitespace().map(str::to_string).collect()); - let words = unwrap_shell_words(words); - let program = words.first().map(String::as_str).unwrap_or(""); - let subcommand = words - .get(1) - .map(String::as_str) - .filter(|word| { - !word.starts_with('-') - && word - .chars() - .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') - }) - .unwrap_or(""); - return if subcommand.is_empty() { - format!("{tool}: {program}") - } else { - format!("{tool}: {program} {subcommand}") - }; + // Shell approval must remain per request until a grammar-aware matcher exists. + return String::new(); } if tool.eq_ignore_ascii_case("permissions") { @@ -7853,7 +7828,7 @@ pub async fn resolve_approval( * Only an *allow* is ever remembered — a remembered denial would turn * one misclick into a run that can never do its job again, silently. */ - if allow && remember == Some(true) { + if allow && remember == Some(true) && !ask.signature.is_empty() { let rules = load_rules(&state.tables, &project_id); // Uniqueness is the writer's job; the single writer makes that safe. if !rules.iter().any(|rule| rule == &ask.signature) { @@ -11489,6 +11464,28 @@ pub async fn review_pull_request( url: String, agent: String, ) -> Result<(), String> { + let path = url + .strip_prefix("https://github.com/") + .ok_or_else(|| "review URL must be an HTTPS GitHub pull request".to_string())?; + let parts: Vec<&str> = path.split('/').collect(); + let valid_name = |value: &str| { + !value.is_empty() + && value != "." + && value != ".." + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.')) + }; + if parts.len() != 4 + || !valid_name(parts[0]) + || !valid_name(parts[1]) + || parts[2] != "pull" + || parts[3].is_empty() + || !parts[3].bytes().all(|byte| byte.is_ascii_digit()) + || !parts[3].parse::().is_ok_and(|number| number > 0) + { + return Err("review URL must name one GitHub pull request".to_string()); + } let agent = parse_review_agent(Some(&agent))?; let settings = state .tables @@ -12843,7 +12840,7 @@ async fn drive_run( * here — audited in the I/O panel, never silently. */ let signature = approval_signature(&approval.tool, &approval.input); - let by_rule = load_rules(&tables, &project_id) + let by_rule = !signature.is_empty() && load_rules(&tables, &project_id) .iter() .any(|rule| rule == &signature); // Auto answers its own questions. The channel is open precisely @@ -13105,7 +13102,10 @@ async fn drive_run( */ if ping_outstanding && matches!( - authored_directive_line(&line, &mut directive_state.fenced) + authored_directive_line( + &line, + &mut FenceState(directive_state.fenced.0), + ) .and_then(crate::directives::parse_authored), Some(crate::directives::Authored::Directive( crate::directives::Directive::Pong @@ -13144,7 +13144,10 @@ async fn drive_run( */ if let Some(crate::directives::Authored::Directive( crate::directives::Directive::ExtendWatchdog { what, seconds }, - )) = authored_directive_line(&line, &mut directive_state.fenced) + )) = authored_directive_line( + &line, + &mut FenceState(directive_state.fenced.0), + ) .and_then(crate::directives::parse_authored) { let granted = seconds From 8ff14fd281205b5d94cacaaa66b6ac08552e6123 Mon Sep 17 00:00:00 2001 From: meh Date: Sun, 4 Oct 2026 17:27:37 +0700 Subject: [PATCH 4/4] Update project source --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 34770321..045fc37f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,7 @@ agency-proxy-protocol = "^0.1.11" # The GUI and both storage tools compile the same schema against one resolved # WorkTable package. A workspace dependency prevents their compatible ranges # from drifting into separate copies without freezing the selected patch. -worktable = "1.10.0-beta1" +worktable = "^1.11.0" # Heavy deps are declared per-crate on purpose: only apps/gui pulls in the # Tauri stack, so agent/proxy builds never trigger a webview toolchain build.