Skip to content

feat(patchy): import CSV and download generated files - #450

Merged
allisonmahmood merged 4 commits into
mainfrom
tier2/411-csv-download
Oct 1, 2026
Merged

allisonmahmood merged 4 commits into
mainfrom
tier2/411-csv-download

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Patches had to hand-roll CSV parsing and store generated files just to offer a download. This adds a supported CSV codec on both import graphs and a shell-approved download that needs no file store.

patchy/csv wraps PapaParse with physical-line errors, strict record widths, formula protection, and the 10-million-character / 1-million-cell bounds. patchy.download(name, data) reuses the D-1 card from #408, requires a trusted shell click, and refuses encoded payloads above 20 MiB. The refusal styling follows the #385 pick. Skills, capability announcements, and product documentation describe both APIs.

Stacked on tier2/410-member-directory; this PR targets that branch and contains only the #411 implementation and refusal-styling commits. Implements #384 §12 and closes #411.

Verification from the implementation pass

  • Typecheck and lint passed.
  • CSV edge cases passed in the sandboxed page and a published workerd handler.
  • Generated downloads passed on company/public tier 1 and tier 2; existing stored-file download and staging checks passed.
  • Browser smoke covered desktop/narrow cards and dismissal focus. Standards and spec reviews had no remaining findings.
  • Full offline suite: 137/138 test files passed. The packed tier 2 startup scenario hit its existing 12-second subprocess timeout, then passed in isolation without changes.

These checks preceded the final refusal-styling commit.

Implemented with GPT-6 Astra via omp; refusal styling refined with Claude Opus 5.5.

@github-actions github-actions Bot added area:server Touches the server area area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:docs Touches the docs area size:xl Over 1,000 changed lines; review in multiple passes labels Sep 30, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Opus review

Three blocking findings, most severe first. I reproduced each one against the branch. The first two with small scripts, the third from the broker's reservation arithmetic.

1. patchy/csv reports a closed quote as unterminated_quote when whitespace follows it at the end of a row

packages/patchy/src/csv.ts:101 accepts spaces and tabs after a closing quote. Then emit (csv.ts:60-66) hands PapaParse the row without its line terminator. Papa only allows those spaces before a delimiter or a newline, and the slice has no newline, so it reports MissingQuotes. The helper maps that to unterminated_quote:

parse('x,"a" \r\ny')  -> CsvError unterminated_quote, line 1
parse('"a"  ')        -> CsvError unterminated_quote, line 1
parse('"a" ,b')       -> [["a","b"]]   (the space is dropped, not kept "as written")

Plain Papa.parse('x,"a" \r\ny') returns [["x","a"],["y"]] with no errors. So the helper refuses the whole file, and names a quote that is actually closed, on input its own library accepts. It also treats the same whitespace two ways depending on what follows it. The cause is two tokenizers that disagree: the scanner decides where rows and quotes end, and Papa re-decides per row. Since the scanner already detects real unterminated quotes at EOF, any MissingQuotes coming out of emit is a disagreement, not a user error. Fix: make the scanner authoritative. Either treat anything after a closing quote other than ,, a line break or EOF as invalid_quotes, or keep accepting the whitespace and make both paths agree. Add the trailing-whitespace case to csv.spec.ts so it runs on the page and in workerd.

2. download(name, data) detaches the caller's Uint8Array or ArrayBuffer, and the docs don't say so

packages/patchy/src/download.ts:10-12 passes a full-buffer Uint8Array through unchanged, and wraps an ArrayBuffer in a full view. clientTransport.ts:265-282 then transfers that buffer to the shell. The common new TextEncoder().encode(csv) result is a full-buffer view, so after await patchy.download("a.csv", bytes) the patch's bytes.byteLength is 0. I confirmed with a MessageChannel: 9 bytes before, 0 after.

Concrete failure: a viewer clicks Not now, and the patch keeps its encoded bytes and offers them again. The second card says "0 bytes" and downloads an empty file. Any later use of the same buffer, such as also putting it in a store, sees it empty. files.put documents this ownership transfer (README line 387). download is documented in the README, the patchy-loop skill and docs/product.md as simply accepting Uint8Array or ArrayBuffer. Fix: copy in createDownload, since at most 20 MiB is copied once, on a user-paced path. Or document the transfer exactly as files.put does.

3. A pending generated-file offer counts its bytes twice against the frame's 64 MiB for as long as the viewer ignores it

The broker reserves the payload with the request (packages/serving/src/broker.ts:689-691). It then awaits handleDownloads.add (broker.ts:712), which reserves the same size again for the Blob (packages/serving/src/downloads.ts:149). The request reservation is only released in finally, after the viewer clicks. So one pending 20 MiB offer holds about 40 MiB.

A second offer of about 12 MiB or more then fails inside add with too_large / frame.heldBytes, and no card appears. That contradicts the D-1 pick, where offers stack ("three visible, older ones fold into N more files"), and the documented 20 MiB per-file limit. The frame's other operations also lose that budget in the meantime. The stored-file path (broker.ts files.download) does not await the card and releases its reply bytes right away, so it holds one copy. Fix: once the Blob exists, release the request's byte reservation and drop the ArrayBuffer reference, keeping only the JSON overhead and the pending slot for the await. Better still, add a test with two large pending offers.

Checked, no finding

  • Parsing: BOM only at the start, CRLF/LF/bare CR and quoted multiline fields. Unterminated quotes name their opening physical line and return no partial result. Duplicate headers (including two empty ones) throw. Wrong-width rows are reported by starting line and never padded. Only empty physical lines are skipped.
  • Bounds: both are enforced before cells are materialised, and one wide row is bounded too.
  • API surface: no PapaParse options leak through the API.
  • stringify: writes CRLF, protects text cells starting with = + - @ tab or CR, leaves numbers unprotected, and has a working off switch.
  • Both graphs: the import check, the dist bundle and the licence copy are in place, and csv.spec.ts runs every case in the sandboxed page and in a published workerd handler.
  • Download: the shell only honours an isTrusted click on its own button, and the test proves a synthetic click is ignored. The 20 MiB bound is measured on encoded bytes, a 21 MiB payload is refused with the card, and exactly 20 MiB goes through. The card shows name and size. It works on public tier 1, tier 1 and tier 2, and nothing reaches the runtime.
  • Surfaces: README, the catalogue, the Helper glossary, docs/product.md and ui-consistency are all updated.

Reviewed by Claude Opus 5.5 via Claude Code.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed 010acd3d09b3c805a81d7e24b2f0e9f3e198198c with git diff origin/tier2/410-member-directory...HEAD, against #411, #384 §12 and the download design selected in #385. One pass, no subagents. Only merge blockers considered.

Standards

No merge-blocking method or YAGNI findings. The implementation reuses the existing download card, broker transport, limits registry and SDK packaging. The CSV framing pass addresses the explicit requirement to enforce the cell bound before PapaParse materializes an oversized row.

Spec

No merge-blocking intent findings. The diff covers the CSV contract on both import graphs, generated downloads on both page clients, shell-owned approval and byte limits, and the requested documentation and skills. I found no missing requirement, incorrect implementation or extra scope that warrants blocking this merge.

Verification in this review:

  • Direct CSV execution passed 7,381 round trips, physical-line error checks, formula protection with numbers unchanged, and exact/over-limit character and cell boundaries.
  • An isolated Chromium page exercised the actual download-card module and shared styles: filename and size, ignored scripted Download clicks, trusted-click completion, dismissal and focus return, desktop/narrow refusal rendering, and resource release on close.
  • I inspected the added page/workerd acceptance coverage but did not rerun the hosted or workerd suites. The isolated UI check did not exercise broker admission.

Applicable surfaces were the shell-local protocol and both clients, SDK packaging/catalogue/skills, product documentation and glossary, served cards, and dismissal/close paths. No CLI-command, dev-runner, migration, company-resource or package-layout change was required.

Standards: 0 blockers. Spec: 0 blockers.

@allisonmahmood

allisonmahmood commented Sep 30, 2026 •

Copy link
Copy Markdown
Owner Author

Review follow-up

Pushed 47aa2b8 (review fixes) and 50057a1 (CI test isolation). Read both conversation reviews, the Reviews-tab bodies and inline comments. The latter two are empty; no Grok review is posted.

Fixed

  1. Opus: closed quotes followed by whitespace. The framing scan now consistently rejects characters after a closing quote other than a comma, line break or EOF with invalid_quotes. Papa's row-local diagnostics no longer misclassify an already closed field as unterminated_quote. Added page and workerd cases for spaces/tabs before CRLF, LF, EOF and commas, including physical lines after a multiline field. README, product docs and the project skill document the strict rule.
  2. Opus: detached generated-download inputs. download copies caller-owned Uint8Array and ArrayBuffer inputs before the transport transfers them. Blob conversion already returns a fresh buffer. Browser coverage dismisses and reuses each input type, then checks the downloaded contents on company tier 1, public tier 1 and tier 2.
  3. Opus: double held-byte accounting while approval is pending. After the card creates its Blob, the broker releases the request-buffer reservation and clears all local/message references to that buffer before awaiting approval. The envelope, request slot and Blob reservation remain accounted for. Coverage holds two 20 MiB offers simultaneously, dismisses one, admits a replacement and dismisses the remaining offers. Blob construction still reserves its temporary copy, so the 64 MiB aggregate guard is not bypassed.
  4. CI: unrelated Node 22 CLI timeout. The previous run's sole failure was six sequential CLI launches sharing a 5-second timeout (5.07 seconds; adjacent cases took 4.99 and 4.90 seconds). Split the two independently asserted command depths into separate cases. All assertions and the timeout remain unchanged; all six cases pass locally.

Kept as-is

  • Chose Opus's suggested strict CSV framing rule rather than accepting and silently dropping trailing whitespace: cell text is otherwise preserved exactly.
  • Did not take the alternative of merely documenting buffer transfer: preserving inputs makes dismissal/retry safe. Stored-file put ownership semantics remain unchanged.
  • Kept the 20 MiB file bound, 64 MiB shell guard, trusted shell click, shell-local/public behavior and the selected D-1 styling, including the final refusal styling/copy. Removed the sentence-pinning assertion; refusal metadata, file identity and absence of Download remain covered.
  • Astra reported no blocking findings and requested no changes. No posted finding was dismissed as a false positive or left unresolved.

Verification

  • pnpm typecheck, pnpm lint, and pnpm format:check passed; the later CLI-only edit also passed ESLint.
  • CSV/import-graph/transport suites: 70 passed.
  • Chromium CSV page/workerd and generated-download suites: 2 passed, including all new cases and all three tier/scope combinations.
  • Split CLI state/depth cases: 6 passed.
  • Separate disposable-instance browser smoke: the original 13-byte CSV buffer remained intact after Not now and Download; the saved file contained exactly name\r\nÉlodie; two 20 MiB cards remained pending together and dismissed cleanly. Visually checked desktop and 390px layout. No production or daily-driver instance touched.

Latest commit is 50057a179ebd56666ef8cd9ac3f3eb2c815ff04e. All nine reported checks passed on this commit: Node 22 tests, Node 24 tests, Postgres concurrency, Clerk live, lint/typecheck/format, packed CLI smoke, dependency review, server image and labels. CI run. The stack base has no separately configured required checks. Final GitHub state is CLEAN / MERGEABLE, still open and non-draft against tier2/410-member-directory. Rechecked conversation comments, review bodies and inline comments after CI completed: no new review findings or Grok review. No unresolved findings. Ready to merge; not merged.

@allisonmahmood allisonmahmood linked an issue Oct 1, 2026 that may be closed by this pull request
@allisonmahmood
allisonmahmood force-pushed the tier2/410-member-directory branch from d85010e to 5a3f3e8 Compare October 1, 2026 06:12
Base automatically changed from tier2/410-member-directory to main October 1, 2026 06:30
allisonmahmood and others added 4 commits October 1, 2026 08:31
The refused card now matches the D-1 mock: note-refused paper, the
sentence "This file is too large to download (24.1 MB, the limit is
20 MB)." with both sizes from the card's own size format and the limit
from the registry, and a plain Dismiss button.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@allisonmahmood
allisonmahmood force-pushed the tier2/411-csv-download branch from 50057a1 to 1f8b40e Compare October 1, 2026 06:31
@allisonmahmood
allisonmahmood merged commit 8306348 into main Oct 1, 2026
21 of 23 checks passed
@allisonmahmood
allisonmahmood deleted the tier2/411-csv-download branch October 1, 2026 07:11
allisonmahmood added a commit that referenced this pull request Oct 1, 2026
Tier 2 records every invocation, the calls it makes and its `ctx.log`
lines, but nobody could read that record outside the database. Owners
and admins had no way to see who ran what, as whom, or why an action
failed.

This adds the per-patch log to the portal, as picked on #385 (L-2 and
W-2):

- `/patches/<name>/log`, for the patch's current owner and every admin.
Everyone else gets a 403, and reassignment moves the owner's access.
Rows are top-level invocations, newest first: time, person, version,
handler, kind, outcome and duration. A row expands into the calls and
nested handlers inside it, in sentence form ("leads.create (mutation) ·
as the patch"), followed by the patch's `ctx.log` lines. Failed rows
open by default. A reply the page never received shows the real settled
outcome plus "reply not delivered". Pages hold 25 entries, paged by
cursor. Filters cover outcome, person and handler and search 1,000
entries at a time; the page says when older entries lie beyond that
window. Connection calls name the connection by handle. Each entry reads
and shows at most 50 steps, outermost first, and says when it made more.
The nothing-logged and filtered-empty states follow the mock. The page
says the log is an attribution record, not an access audit, and that log
lines are written by the patch itself.
- Recent activity on the card for the owner and admins: the last three
entries in sentence form ("Alice Chen · Sales CRM v12 · leads.import
(action)"), each linking into the log, then "See the full log".
- `InvocationLog` gains two bounded readers over the existing
`runtime_invocations` and `runtime_calls` columns: `page` (the card
skips its trees) and `choices`, which lists the filter options from the
newest 1,000 entries. No migration. The per-connection recent-calls list
is unchanged.
- The shell component set gains `pill-failed`, `list-tree` and an
expandable `table-expand` row. The log table keeps words whole and
scrolls inside `portal-table` on phones; other tables are unchanged.
- Docs: the `ui-consistency` spec, the Portal glossary (**Log**),
`CONTEXT-MAP.md` (Portal → Runtime) and `docs/product.md` (who reads the
log).

Stacked on `tier2/411-csv-download` (#450); this PR contains only the
#412 commits. Implements #412, part of #384.

## Verification

- `pnpm lint` and `pnpm typecheck` pass.
- Tests pass in `packages/portal`, `packages/runtime`, `packages/core`,
`apps/server`, `packages/patches/src/Subscriptions.test.ts` and
`packages/patchy/src/devExecution.test.ts`. New cases:
- an owner sees a failed action's tree, with the connection call that
succeeded before the failure, and is refused another owner's log;
- admins read every patch's log, and reassignment moves the owner's
access;
  - Recent activity appears for the owner and admins only;
  - cursor paging, filters, and the empty states;
- `InvocationLog.page` bounds each entry's tree, reads overdue entries
as unknown and scopes cursors to the patch.
- I checked the log page, card and narrow layouts against the L-2 and
W-2 mocks in a real browser against a disposable server with seeded
invocations. The versions table on phones is unchanged from before this
branch.

Built with Claude Opus 5.5 via Claude Code.

---------

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

area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:docs Touches the docs area area:server Touches the server area size:xl Over 1,000 changed lines; review in multiple passes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(patchy): patchy/csv and the shell's generated-file download

1 participant