Skip to content

API brotli, cache validators, bfcache-friendly index and hub gating (B22, D8, I5, J5, B17) - #1889

Merged
SawyerHood merged 8 commits into
bb/mobile-perf/timeline-delta-ring-and-output-capfrom
bb/mobile-perf/http-caching-and-hub-gating
Aug 19, 2026
Merged

SawyerHood merged 8 commits into
bb/mobile-perf/timeline-delta-ring-and-output-capfrom
bb/mobile-perf/http-caching-and-hub-gating

Conversation

@SawyerHood

@SawyerHood SawyerHood commented Aug 19, 2026 •

Copy link
Copy Markdown
Collaborator

What was wrong

  • API JSON was gzip-only through hono/compress. It never set Vary and its 1 KB threshold did not apply because Hono JSON has no Content-Length, so every body streamed through gzip. Brotli saves 10-20% on the timeline and sidebar payloads a phone downloads per turn.
  • Attachment content had no cache headers although stored names are immutable. Host-file responses ignored the sha256/mtime the daemon returns. iOS purges the memory cache on backgrounding, so PWA relaunches re-downloaded multi-megabyte screenshots. The SDK also copied every upload through arrayBuffer() and the composer preview re-downloaded the image it had just uploaded.
  • index.html and all public icons/manifests were served no-store. no-store blocks the WebKit back/forward cache, and icons were refetched on every favicon flip and never edge-cached. The favicon code re-decoded both PNGs on every badge flip, even in an installed PWA where no tab icon exists.
  • The plugin-frontend pagehide handler tore everything down even for a bfcache freeze and had no pageshow reboot.
  • Every thread-list subscriber received every thread's raw events-appended stream (~10 frames/s per streaming thread) and ran cache walks for threads it was not viewing.

What changed

  • New apps/server/src/api-response-compression.ts buffers core /api/v1 JSON (not plugin bb.http handlers, not /internal streaming) and sends Brotli q4 or gzip with exact Content-Length and Vary: Accept-Encoding; sub-1 KB bodies stay identity. It runs inside the existing streaming gzip fallback.
  • Attachment content: private, immutable, max-age=31536000 + ETag + Content-Length + 304. Daemon file responses: ETag (sha256), Last-Modified, Content-Length, default private, no-cache, 304 on If-None-Match; content routes pass If-None-Match through. SDK passes Blob/File to FormData directly. Composer keeps an object URL for a just-picked image (revoked on remove). Images use decoding="async".
  • index.html: no-cache. Non-HTML public files: public, max-age=86400. Favicon base glyphs memoized; favicon work skipped in standalone display mode.
  • Plugin frontends tear down only on a non-persisted pagehide; a persisted pageshow reconciles or reboots.
  • Hub: thread-detail subscribers get every events-appended frame; thread-list-only sockets get the first frame at once and one merged frame per 1 s window per thread. Frames with list-relevant metadata or other change kinds bypass coalescing.

How you verified

  • New tests: apps/server/test/app/api-json-compression.test.ts (br + Content-Length + Vary, gzip fallback and q=0, identity below threshold, plugin/internal paths not buffered, real /api/v1/system/config); apps/server/test/hosts/daemon-file-response.test.ts (validators, caller headers kept, 304, If-None-Match matching); apps/server/test/app/hub.test.ts (detail vs list-only fan-out, trailing merged frame, bypass rules, per-thread windows, waiters and listeners); apps/app/src/components/promptbox/AttachmentPreview.test.tsx (object-URL src, fallback URL, decoding=async, revoke on remove); apps/app/src/lib/favicon-color-preference.test.ts (one decode per glyph, standalone skip); apps/app/src/lib/plugin-frontend.test.ts (page lifecycle policy).
  • Updated tests: static-cache.test.ts (no-cache index, max-age=86400 icons/manifest), public-project-attachments.test.ts (cache headers, ETag, 304).
  • pnpm exec turbo run typecheck --filter=@bb/app --filter=@bb/sdk --filter=@bb/server: pass. lint: 0 errors. Full @bb/server and @bb/sdk suites: all pass except a pre-existing umask-dependent internal-skill-trees test that also fails on baseline.

Fixes: part of the mobile / iOS Safari performance program (verified sweep report in the bb thread; no single issue).

Stack context

Layer 10 of 22 in the bb/mobile-perf/* stack (bottom → top: quick wins first, big rocks last).

  • Prerequisite (layer below): bb/mobile-perf/timeline-delta-ring-and-output-cap (Timeline delta snapshot ring and pending-turn tool output preview cap (B19, B20) #1888).
  • Next layer: bb/mobile-perf/boot-shell-quickwins (Boot payload quick wins: SDK guide, font preload, dark pre-paint, route preload + skeleton (A6, A8, A10, A13, A15, J1) #1890).
  • Audit findings addressed: see title IDs. Review: approved-with-fixes; 2 review fix commit(s).
  • Reviewer notes / follow-ups: Minor (not fixed, by design/bounded): apps/app/src/lib/attachment-local-previews.ts keeps up to 24 object URLs (and thus the picked File/Blob) alive after a draft is sent; only rem | Behavioral note (documented by implementer): SDK/plugin thread:changed subscribers without a threadId (thread-list channel) now receive plain events-appended at leading edge + on | Pre-existing, unrelated: apps/server/src/server.ts fails the root eslint no-restricted-imports rule for node:fs/promises (present at base dde6cdd; @bb/server has no lint task s
  • Wire/contract: None on the server<->daemon wire (HOST_DAEMON_PROTOCOL_VERSION not bumped): daemon-file-response only consumes fields the daemon already returns (sha256, modifiedAtMs). Client-facing HTTP: API JSON may now be Content-Encoding: br with Content-Length + Vary; attachment content and host-file routes gain ETag/Last-Modified/Cache-Control/Content-Length and can answer 304; index.html no-cache; public f

AGENT GENERATED: by Claude Opus 5

@SawyerHood SawyerHood changed the title bb/mobile perf/http caching and hub gating API brotli, cache validators, bfcache-friendly index and hub gating (B22, D8, I5, J5, B17) Aug 19, 2026
@SawyerHood
SawyerHood force-pushed the bb/mobile-perf/http-caching-and-hub-gating branch from f2b3c18 to ecaa176 Compare August 19, 2026 07:42
@SawyerHood
SawyerHood force-pushed the bb/mobile-perf/http-caching-and-hub-gating branch from ecaa176 to 38a73f7 Compare August 19, 2026 07:50
@SawyerHood
SawyerHood marked this pull request as ready for review August 19, 2026 08:04
@SawyerHood
SawyerHood force-pushed the bb/mobile-perf/http-caching-and-hub-gating branch from 38a73f7 to d87ac63 Compare August 19, 2026 15:59
SawyerHood and others added 8 commits August 19, 2026 16:03
hono/compress only ever picked gzip, never set Vary, and its 1 KB
threshold was ineffective because Hono JSON responses carry no
Content-Length, so every API body was streamed through gzip regardless
of size. Timeline and sidebar payloads are the largest bytes a phone
downloads per turn and Brotli saves 10-20% on them.

Add a small middleware that buffers core /api/v1 JSON (not plugin
bb.http handlers, not /internal streaming tool calls), ranks the
client's Accept-Encoding with rankAcceptedAssetEncodings (q=0 honoured),
encodes with Brotli q4 or gzip, and sets Content-Encoding, an exact
Content-Length and Vary: Accept-Encoding. Sub-threshold bodies stay
identity with a Content-Length. It runs inside the existing streaming
gzip fallback, which then only touches what it leaves untransformed.

Co-Authored-By: Claude <[email protected]>
index.html was served with Cache-Control: no-store, which forbids the
WebKit back/forward cache over HTTPS, so every back navigation on iOS
Safari reloaded the whole SPA. Icons and manifests under public/ also
went out no-store, so favicon badge flips and PWA relaunches refetched
the PNGs and the connect edge could never cache them.

The document now goes out no-cache: it is still revalidated on every
navigation (a new build is picked up at once) but the page may be kept
in bfcache. Non-HTML public files get public, max-age=86400. Hashed
/assets keep the immutable year.

Co-Authored-By: Claude <[email protected]>
Stored attachment names are `${stem}-${Date.now()}-${rand}` so the
bytes behind a name never change, yet the content route sent only a
content-type. Host-file responses ignored the sha256/modifiedAtMs the
daemon already returns. iOS purges the memory cache on backgrounding,
so PWA relaunches and timeline scroll-back re-downloaded multi-megabyte
screenshots and decoded 12 MP originals for 96x64 thumbnails.

Server: attachment content now carries Cache-Control: private,
immutable, max-age=31536000, an ETag and Content-Length, and answers
If-None-Match with 304. Daemon file responses carry ETag (sha256),
Last-Modified (when the daemon has an mtime), Content-Length and a
default Cache-Control: private, no-cache so browsers store and
revalidate; the content routes pass If-None-Match through for a 304.

Client: the SDK streams a Blob/File straight into the multipart form
instead of copying it through arrayBuffer(); the composer keeps an
object URL for a just-picked image so the preview does not re-download
the original it just uploaded (revoked on remove, bounded FIFO); and
timeline/composer images decode asynchronously.

Co-Authored-By: Claude <[email protected]>
Every unread-badge or tint flip re-fetched and re-decoded both favicon
PNGs before redrawing on a canvas, and an installed PWA (which has no
tab strip) still did all of that work.

Cache the decoded base image per href for the page's lifetime and
return early from the favicon render when the display mode is
standalone.

Co-Authored-By: Claude <[email protected]>
The one-shot pagehide listener tore down every plugin frontend even
when the page was only entering the back/forward cache, so a bfcache
restore came back with no plugin UI and no way to boot again.

Tear down only when pagehide is not persisted. On a persisted pageshow,
reconcile the still-mounted frontends, or reboot (reset tornDown and
bootPromise) if a teardown did happen.

Co-Authored-By: Claude <[email protected]>
Every open app window holds one thread-list subscription and received
every thread's raw events-appended stream (~10 frames/s per streaming
thread), each of which the client parses and turns into timeline/search
cache walks for threads it is not viewing.

The hub now delivers plain events-appended to thread-detail
subscribers unchanged, and to sockets that only hold the thread-list
subscription on a leading-edge-plus-1 s coalesced cadence per thread
(merged frames carry the union of event types). Frames whose metadata
the list path reads directly (backgroundActivityChanged,
hasPendingInteraction, projectId, turn/completed,
client/turn/requested) or that carry any other change kind still go out
immediately. Server-side listeners and thread event waiters see every
frame as before.

Co-Authored-By: Claude <[email protected]>
…sion

Hono's `/plugins/:id/http/*` route also answers `/plugins/:id/http`, but the
buffered-compression exclusion only skipped paths with a trailing slash, so
a plugin streaming JSON from its root path would have been fully buffered.
Mirror PLUGIN_WIRE_HTTP_PATH's `(?:/|$)` and cover it in the test.

Co-Authored-By: Claude <[email protected]>
The unit test proved createDaemonFileContentResponse honours If-None-Match,
but nothing checked that the route actually forwards the request header.
Extend the local-host file-content test with a revalidation round trip.

Co-Authored-By: Claude <[email protected]>
@SawyerHood
SawyerHood force-pushed the bb/mobile-perf/http-caching-and-hub-gating branch from d87ac63 to 38abcca Compare August 19, 2026 16:13
@SawyerHood
SawyerHood merged commit 4dc54e5 into main Aug 19, 2026
12 checks passed
@SawyerHood
SawyerHood deleted the bb/mobile-perf/http-caching-and-hub-gating branch August 19, 2026 16:23
SawyerHood added a commit that referenced this pull request Aug 19, 2026
… (B19, B20) (#1888)

## What was wrong

- Timeline delta cache (`timeline-latest-rows-cache.ts`) held one
snapshot per params key. Two viewers of a streaming thread (desktop +
phone) poll out of phase. The faster client advances the snapshot; the
slower one never finds the revision it echoes and gets the full window
on every batch (audit B19).
- The latest timeline page ships the running turn's full command/tool
outputs inline (up to 32 K each). One running thread measured 434 KB raw
with 264 KB of output across 138 command rows, all rendered collapsed.
Every poll re-shipped and re-parsed it (audit B20).

## What changed

- Server (B19): each params key keeps a ring of 4 recent revisions keyed
by `maxSeq`. `GET /threads/:id/timeline?afterSequence=N` looks up
revision N and only falls back to a full window when N left the ring.
Repeat sets of the same revision only refresh recency.
- Server (B20): new `timeline-output-preview.ts`. In the default window
(no `includeNestedRows`), a top-level command/tool output longer than 4
000 chars becomes a 2 000-char head + omitted marker + 1 000-char tail,
and the row carries `outputPreview: { totalChars }`.
`includeNestedRows=true` (CLI verbose log, SDK callers) still gets full
inline output. The existing turn-summary-details route scoped to the
row's `turnId` + `sourceSeqStart..sourceSeqEnd` returns the whole output
(works for running turns and after the turn completes).
- Contract: optional `outputPreview` on command/tool rows;
`includeNestedRows` doc; regenerated plugin SDK bundled d.ts and
templates embed.
- Client: `useTimelineWorkRowFullOutput` +
`CommandWorkRowBody`/`ToolWorkRowBody` in `TimelineRowDetails.tsx`.
Expanded rows render the preview at once and load the whole output
through turn-summary-details once the row is not pending (a running
row's range still moves; its preview tail is the live part). A short
note explains the state and offers Retry on failure; nothing extra
renders once the full output is loaded or the row was never previewed.

## How you verified

- New tests (fail before, pass after):
- `apps/server/test/public/public-thread-timeline-delta.test.ts`: two
interleaved clients both receive mergeable deltas; a revision that left
the ring falls back to a full window.
-
`apps/server/test/public/public-thread-timeline-output-preview.test.ts`:
preview cap + `outputPreview` marker; small outputs untouched;
`includeNestedRows=true` full output; row-scoped turn-summary-details
returns full output for a running turn and after `turn/completed`.
-
`apps/app/src/components/thread/timeline/TimelineRowDetails.output-preview.test.tsx`:
expanded finished row calls `sdk.threads.timelineTurnSummaryDetails`
with the row's turnId/range and renders the full output; a pending row
keeps the live preview and does not fetch; a failed load shows the
preview with Retry.
- `pnpm exec turbo run typecheck --filter=@bb/server --filter=@bb/app
--filter=@bb/server-contract --filter=@bb/templates
--filter=@bb/thread-view --filter=@bb/sdk --filter=@bb/cli`: 8/8
successful.
- `pnpm exec turbo run lint --filter=@bb/server --filter=@bb/app
--filter=@bb/server-contract`: 0 errors; @bb/app warning count unchanged
from baseline (147).
- Targeted vitest: server (delta + preview + timeline-in-turn-window +
public-thread-data + output-truncation +
conversation-outline-performance) all pass; app (output-preview,
ThreadTimelineRows.actions, render-stability, controller.merge) 52/52;
full suites of @bb/server-contract, @get-bb/plugin-sdk, @bb/templates
pass.

Fixes: part of the mobile / iOS Safari performance program (verified
sweep report in the bb thread; no single issue).


## Stack context

Layer 9 of 22 in the `bb/mobile-perf/*` stack (bottom → top: quick wins
first, big rocks last).
- Prerequisite (layer below): `bb/mobile-perf/search-fts` (#1887).
- Next layer: `bb/mobile-perf/http-caching-and-hub-gating` (#1889).
- Audit findings addressed: see title IDs. Review: approved-with-fixes;
1 review fix commit(s).
- Reviewer notes / follow-ups: Follow-up (not a defect of this package):
only top-level command/tool rows are previewed. A pending delegation's
childRows and file-change diffs/stdout in the running turn still sh |
Follow-up (edge UX): a row that stays `pending` while the thread is no
longer running (e.g. an interrupted item that never got its
item/completed before the turn closed) keeps the
- Wire/contract: HTTP client<->server contract only (no server<->daemon
wire change; HOST_DAEMON_PROTOCOL_VERSION not bumped).
packages/server-contract: new optional `outputPreview?: { totalChars:
number }` on `timelineCommandWorkRowSchema` and
`timelineToolWorkRowSchema` (new export `timelineOutputPreviewSchema` /
`TimelineOutputPreview`); `includeNestedRows` query doc updated.
Behavior change on GET /threads/:id

> AGENT GENERATED: by Claude Code (claude-mangosteen-eap)

---------

Co-authored-by: Claude <[email protected]>
SawyerHood added a commit that referenced this pull request Aug 19, 2026
…te preload + skeleton (A6, A8, A10, A13, A15, J1) (#1890)

## What was wrong

- The browser SDK attached the `guide` area, so ~112 KB of generated
guide markdown sat in the boot chunk although no browser code calls it
(A8).
- `@bb/domain`, `@bb/server-contract` and other leaf contract packages
had no `sideEffects: false`, so barrel-reachable modules could not be
dropped from the boot path (A13).
- No font preload: the Inter latin woff2 request started only after the
JS rendered text. `--font-mono` named the unshipped "Fira Code" (A15).
- The pre-paint script never added the `dark` class or the cached
palette CSS, so dark/themed sessions painted the light default palette
until main.tsx ran (J1).
- The `*` route chunk was fetched only on first React render and sat
behind `fallback={null}`; the views then showed a bare "Loading…"
paragraph (A6).
- 24 desktop-app icon PNGs were base64-inlined into a route chunk (~35
KB br) for a menu that needs a local host daemon (A10).

## What changed

- `createBbSdk` takes the guide area as an explicit argument. The Node
factory passes `createGuideArea()` and returns `BbSdk`; the browser
factory returns `BrowserBbSdk` (all server-backed areas, no `guide`).
The public-types test pins the browser key set. Plugin SDK bundled d.ts
regenerated.
- `sideEffects: false` on `@bb/domain`, `@bb/server-contract`,
`@bb/hono-typed-routes`, `@bb/host-daemon-contract`, `@bb/fuzzy-match`.
- New build-only Vite plugin `bb:font-preload`
(`apps/app/vite-font-preload.ts`) injects `<link rel="preload" as="font"
type="font/woff2" crossorigin>` for the emitted
`inter-latin-wght-normal` asset. `--font-mono` is now the system
monospace stack.
- `index.html`: the head script adds `dark` per `bb.theme` /
`prefers-color-scheme`; a body-end script injects `bb.appThemeCss` into
`<style id="bb-app-theme">` after the app stylesheet.
`applyCachedAppThemeCss` adopts that element and re-appends it only when
something was inserted after it (dev-mode style tags).
- `App.tsx` starts `import("./views/SplitWorkspaceRoute")` at module
scope and reuses the promise in `lazy()`. New `RouteLoadingSkeleton` (48
px header row + composer footprint) is the Suspense fallback for the `*`
route and replaces the "Loading…" branches in `RootComposeView` and
`ThreadDetailView`.
- `build.assetsInlineLimit` excludes `/workspace-open-target-icons/`.
- `bundle-budget.json` ratcheted to 3% above the new measurement.
- A12 (chunk minSize) not applied: rolldown 1.0.0 only supports
`minSize` for manual `codeSplitting.groups`; verified with a build that
it has no effect on automatic boot chunks.

## How you verified

- `pnpm exec turbo run build --filter=@bb/app` then `node
apps/app/scripts/check-bundle-budget.mjs`: boot payload 1538.4 KB raw /
415.5 KB brotli, 41 chunks (before: budget 1671 / 456.4).
`dist/index.html` contains the font preload link;
`root-compose-create-preference-*.js` is 4,253 B; the entry chunk
references the SplitWorkspaceRoute chunk statically.
- `pnpm exec turbo run typecheck --filter=@bb/sdk --filter=@bb/app
--filter=@bb/cli --filter=@bb/server --filter=bb-app
--filter=@get-bb/plugin-sdk`: pass.
- `pnpm exec turbo run lint --filter=@bb/app --filter=@bb/sdk`: 0 errors
(147 pre-existing warnings, none in touched files).
- New tests: `apps/app/src/index-html-pre-paint.test.ts` (7 tests: runs
the real index.html inline scripts under jsdom; dark class from
stored/system preference; palette style injected as last head child;
adoption by applyCachedAppThemeCss) and
`apps/app/src/vite-font-preload.test.ts` (3 tests). Also ran
theme.test.ts, App.* route tests,
RootComposeView/SplitWorkspaceRoute/SplitThreadArea tests, full @bb/sdk
suite (94 tests), CLI guide tests: all pass.

Fixes: part of the mobile / iOS Safari performance program (verified
sweep report in the bb thread; no single issue).


## Stack context

Layer 11 of 22 in the `bb/mobile-perf/*` stack (bottom → top: quick wins
first, big rocks last).
- Prerequisite (layer below):
`bb/mobile-perf/http-caching-and-hub-gating` (#1889).
- Next layer: `bb/mobile-perf/katex-lazy` (#1891).
- Audit findings addressed: see title IDs. Review: approved-with-fixes;
1 review fix commit(s).
- Deliberately not done here: A12: rolldown 1.0.0 (Vite 8.0.12) exposes
codeSplitting.minSize only as a fallback for manual groups, not as a
minimum for automatic chunks; verified by build t
- Reviewer notes / follow-ups: A12 (chunk minSize) intentionally skipped
by the implementer; rolldown's codeSplitting.minSize is a fallback-group
setting and did not change the boot graph. Not a defect, just uni |
Minor, not fixed: the font <link rel=preload> is injected with
injectTo:"head" so it lands as the last head child, after ~40
modulepreload links and the stylesheet. Preload scanner | Pre-existing,
not a regression: the root "@bb/sdk" export maps the browser condition
to dist/browser.js while its "types" point at node.ts (BbSdk with
guide). apps/app only type-im
- Wire/contract: None. No server<->daemon payloads, host RPC, or
WebSocket messages changed; HOST_DAEMON_PROTOCOL_VERSION not bumped.
Type-level contract change only: @bb/sdk BbSdk is now BbSdkAreas +
guide; createBrowserBbSdk() returns BrowserBbSdk (no guide). No browser
caller used sdk.guide. bundled-types/bb-plugin-sdk.d.ts regenerated.

> AGENT GENERATED: by Claude Code (claude-mangosteen-eap)

---------

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant