Skip to content

Sample file previews and stream downloads through direct file routes - #4554

Merged
ymichael merged 9 commits into
mainfrom
bb/improve-this-implementation-thr_5tj9gs4ah6
Sep 30, 2026
Merged

ymichael merged 9 commits into
mainfrom
bb/improve-this-implementation-thr_5tj9gs4ah6

Conversation

@ymichael

@ymichael ymichael commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Unsupported files showed only “Preview not available,” without useful file details or a download action. Preview classification downloaded whole files through the daemon's size-capped read API, and callers used inconsistent file routes. Raw document responses sandboxed HTML only: opening an SVG or XHTML document could run scripts with BB's origin privileges.

What changed

  • Built-in previews, markdown images, media, downloads, pdf-preview, and inline-vis use direct, path-shaped file URLs. The server resolves the host and root for each request; built-in previews no longer mint or refresh leases.
  • File routes cover thread storage, absolute host paths, environment working trees and Git revisions, and project sources on the primary or named host. Relative assets resolve against those routes. Windows drive paths are supported. Host routes intentionally allow reads from the filesystem/drive root; a thread selects the host, not a restricted filesystem scope.
  • Arbitrary-directory plugin previews retain POST /api/v1/files/previews with { hostId?, rootPath, ttlMs? }. As on main, each request mints its own lease with the requested lifetime; lease reads now stream through the same handler and honor byte ranges. Leases remain in memory and expire; direct routes do not.
  • Working-tree reads stream through the existing host.read_file_chunk RPC, with single byte ranges, weak ETag revalidation, bounded chunks, and file-change detection. Git revision routes use the existing whole-file read and retain its size limits. No new daemon wire fields are introduced.
  • Previews sample the first 64 KiB. Unsupported binaries show file details and Download without fetching the remainder; text is fetched in full only within the 25 MB preview limit. Downloads stream directly from the file URL. HTML renders interactively only up to 5 MiB; larger HTML can still be read or downloaded.
  • Every raw-file response now carries Content-Security-Policy: sandbox allow-scripts, including SVG and XHTML. Scripts remain usable inside interactive previews but cannot acquire BB's origin privileges. HTML retains no-store, and all raw files retain nosniff.
  • sdk.projects.fileContent and bb project content read through project file routes and determine UTF-8 versus base64 from the bytes. The SDK rejects empty, ., .., backslash, and NUL path segments with "Invalid file path" before sending, because URL parsing would otherwise collapse .. and reach a different API route. Duplicate content routes and lease-specific app query/context plumbing are removed. docs/debugging-and-qa.md documents the resulting routes, limits, and security behavior.

Related: #2697. This supplies consistent file byte routes and downloads; it does not implement the canonical file-reference design from that issue.

How you verified

  • pnpm exec turbo run test --filter=@bb/server -- test/files/file-content-routes.test.ts test/files/host-file-routes.test.ts test/security/api-origin-guard.test.ts: 29 tests passed. Coverage includes streaming/ranges, file-change errors, large HTML, source routing, traversal rejection, revision reads, and browser-origin guards.
  • New SVG/XHTML response-policy regressions failed before the security fix and passed afterward. They check both full and partial responses. The opaque-origin regression now covers reads as well as mutations.
  • pnpm exec turbo run typecheck lint --filter=@bb/server: passed the available tasks. After correcting a test-fixture type, reran the 13 file-content tests successfully. Formatting and git diff --check passed.
  • Chromium verification against an isolated instance of the real server with a fresh test database and synthetic daemon responses: before the fix, SVG/XHTML scripts read the thread API, browser storage, and an embedding page's DOM, and four synthetic mkdir requests reached the daemon boundary. No real filesystem mutation was performed.
  • After the fix, all six browser cases (HTML, SVG, XHTML; direct navigation and iframe embedding without a sandbox attribute) still executed their scripts but could not read BB's API/storage or the embedding page. No mutation reached the synthetic daemon. HTML was already protected before the fix.
  • A fresh logged-out browser and a cookie-free HTTP request to the deployed remote entry point's file URL returned 401 and the sign-in page. This verifies the existing remote login gate; the source fix has not been deployed. Browser security verification was Chromium only.

Side-by-side verification against main (merge base 0e7b518f13): two isolated dev instances with fresh data directories, the same fixture repository, and real agent threads, driven by real clicks in headless Chrome. It recorded the rendered panel, iframe script and asset loading, image loading, Download SHA-256, and every file request with its status. This covered ae0fa06e7e; after 27303a80d7 the lease API, bb project content, and the Docs plugin were rechecked. e5858ac82c (headers only) was verified by its own tests above.

  • Same as main: workspace, thread-host, thread-storage, and project (new-thread screen) previews across text, Markdown, CSV, HTML/HTM, SVG, PNG, PDF, empty, UTF-8 split at 64 KiB, >64 KiB text, Unicode/space paths, deep and symlinked-dir relative images, and symlink escapes; HEAD and merge-base previews of deleted files; Diff panel file opens; chat images; the agent's image-read rows; inline-vis (workspace and thread-storage HTML with relative assets, Markdown, >5 MB error); the PDF viewer; Skills library relative images; the Docs plugin (lease API); 13 bb project content cases; and HTTP range, HEAD, 304, 416, traversal, and unknown-ID handling on every route family.
  • Intended improvements confirmed: unsupported and oversized files show details and Download, with byte-exact downloads up to 40 MB (main showed "not available" or a 25 MB error); .htm is sandboxed (main served it as unsandboxed text/html); thread-host HTML previews load relative assets; HTML over 5 MB shows as source instead of a 413; video streams from its URL instead of a base64 data URL.
  • Two regressions found and fixed in 27303a80d7: bb project content <project> ../../hosts sent GET /api/v1/hosts and printed the host list as file content (main returns 400), and lease reuse, which returned the same lease and ignored shorter ttlMs values.
  • Not run: remote share-link previews in headless Chrome, which needs a share login. Checked manually instead: sandboxed HTML previews through the share link fail to load their relative assets on both main and this branch (the gate's SameSite=Lax cookie is not sent from sandboxed frames), so this is not a regression. The host-scoped plugin preview panel has no first-party entry point. Desktop and native mobile were not run.
  • pnpm exec turbo run test for app, CLI, SDK, contract, client-core, pdf-preview, and inline-vis passed. In the server suite, install-machine-script and plugin-update failed only under full parallel load and passed alone on both this branch and main.

AGENT GENERATED

@ymichael
ymichael force-pushed the bb/improve-this-implementation-thr_5tj9gs4ah6 branch from 60d717d to 40762b3 Compare September 30, 2026 16:46
@ymichael ymichael changed the title Describe unsupported file previews and offer a download Preview files from a byte-range sample and download unsupported files by URL Sep 30, 2026
ymichael and others added 4 commits September 30, 2026 10:57
Files with no preview renderer showed only "Preview not available for
<mime>." The preview loader already fetches the full file to classify it,
so unsupported previews now keep those bytes. The panel shows the file
name, MIME type and size, and a Download button that saves the fetched
bytes, which works for every preview source regardless of whether its
URL is directly downloadable.

The byte-size formatter and blob-download helper that were private to
the git diff header and voice input move to shared app libs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Unsupported previews kept the whole file in the React Query cache just
so Download could save it, holding up to the 25 MB daemon cap per open
tab for a button that may never be clicked. Previews now keep only
sizeBytes. Each preview tab passes a fetchFileBlob that re-reads the
file from its own source when Download is clicked: the raw thread
storage and host-file routes, the environment diff-file and project
file-content APIs, or a host file read.

The base64-or-utf8 decode repeated across the environment, project and
host preview queries moves to a shared helper, and project file routing
is built once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Previews read every file in full, through a daemon read capped at 25 MB,
only to decide whether it was text; Download then read it a second time,
and files over 25 MB could not be previewed or downloaded at all.

Every preview source now has one raw, Range-capable URL backed by
chunked host.read_file_chunk reads. Thread storage already had one; the
thread files/raw route (previously HTML only) and preview-lease routes
now stream, and environments gain diff/file/raw and projects files/raw.
The client samples the first 64 KiB: complete samples become the preview,
binaries become an unsupported preview from the sample and Content-Range
size, media renders from the raw URL, and text is fetched in full only
up to 25 MB, otherwise it is reported as too large. Download is an
anchor to the raw URL, so the browser streams it to disk.

The host preview query no longer falls back to a full files.read when a
preview lease cannot be created; that path only failed with the host.
Raw responses share one header policy (nosniff, sandboxed no-store HTML
up to 5 MB).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Every preview source had its own byte route (thread storage, thread host
files, worktree, project files, and the new environment/project raw
routes), each duplicated by a whole-file content route. Replace them with
one mint-and-stream pair: POST /files/previews now also accepts a
source (thread-storage, thread-host, environment with an optional git
ref, or project) that the server resolves to a host and root, and GET
/file-previews/:lease/* streams that root. The same resolved root reuses
its lease, so URLs stay stable while clients refresh them. Git-revision
leases read the blob in one whole-file read with SHA-256 revalidation.

The app mints leases through one query per source: previews, HTML
iframes, markdown images in previews and plugin documents, chat and
timeline images, and Download links all use lease URLs. Thread timelines
resolve the thread host lease once in ThreadTimelineSurface and share it
through context. The pdf-preview plugin requests leases directly, and
inline-vis returns the lease URL from its preparePreview RPC.
sdk.projects.fileContent reads through a project lease and derives the
utf8/base64 encoding from the bytes, replacing the x-bb-content-encoding
header.

Removed routes: threads/:id/thread-storage/{content,files/*},
threads/:id/host-files/content, threads/:id/files/raw,
threads/:id/worktree/files/*, projects/:id/files/{content,raw},
environments/:id/diff/file/raw. Plugin SDK bumps to 0.6.7 because the
bundled SDK file-preview types change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/improve-this-implementation-thr_5tj9gs4ah6 branch from 40762b3 to 7b37f98 Compare September 30, 2026 18:00
@ymichael ymichael changed the title Preview files from a byte-range sample and download unsupported files by URL Read files through source-resolved preview leases; sample previews and stream downloads Sep 30, 2026
ymichael and others added 3 commits September 30, 2026 11:32
… leases fresh

Review follow-ups on the lease-based file reads:

- The 5 MB HTML limit lived in the shared raw-file headers, so a larger
  HTML file failed with 413 for text previews, downloads, and
  sdk.projects.fileContent. HTML responses now always stream with the
  sandbox CSP and no-store policy; the app renders an iframe only up to
  5 MB and otherwise shows source or the Download panel. The non-text
  HTML iframe state is gone with it.
- Host-scoped previews leased the file's parent directory, which the
  daemon rejects when that directory is a symlink. They now lease the
  filesystem root (or the Windows drive root) and keep relative markdown
  images confined to the file's folder at the routing level.
- inline-vis minted a ten-minute lease that its iframe kept forever. It
  now mints one-hour leases and re-prepares at half-life while mounted;
  lease reuse keeps the URL stable, and a server restart swaps in the
  new URL.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Preview leases solved one problem: a path-shaped URL whose relative
references resolve under a fixed root. For the built-in sources the
server can resolve that root from an ID on every request, so the
lease map, lease reuse, half-life refresh, restart recovery, per-source
lease queries and the timeline lease context were bookkeeping with no
security value (the local API has no auth beyond the origin guard).

Each built-in source now has a GET route that shares one streaming
handler and header policy:

- threads/:id/thread-storage/files/*
- threads/:id/host-files/* and hosts/:id/files/* (absolute path, with a
  leading drive segment selecting a Windows drive root)
- environments/:id/files/* and environments/:id/revisions/:ref/files/*
  (ref is HEAD or a 4-40 character hex commit)
- projects/:id/files/* and projects/:id/hosts/:hostId/files/*

The app builds these URLs synchronously. pdf-preview fetches them
directly, inline-vis returns them from preparePreview without a lease or
refresh timer, and sdk.projects.fileContent reads them. The skills
dialog no longer loads a whole SKILL.md preview just to learn a lease
URL. POST /files/previews keeps only { hostId?, rootPath } for plugins
that preview an arbitrary host directory, so the plugin SDK surface and
version match main again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael ymichael changed the title Read files through source-resolved preview leases; sample previews and stream downloads Sample file previews and stream downloads through direct file routes Sep 30, 2026
ymichael and others added 2 commits September 30, 2026 15:28
Verification against main turned up two regressions from the direct file
routes.

sdk.projects.fileContent (and `bb project content`) now builds a path
URL, and URL parsing collapses "." and ".." segments before the request
leaves the client. "../../hosts" therefore reached GET /api/v1/hosts and
printed its JSON as file content, where main's ?path= route answered 400
Invalid file path. The SDK now rejects empty, dot, backslash, and NUL
segments with the same message before sending anything.

POST /files/previews reused one lease per host root and only ever
extended its expiry, so a caller asking for a short ttlMs could get a
longer-lived lease shared with other callers. Reuse existed only to keep
the app's own preview URLs stable, and those no longer use leases, so
each request again mints its own lease with the requested lifetime, as
on main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit e56f854 into main Sep 30, 2026
20 checks passed
@ymichael
ymichael deleted the bb/improve-this-implementation-thr_5tj9gs4ah6 branch September 30, 2026 23:11
lukes-clanker Bot pushed a commit to banjerluke/bb that referenced this pull request Oct 1, 2026
Adds a "Download" choice to the PDF file opener preference and a
"Download PDF" item to the timeline file-link menu. Downloads fetch the
file through the direct file routes and save it client-side; locations
that cannot be downloaded (explicit host targets, unresolved workspaces)
explain why and fall back to the preview.

Squashed from feat/pdf-download-opener (6 commits) while rebasing onto
upstream's direct file routes (get-bb#4554).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
lukes-clanker Bot pushed a commit to banjerluke/bb that referenced this pull request Oct 6, 2026
Adds a "Download" choice to the PDF file opener preference and a
"Download PDF" item to the timeline file-link menu. Downloads fetch the
file through the direct file routes and save it client-side; locations
that cannot be downloaded (explicit host targets, unresolved workspaces)
explain why and fall back to the preview.

Squashed from feat/pdf-download-opener (6 commits) while rebasing onto
upstream's direct file routes (get-bb#4554).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
lukes-clanker Bot pushed a commit to banjerluke/bb that referenced this pull request Oct 8, 2026
Adds a "Download" choice to the PDF file opener preference and a
"Download PDF" item to the timeline file-link menu. Downloads fetch the
file through the direct file routes and save it client-side; locations
that cannot be downloaded (explicit host targets, unresolved workspaces)
explain why and fall back to the preview.

Squashed from feat/pdf-download-opener (6 commits) while rebasing onto
upstream's direct file routes (get-bb#4554).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
lukes-clanker Bot pushed a commit to banjerluke/bb that referenced this pull request Oct 15, 2026
Adds a "Download" choice to the PDF file opener preference and a
"Download PDF" item to the timeline file-link menu. Downloads fetch the
file through the direct file routes and save it client-side; locations
that cannot be downloaded (explicit host targets, unresolved workspaces)
explain why and fall back to the preview.

Squashed from feat/pdf-download-opener (6 commits) while rebasing onto
upstream's direct file routes (get-bb#4554).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Oct 16, 2026
## Human comments

## What was wrong

The shared preview header exposed copy and refresh controls but omitted
Download. After #4554, unsupported files could be downloaded while
previewable Markdown, JSON, and other files could not. This is the
remaining behavior reported in #2697 and tracked in #5620.

## What changed

Add Download to the wide file-preview header and compact File actions
menu, using the existing save-file path and the original file URL and
basename. This covers text, Markdown, CSV, HTML, images, videos, and
empty files across the shared secondary-panel preview surfaces. Loading,
missing, and stale previews do not expose a download target. Existing
file routes and SDK/CLI access are reused; no wire contracts change.

## How you verified

- `pnpm exec turbo run test typecheck lint --filter=@bb/app --`: passed;
625 test files and 5,923 tests passed, with 4 tests skipped.
- Eight added regression cases failed before the fix; all 42 FilePreview
tests passed afterward. Coverage exercises both header layouts and
verifies original URLs, filenames, and stale/missing-file behavior.
- Isolated source Chromium: clicked Download from the Markdown compact
menu and JSON wide header. Browser downloads completed and `cmp`
confirmed exact original bytes and filenames, including Markdown CRLFs.
- Started `pnpm start:worktree` and confirmed Download in the built app
with a dedicated sample project.
- Desktop and native mobile were not run.

Fixes #5620

> AGENT GENERATED
lukes-clanker Bot pushed a commit to banjerluke/bb that referenced this pull request Oct 29, 2026
Adds a "Download" choice to the PDF file opener preference and a
"Download PDF" item to the timeline file-link menu. Downloads fetch the
file through the direct file routes and save it client-side; locations
that cannot be downloaded (explicit host targets, unresolved workspaces)
explain why and fall back to the preview.

Squashed from feat/pdf-download-opener (6 commits) while rebasing onto
upstream's direct file routes (get-bb#4554).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
lukes-clanker Bot pushed a commit to banjerluke/bb that referenced this pull request Nov 4, 2026
Adds a "Download" choice to the PDF file opener preference and a
"Download PDF" item to the timeline file-link menu. Downloads fetch the
file through the direct file routes and save it client-side; locations
that cannot be downloaded (explicit host targets, unresolved workspaces)
explain why and fall back to the preview.

Squashed from feat/pdf-download-opener (6 commits) while rebasing onto
upstream's direct file routes (get-bb#4554).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
lukes-clanker Bot pushed a commit to banjerluke/bb that referenced this pull request Nov 12, 2026
Adds a "Download" choice to the PDF file opener preference and a
"Download PDF" item to the timeline file-link menu. Downloads fetch the
file through the direct file routes and save it client-side; locations
that cannot be downloaded (explicit host targets, unresolved workspaces)
explain why and fall back to the preview.

Squashed from feat/pdf-download-opener (6 commits) while rebasing onto
upstream's direct file routes (get-bb#4554).

Co-Authored-By: Claude Opus 5.5 <[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