Skip to content

feat(chat): attach files to a Chat message, up to 5 of 10 MB, kept 90 days (W1-13) - #1834

Merged
gkhngyk merged 14 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-w1-13-uploads
Oct 30, 2026
Merged

gkhngyk merged 14 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-w1-13-uploads

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

Chat Wave 1, W1-13: attach files to a Chat message (CHAT-02 §21), behind CHAT_AGENTIC. Stacked on #1833. With the flag off, nothing is written. Product owner approved.

Composer

  • Three ways in: + Attach files ("Up to 5 files, 10 MB each"), drag and drop, and paste. They turn on when an uploader is given.
  • Chips: each file becomes a chip with a type label (PDF, CSV…), its name, "Uploading…" and ×.
  • Errors under the box (spec §21): the type, 10 MB and 5-file limits, and "Upload failed." with Retry.
  • While uploading: Send waits ("Uploading · Send waits for your files"), then attachments carries the ready files' ids.

Upload path

  • lib/chat/uploads.ts: the type list (inferring from the extension when the browser gives no type, e.g. .md), 10 MB and 5 files. It matches the bucket and table checks in 00409.
  • Server actions (lib/actions/chat-uploads.ts). Each returns { ok, failure } and never throws. They are listed in subscription-guard-coverage's OPEN_ACTIONS with reasons; prepare checks the plan itself, like content images.
    • prepareChatUpload checks type, size, that Chat is on, the plan is active and the chat is the person's. It writes a pending row ({org}/{id}) and returns a one-time createSignedUploadUrl.
    • finishChatUpload marks the upload ready when the object exists, else failed.
    • removeChatUpload deletes a draft's file and row.
  • lib/chat/upload-client.ts: uploads with uploadToSignedUrl, so there's no percentage, only "Uploading…". A failure rolls the row back, and Retry starts over.
  • Engine: startChatRun takes attachmentIds (at most 5). Each must be the person's, ready and not on another message, all checked before anything is saved (else 400 attachments). Then they're tied to the user message and the chat. Reading files during a run is CHAT-04, not this PR.
  • Server: server/src/lib/chat-uploads-sweep.js deletes attachments past 90 days, object first, then row, 500 at a time. It's added to server.js's daily chain.

Related issue

Part of Chat (CHAT-02, Wave 1).

Type of change

  • feat — New feature

How to test

  1. With 00409 and the chat-uploads bucket (feat(chat): add the tables Chat's first wave needs (00407–00413) #1812), attach a PDF in a chat.
    • The chip shows "Uploading…", then ready, and Send carries it.
    • A 6th file, an 11 MB file and an .exe are refused with the spec's messages.
  2. Tests:
    • web: the composer, uploads, the chat-uploads actions, the engine and subscription-guard-coverage (12 files, 102 tests);
    • server: the sweep (3/3).

Checklist

  • Branch follows the naming convention
  • Commits follow Conventional Commits
  • Web and server: eslint, typecheck and the related tests pass
  • Tests added

🤖 Generated with Claude Code

cihan-gyk and others added 6 commits October 30, 2026 01:12
…iles, Help and add-on packs

Chat's Wave 1 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC:
nothing reads or writes them while the flag is off. Tables, types and the
demo's coverage only; the code that uses them comes in the Wave 1 PRs.

- 00407: chat_conversations gets shared_at (Share with team: every member
  of the workspace reads it), last_read_at (unread results), deleted_at
  (Delete with Undo; deleted chats are hidden from every member) and a
  title search column; chat_messages gets context_json (what a person's
  message was scoped to) and a text search column. 'simple' text search,
  so a chat in any language is found. The author policy now leaves deleted
  chats out, and a shared policy reads shared ones.
- 00408: chat_user_prefs gets the rest of Settings › General and the
  one-time notices: rail_open, panel_size, default_mode, answer_language,
  notify_via, show_thought, panel_on_pages, focus_prompted_at,
  usage_notice_period, legacy_imported_at.
- 00409: chat_uploads and the private bucket chat-uploads: 10 MB a file,
  the composer's 11 types, 5 a message (a trigger backs the server's
  check), kept 90 days.
- 00410: chat_tool_cache (a chat's read results by tool and scope, server
  only) and each step's and model call's measure: latency, cache hit,
  truncation, result tokens on chat_run_steps (never granted to members),
  prompt cache read/write tokens and latency on the ledger.
- 00411: chat_files (filed deliverables and saved answers, the
  workspace's, kept a year, searchable by title, summary and tags),
  chat_file_task_links, chat_storage_usage kept by a trigger, and the
  private bucket chat-files.
- 00412: help_answer_cache and help_gaps (server only, no workspace or
  person ids).
- 00413: add_on_products seeded with the owner's packs (AI credits $10,
  $50, $250, $1,000 at half their price in budget, 12 months; storage
  +25/+100/+250 GB at $5/$15/$29 a month; $50 and +25 GB Most picked),
  add_on_purchases (Admins read), ai_credit_grants and storage_grants
  (server only), and prompt_improve_usage.grant_id.

Members only ever read; every write is the server's. Tool names, tool
results and dollars stay server only. web/src/types/supabase.ts carries
the new tables and columns; schema.test.ts checks the policies, the
server-only tables, the limits and the seeded packs from the SQL;
steps.test.ts keeps the step measure out of the member columns. The demo
coverage skips chat_files and chat_tool_cache (a person's own Chat work).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… and a read-only view

Chat Wave 1, W1-10 (CHAT-02, agentic update). A copy of the mockup's
composer (compHTML), as components to be wired into the Chat pages by the
shell (W1-01).

- ChatComposer: the box, a toolbar with the run mode and Send, and the line
  under it. Variants: home (2 rows), dock and panel (1 row). The box grows
  to 240px, then scrolls.
- Enter sends, Shift+Enter adds a line. Enter during an input method's
  composition or on a touch screen is the box's own (composerKeyAction).
  Send is off for an empty box.
- While a run answers, Send is Stop, and Esc stops too. The box steers:
  "Steer while I work…". Enter stops the run, its done steps kept, and
  sends the text as the next message (onSteer; decided 2026-10-30). The
  line under reads "Enter stops this run and sends your message". A page
  without steering keeps the text until the run ends.
- ModeSwitch: Ask me first · Auto, ask before changes · Full auto, each pick
  with the mockup's toast. Full auto below Growth is locked: "Needs Growth",
  and it can't be picked.
- Analysts and Agency partners read only: no mode switch, a "Read-only ·
  Analyst" link to Your access, and "@ data · read-only" under the box.
- The model button reads "Auto · Haiku reads, Sonnet writes". Slots for
  the + / @ tools (W1-12) and the usage meter (W1-23).
- The Chat pieces preview gets a Composer section: home, a dock with a
  pretend run, and an Analyst's panel.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…poser

Chat Wave 1, W1-11 (CHAT-02 items 5–10c), on the composer (W1-10).

- Context chips above the text: what Chat looks at, by name ("Ansvisor",
  "Last 30 days"), never an ID. A label over 28 characters is cut, with the
  whole name in its tooltip. × asks the page to drop it for the chat
  (onRemoveChip). A send or a steer carries the chips left
  (onSend(text, { context })).
- One ghost suggestion in the empty box, dim, with a Tab key hint. Tab, or a
  click on it, makes it the text with the cursor after it. Typing replaces
  it, and it comes back when the box is empty again. It never sends by
  itself: while only it shows, Enter does nothing and Send stays off. With
  text, Tab moves on as usual. No ghost while a run answers. The page picks
  the suggestion: the variant's starter, then a clear follow-up, and a READ
  one for Analysts and Agency partners.
- The line under reads "Tab to accept · / skills · @ data" while the ghost
  shows.
- The preview's composers get the mockup's chips and starters.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Chat Wave 1, W1-12 (CHAT-02 items 11–17, agentic update; mockup #slash,
#atmenu, #plusmenu), on the composer's chips (W1-11). Menus open above the
box: ↑ ↓ move, Enter picks, Esc closes and keeps the text, and a click
outside closes them.

- /: typed first in an empty box, or from the / button. It lists Wave 1's
  shortcuts, which start a message: /analyze "Analyze", /report "Create a
  report on", /create "Create content for". Typing filters them by command
  or a word of the name. From the button, the box's text stays after the
  starter. Analysts and Agency partners have no / (as the mockup). Skills
  join the menu in Wave 2.
- @: typed at the start of a word, or from the @ button at the cursor. It
  references data: the page's own charts and metrics first (references,
  for W1-08), then the brand's matches (searchReferences), up to eight. A
  pick leaves the "@…" text and shows as a chip by name. × takes it off,
  and the send carries it (references: type, id, label, scope). No ID
  shows.
- searchChatReferences (server action, CHAT_AGENTIC): the brand's tracked
  prompts, its pages and its open Action Center tasks that match, a source
  at a time. Read with the person's session; site_pages isn't in the
  generated types, so it is read with the service role for a brand the
  session can read. Template tasks are named from their keys. A search is
  made safe for PostgREST's filters. It answers { ok, failure } and never
  throws (ansvisor#1777).
- +: Attach files when the page uploads (onAttach, W1-13). Connect a tool:
  Settings › Integrations for an Admin; for others, "Ask your Admin to
  connect" sends one access request (B2). Read a page and Create an image
  stay hidden until their waves.
- The preview's composers reference the mockup's chart, metric, table,
  page and task.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… Data used and its stamp

Chat Wave 1, W1-14 (CHAT-03 items 12a–14, the v2 timestamps), on the
composer's menus (W1-12). RunAnswer draws an answer from its run's events,
with the shared pieces (D1/D2):

- The agent works beside it (AgentAvatar), waits on the person, or is still.
- One status line, updated in place, in the running step's words:
  "Reading Citations…", "Opening ansvisor.com/pricing…", "Checking
  facts…". With no step running, "Writing the answer…" while text streams,
  else "Thinking…". "Reconnecting…" when the stream dropped.
- The steps under their header (RunSteps). Each step done, thinking left
  out, is a ✓ chip with its rows, and a click shows its detail. W1-21's
  "Checked facts" step (ansvisor#1822) is one of them.
- The answer streams in (Markdown).
- "Data used": one chip per source a read step read, with its largest row
  count, and per page a step opened. Skills, thinking, checks and failed
  reads are no source. The header counts these chips as its sources.
- "Generated Oct 30, 2026 · 09:14 · Data as of …" in the person's time zone,
  the GMT offset in its tooltip.
- What follows (next moves, the answer's actions) fades in once the run is
  done, and not at all with reduced motion.
- run-view.ts holds the status line, chips and Data used, from the steps
  alone.
- The Chat pieces preview plays the mockup's answer a step at a time ("Live
  answer"); its counts take the new pieces in.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… days

Chat Wave 1, W1-13 (CHAT-02 items 18–22, 00409), on the live answer
(W1-14), behind CHAT_AGENTIC.

- The composer attaches files from + Attach files, a drop or a paste
  (uploader prop). Each file is a chip: type tag, name, "Uploading…", ×.
  Under the box: "This file type isn't supported.", "Files must be 10 MB or
  smaller.", "You can attach up to 5 files.", or "Upload failed." with
  Retry. Send waits while a file goes up, and a send carries the ready
  files' ids (ComposerSend.attachments).
- lib/chat/uploads.ts holds the rules the bucket and table also hold: the
  listed types (a type from the extension when the browser gives none),
  10 MB, 5 files.
- Server actions (chat-uploads.ts), which answer { ok, failure } and never
  throw:
  - prepareChatUpload checks the type, the size, Chat on, an active plan
    and the person's own chat. It keeps a pending row
    ({organization_id}/{id}) and gives a one-time upload address.
  - finishChatUpload marks the file ready once it is there.
  - removeChatUpload takes a draft's file and row away.
  - Named in the subscription guard's open actions with why.
- lib/chat/upload-client.ts sends the file to its address. A failure takes
  its row back, so Retry starts over.
- startChatRun takes attachmentIds (up to 5). Each must be the person's
  own, ready and not sent with another message, checked before anything is
  kept; then the files are linked to the message and its chat. Reading
  attachments in the run is CHAT-04's work.
- Server: sweepExpiredChatUploads deletes each attachment past its 90 days,
  file first, then row, in the daily run.
- The preview's home composer attaches files that are "up" after a moment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 30, 2026
The × button unmounts with its chip, so a keyboard user lost their place
(focus fell to the page body). Focus the message box after removing a chip.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A
# Conflicts:
#	web/src/components/chat/composer/chat-composer.tsx
PostgREST reads * as % in like and ilike, so "@price*list" matched
anything between the two words. Strip it with the other pattern
characters.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A
…nswer

A read step whose words aren't "Read …" (the app's own "Opened a page"
from the page router) read no source: it no longer shows as a Data used
chip or as "Reading Opened a page…". The answer's Markdown links only
http(s) addresses (in a new tab) and pages of the app, and shows an
image as its alt text.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A
…hen its bytes are that type

- upload-client: a File goes up as a form part with the browser's type, not
  contentType, so a .md the browser gave no type reached the bucket as
  application/octet-stream and was refused. It now goes up as a File with
  the type the app named.
- finishChatUpload: ready only when the object is there with the type it
  was prepared for, at most 10 MB, and its first 1 KB is that type's
  (contentMatchesType: %PDF-, zip, PNG/JPEG/WebP signatures, no NUL in
  text). The row keeps the bucket's size. A file that fails the check is
  deleted at once instead of waiting 90 days.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A
gkhngyk
gkhngyk previously approved these changes Oct 30, 2026

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good with c373b4d: one fix commit on this branch (6e3bf8b, described below), then a clean merge of the fixed #1827/#1828/#1833 stack.

What the commit fixes

  1. A file the browser gives no type never uploads. uploadToSignedUrl with a File sends it as a form part, and the part's type is the browser's file.type. The contentType option is only used for non-Blob bodies. So a .md (and often .csv or .docx on some systems) goes up as application/octet-stream, and the bucket refuses it. The extension fallback in uploadTypeOf never takes effect. Fix: send new File([file], file.name, { type }). Test: upload-client.test.ts.

  2. finishChatUpload marks a file ready once it exists, without looking at it. 00409 says "ready once the server checked it", and CHAT-04 will read these files as data. The fix checks three things before marking a file ready:

    • the stored object's type is the one it was prepared with;
    • its size is at most 10 MB, and the row keeps the bucket's size rather than the size the browser declared;
    • its first 1 KB matches that type (contentMatchesType in uploads.ts: %PDF-, the zip header for DOCX/XLSX, the PNG/JPEG/WebP signatures, and no NUL byte for the text types). It reads them through a 60-second signed URL with a Range header and a 10 s timeout.

    A file that fails is deleted right away instead of waiting 90 days for the sweep. Tests: chat-uploads.test.ts (2 new cases) and uploads.test.ts.

Optional, not blocking

  • startChatRun checks message_id is null before linking, but the update itself doesn't. If the same ids go out in two sends at once, the second send moves the files onto its own message. Adding .is('message_id', null) to the update, and comparing the returned row count, closes that gap. It only affects the person's own files.
  • Before CHAT_AGENTIC goes on for customers, consider a daily attachment cap per workspace, like IMAGE_UPLOADS_PER_DAY for content images. Attachments don't count toward storage, and they're kept for 90 days.
  • upload-client.ts isn't used by any page yet. Only the preview's fake uploader is wired. That's fine for this step; the follow-up that wires it gets the fixes above.
  • For CHAT-04, which reads these files: treat file text as untrusted data in the prompt, as #1821 does for tool results, and put limits on PDF/DOCX/XLSX parsing (pages, decompressed size, time).

What I checked

  • Actions: sign-in, CHAT_AGENTIC / CHAT_AGENTIC_ORGS per organization, an active plan (the same rule as assertWritable), the person's own chat, type and size. finish/remove only touch the person's own draft (user_id, message_id is null). The OPEN_ACTIONS reasons hold.
  • Engine: at most 5 ids, each checked for the person, the organization, ready and not yet sent, all before anything is saved.
  • Sweep: deletes the object first, then the row, 500 at a time and at most 10,000 a run. It never throws, and a failed delete keeps the row for the next day. It uses chat_uploads_expires_idx.
  • No signed read URLs are added in this PR.
  • Embeds: none added.

Base and merge: stacked on #1833 (1ebd26adc) → #1828 → #1827 → #1826 → #1812. With #1828's current head (602a4e2ef, which carries #1827's fix) merged in, and with current main, it merges cleanly. No new migrations (00407–00413 are #1812's).

Tests run (on take-1834 merged with #1828's and #1833's current fixes and main):

  • web: src/lib/chat, src/components/chat, the chat actions, subscription-guard-coverage, guards/plan-row and the chat pages, 37 files, 488 tests
  • tsc --noEmit, eslint on the touched files
  • server: the sweep and demo coverage, 10 tests

All pass. A rolled-back dry run of 00409 covered linking 5 attachments, refusing a 6th and anything over 10 MB, member, other-workspace and anonymous reads, and the bucket's settings.

gkhngyk added a commit to cihan-gyk/ansvisor that referenced this pull request Oct 30, 2026
gkhngyk added a commit to cihan-gyk/ansvisor that referenced this pull request Oct 30, 2026
…ew fixes) into take-1840

# Conflicts:
#	web/src/app/[locale]/(dashboard)/dashboard/chat/_chat-page-access.ts
#	web/src/components/chat/chat-thread-view.tsx
gkhngyk added a commit to cihan-gyk/ansvisor that referenced this pull request Oct 30, 2026
…svisor#1833 and ansvisor#1834 fixes) into take-1843

# Conflicts:
#	web/src/app/[locale]/(dashboard)/dashboard/chat/_chat-page-access.test.ts
#	web/src/app/[locale]/(dashboard)/dashboard/chat/_chat-page-access.ts
#	web/src/components/chat/chat-thread-view.tsx
#	web/src/components/chat/composer/chat-composer.test.tsx

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Merging in order with the other approved Chat PRs. This head merges current main; where they overlapped, both sides are kept. Its tree is what main will be after this squash, checked with the full server and web suites, tsc, lint, format and next build. Chat stays behind CHAT_AGENTIC.

@gkhngyk
gkhngyk merged commit 42db2fb into ansvisor:main Oct 30, 2026
7 of 9 checks passed
@github-actions github-actions Bot removed the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 30, 2026
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.

2 participants