Skip to content

feat(chat): let Chat update drafts, send CMS drafts, build reports and start audits (W2-07) - #1868

Merged
gkhngyk merged 155 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-w2-07-content-tools
Oct 31, 2026
Merged

gkhngyk merged 155 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-w2-07-content-tools

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

Chat W2-07: Chat can update a draft, send it to a CMS as a draft, build a report and start a Site Audit (CHAT-20, CHAT-25, DECISIONS 5). Stacked on #1866 (W2-06). Behind CHAT_AGENTIC. Every tool is WRITE and needs a Manager or an Admin.

Tool What Undo
update_draft updateContentDraft saves the page first as an agent_before version in History, then runs the editor's own save (same allow-list, agent lock, conflict, sanitizeDraftHtml). If that version can't be saved, nothing is saved. The card shows a short change summary ("Page changes: 2 → 10 words · headings: +"Plans for teams""). 30 days. It goes back to that version only if nobody edited the page since (compare-and-write on updated_at), the Content Agent isn't writing, and the version belongs to this draft and is under 90 days old. The page type follows the restored page.
push_cms_draft sendDraftToCms: Webflow, WordPress, Framer or Wix, as a draft only, through the Send dialog's own steps (stored slug and meta, then /api/content-drafts/send with the person's session). None, and the card says so: Chat can't delete or restore a CMS item.
build_report createReport (4 templates, date range). 30 days: removes the report from Reports.
run_site_audit startSiteAudits: one URL through /api/audits, several through /api/audits/bulk, all within quota or none. None (the audits use quota).

What's deliberately not here

  • No publish tool (EXECUTE). None of the four CMS integrations can publish an item live on the server; they send drafts. The EXECUTE row comes when that capability exists. A test pins that there's no EXECUTE row.
  • No webhook target. A webhook hands the page to the customer's automation, which may publish it, so it's an EXECUTE (CHAT-20 §3). It's refused in the schema and in the action.
  • A live page isn't updated from Chat. If the draft has a published_url, or a send already went live, it returns live_item: "This page is live; send it from the Content Editor." A Framer or Webflow item that went live without being marked can't be known before sending.

Cards and limits

  • Auditing more than one page asks for a card in every mode, counted across the run, so splitting calls doesn't avoid it. The same applies now to W2-06's prompt pauses.
  • costCard counts as always-card. The audit card says how many audits it uses of what's left this month, warns "it won't start" when the quota is short, and uses the API's unique-page rule.
  • Errors map to plain codes. Not connected or a refused key → not_connected. Daily limit → quota_exceeded. A send in progress → conflict. 403 → forbidden_role. 404 → not_found. 400 and 422 → invalid.
  • The new actions check the role themselves and return values, never throw.
  • The Activity log names the CMS ("WordPress").

Help: chat/chat.md, "Drafts, reports and audits".

Decision to note: CHAT-20's row 58 gives push_cms_draft a 7-day Undo that restores the previous CMS draft. The server can neither delete nor restore a CMS item, so this PR has no Undo for it and says so on the card. Revisit when the integrations can.

Follow-up, not in this PR: a full diff card for update_draft; the card shows a summary today.

Merge note: a wip(chat) commit and a merge of W2-06's fixes are on the branch; please squash-merge.

Related issue

None. Chat Wave 2 (W2-07).

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

  1. With CHAT_AGENTIC=true, open Settings › Chat › What Chat can do. There are 4 new rows.
  2. Live runs need a model:
    • "Shorten the intro of the Pricing FAQ draft": the card shows the change summary. Approve it; History has an agent_before version, and Activity log › Undo restores it.
    • "Audit /pricing and /features": a card with the audit count.
    • "Send the draft to WordPress": the card says it can't be undone.
  3. Unit tests:
    • write.test: four tools × roles × modes, brand scope, read-only, the multi-page audit card.
    • undo.test: draft restore, conflicts, the agent writing, another draft's version, 91 days, report removal.
    • engine.test: card notes and targets, cost text, not_connected and live_item.
    • actions/chat-content.test: the real actions — page sent and stored slug, code mapping, webhook refusal, live item, snapshot failure, sanitising, audit routes and quota, role.

Checklist

  • Branch follows the naming convention
  • Commits follow Conventional Commits (one wip commit; squash-merge)
  • yarn lint passes (0 errors; 7 old warnings in files this PR doesn't touch)
  • yarn typecheck passes
  • yarn format:check passes
  • Changes are focused — one concern per PR

Full web suite: 6,981 tests pass. Build: see CI.

🤖 Generated with Claude Code

cihan-gyk and others added 30 commits October 29, 2026 20:41
…gestions

Prompts are grouped under topics, but a brand with none could still add
them: the Add Prompt dialog said "No topics defined yet. Add topics in brand
settings." and saved the prompt without a topic, Track buttons did the same,
and generating suggestions made topics the person never chose from the AI's
labels (findOrCreateTopic).

Server (API):
- POST /api/prompts/suggestions/:brandId/refresh and /:brandId/page answer
  409 { code: 'no_topics' } for a brand with no active topic, after the
  role check and before anything is generated, reserved or written.

Server actions and MCP:
- addPromptToSet (every single add: suggestions, Add All, Insights Track,
  fan-out Track, AI Traffic, People Also Ask) and importPrompts (Add Prompt
  dialog, bulk import) return { error, code: 'no_topics' } and write
  nothing. trackPagePrompts checks before it makes a topic.
- refreshPromptSuggestions returns { ok: false, failure: 'no_topics' } as a
  value; other failures still throw, as before.
- accept_prompt_suggestion says to add a topic first (accept_topic_suggestion
  or Prompts > Topics), and its description says so.
- A failed topics read never counts as "no topics".

UI:
- One TopicFirstDialog / TopicFirstNotice (en.json "topicFirst") with an
  "Add a topic" link to /dashboard/prompts/topics?new=1, which opens Add
  Topic once and clears the param. Buttons stay visible; a click that hits
  no_topics shows it.
- Add Prompt shows the notice instead of the form when the brand has no
  topics; it reads topics on every open, so a topic added meanwhile counts.
- Brand > Manage prompts replaces the old "brand settings" text in both
  cards and asks for a topic instead of adding one without.
- Onboarding and brand setup (savePromptSet) are unchanged: they create the
  chosen topics first. Role gating (ansvisor#1763, ansvisor#1769) is unchanged.

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

Review follow-ups on the topic-first flow.

- Prompts page: "Add a topic" in Add prompt, Suggestions and Query Fan-out
  is a button that closes the dialog, switches to the Topics tab with
  showSection and asks TopicsTab to open Add Topic (openAddTopic /
  onAddTopicOpened). The page reads its tab from the route only when it
  opens, so the ?new=1 link changed the address alone after a tab switch.
  Insights, AI Traffic and the prompt page keep the link.
- Roles: AddTopicLink, TopicFirstNotice and TopicFirstDialog read
  canManage. Since ansvisor#1790 only admins and managers write topics; anyone else
  gets managersOnly.addTopic and no link, and the dialog's button says Close.
- refreshPromptSuggestions returns every failure as a value, as ansvisor#1777's
  reads do (apiFailure + isTransientStatus on the body read once, so
  no_topics stays its own): a used-up budget, a read-only workspace or the
  demo brand, a role refusal, an outage, no answer. The card shows them with
  useFailureToast (the upgrade dialog for subscription) instead of a
  message production hides.
- Brand > Manage prompts links to that brand's own topics
  (/dashboard/brands/:id/topics#add-topic, as the brand card does), not the
  active brand's.
- trackPagePrompts reads active topics only; the AI Traffic page dialog
  forgets a Track's no_topics on the next open; the Insights test has its
  own describe block.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	server/src/routes/prompts-suggestions-refresh.test.js
#	web/src/lib/actions/prompt-suggestions.test.ts
#	web/src/lib/actions/prompt-suggestions.ts
…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]>
CHAT-06 items 30–42, the library W1-25's Download menu will call: an
answer rendered from its stored content_md on the server, with no model
call, nothing stored and no new dependency.

- lib/chat/export.ts reads the answer: Markdown to the Content Editor's
  export blocks (headings, paragraphs with bold, italics and links, lists,
  tables, quotes, code), its tables named by the heading above them, the
  formats Download offers (CSV and Excel only with a table), and the file
  name: the question's slug, or the chat title's past 60 characters, plus
  the day it was generated in its time zone. App links are made whole with
  the app's origin; javascript: and other links are dropped.
- lib/chat/export-file.ts writes the files: Markdown as UTF-8; Word with
  draft-export's docxBlocks; CSV (byte order mark, formula-safe cells),
  and a .zip of one CSV per table when there are several (fflate); Excel
  with one sheet per table and plain numbers as numbers
  (write-excel-file/node, as the traffic export).
- lib/chat/export-pdf.tsx writes the PDF with @react-pdf/renderer on the
  server, Inter embedded from public/fonts so Turkish letters print, links
  clickable, tables as tables, page numbers.
- Every file carries the answer's "Generated … · Data as of …" line
  (item 40): first line of Markdown, Word's and PDF's header and footer,
  the first row of a CSV and of each sheet. The caller words it from
  en.json, as the app shows it under the answer.
- draft-export: docxBlocks and docxDocument are exported, and
  docxDocument takes an optional header and footer line; the Content
  Editor's exports don't change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Behind CHAT_AGENTIC; with it off, the Agent page and its menu link stay as
they are today.

- /dashboard/agent and every path under it answer a 301 to the matching
  /dashboard/chat path, query kept, where the new Chat is on for the
  person's workspace (CHAT-01 item 2). Sent with no-store, so turning the
  flag off again takes effect at once. The sidebar and mobile menu link
  Chat straight to /dashboard/chat.
- The chats API (CHAT-01 §1-3, 7-8, 26): GET /api/chat/conversations lists
  the person's chats and the team's shared ones (or their archived ones),
  newest first, with each row's brand name, dot and live step in words, and
  the Chats / Archived counts; POST starts an empty chat; GET .../{id} opens
  one with its messages and steps; DELETE stops a running agent, then hides
  the chat for everyone; .../restore is the Undo (one minute); .../read
  marks its result read for the author. Refusals come back as values
  (ansvisor#1777), never thrown.
- A chat that isn't there, was deleted or isn't shared says "This chat isn't
  available." with New chat (item 26); opening one marks it read.
- The engine and access requests read chats with the service role, so they
  now leave deleted chats out too (ansvisor#1812 note).
- Help: a "chat" area and its first article (approved: false).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Behind CHAT_AGENTIC; with it off the Chat pages have no frame, as today.

- Every Chat route now sits in a shell (CHAT-01 items 5, 9a-9f; CHAT-23
  G1): the 256px chat menu beside the page and a 52px header with the
  open chat's title and status pill, and the runs tray.
- The menu, top to bottom: the toggle and New chat (Ctrl+Shift+O / ⌘⇧O);
  Menu with Home and the count of what needs the person; Governance with
  Activity, What Chat can do and Tool policy (the governance mockup's
  menu); Agents at work (needs you, running, unread results: three rows,
  See all / Show less, the dots' legend); Chats with its count, Pinned,
  Today, Yesterday, Previous 7 days, Previous 30 days, then by month, in
  the person's own time zone. Rows show the dot, the title (bold while a
  result is unread), the live step or the result's time, or the brand, and
  a teammate's initials on a shared chat. Items whose pages aren't built
  yet stay out (Inbox, Settings, Skills, Integrations, Scheduled, Files,
  Search, All chats, Archived).
- The toggle and Ctrl+\ (⌘\) hide or show the menu and keep the choice on
  the person for every device (chat_user_prefs.menu_open, a server action
  that answers as a value, ansvisor#1777). Hidden, the header starts with a strip:
  toggle, New chat, runs pill. Below 1100px the menu is a drawer that
  leaves the saved choice alone. Ctrl+B stays Bold.
- The list is read from the chats API, again on each page change, every
  5 s while a chat works or waits and every 30 s otherwise.
- Thin, quiet scrollbars for Chat's lists (chat-scroll).
- Help: the chat menu and how to hide it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ete with Undo

Behind CHAT_AGENTIC, like the rest of the Chat shell.

- PATCH /api/chat/conversations/{id} `{ pinned?, title?, shared?,
  archived? }`: the author's own chat only (else 404), a trimmed title of
  1 to 200 characters, answered as a value (ansvisor#1777).
- Each chat row's ⋯ (CHAT-23 chatMenu.rowMore, G9), on hover and focus:
  Open, Open in new window, then for the author Pin / Unpin, Rename,
  Share with team / Stop sharing, Archive, and Delete for the author or an
  Admin on a shared chat. A teammate's shared chat only opens.
- The open chat's ⋯ in the header (G10): Chat settings, Open in new
  window, Pin, Rename (in the title), Share with team, Export chat, Activity
  log, Archive, Delete. Export chat is shown disabled ("Coming soon"):
  wiring it to the answer exports is left to W1-25.
- Rename edits the name in place, in the row or the header: Enter or
  clicking away saves, Esc cancels; double-clicking a row's title starts it.
- Every change shows at once and is then sent; a refused one is put back
  with "Couldn't save that". Archive's toast and Delete's (10 s) carry
  Undo; Delete asks first ("Delete this chat?", focus on Cancel, a red
  Delete), stops a running agent, and leaves the open chat for Chat Home.
- A pinned chat shows the pin where its dot is.
- Help: managing and sharing a chat.

Split view, Pause / Stop run, Schedule this and Save as agent come with
their pages (Wave 2 and 4).

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

Other members' profiles are hidden from the person by their policy, so a
teammate's shared chat showed no initials. Read with the service role,
kept to the person's workspace, for the name only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Behind CHAT_AGENTIC, like the rest of the Chat shell.

- Chat Home (CHAT-01 items 10-12, mockup #s-home): "Good morning /
  afternoon / evening, {first name}" by the person's own clock (switching
  at 12:00 and 18:00; no name, no comma), then one line: "Your agents
  worked while you were away. N things need you." linking to the Inbox, or
  "All caught up.". The composer stays below it.
- The Action Center line (item 12, CHAT-09 item 3): "N Action Center tasks
  are due this week" (singular at 1, hidden at 0): the active brand's open
  actions due by Sunday, overdue ones included, read as the person by a
  server action that answers as a value (ansvisor#1777). Complete with Chat asks
  Chat to complete this week's tasks in a new chat and opens it while the
  run goes on.
- The Inbox at /dashboard/chat/inbox (mockup #s-inbox): what needs the
  person (Review), what runs (its progress, Watch) and unread results
  (Open), with "1 needs you · 1 running · 1 done today"; a row opens its
  chat; one line when empty.
- The chat menu gets Inbox, with its count and an amber dot while
  something needs the person (also beside Menu when folded), and the
  collapsed strip gets an Inbox button, as in the mockup.
- Help: Chat Home and the Inbox.

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]>
Chat Wave 1: lane A's pages (W1-01…05) with lane B's composer and answer
(W1-10…14), merged and joined. The engine's test page goes.

- ChatThreadView (components/chat) carries the test view's run handling:
  send, streaming, reconnecting from the last event, Approve/Skip and
  Stop. ChatComposer and RunAnswer now draw it, with D2's approval and
  denial cards under each answer. Chat Home uses the home composer (2
  rows); an open chat docks it under the messages.
- The composer starts in the person's default mode (chat_user_prefs; a
  saved Full auto the plan no longer opens starts as Auto). Full auto opens
  as the plan facts say (chatComposerSetup).
- Steering stops the run, then sends the text as the next message
  (decided 2026-10-30).
- @ searches the chat's brand (searchChatReferences). Files go up with
  uploadChatFile and go with the message as attachmentIds.
- A teammate's shared chat is read only: the box says so, with Start your
  own chat (loadChatThread's new `mine`).
- The test page's title and box go, with their unused chatPage strings.
- Help: chat.md covers asking, the modes, Stop and steering, shortcuts
  and your data, attaching files, and watching the work.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d pause at the limit

Chat Wave 1, W1-23 (CHAT-04 items 15–17; mockup usgHTML, limHTML), on the
wiring (ddbebf3).

- The composer's line shows the AI usage meter: the header's meter and
  its popover, drawn small by class (ComposerUsageMeter). It is amber from
  80% and red once used up. The free trial shows the meter's own words.
- From 80%, one amber line above the composer, once a period. × closes it
  until the next period (localStorage, by the period's mark).
- At the limit, Chat pauses (chatAtCap: used up, and Chat draws on the
  allowance). The red AI usage banner shows above the composer, with
  where to get more, or "ask an Admin" for other members. The box is off:
  "AI limit reached · models on your own key still work", or "Your trial
  AI limit is used up". On the workspace's own key Chat keeps working.
- A teammate's shared chat shows none of it.
- Help: chat.md's AI usage section.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
On a person's first visit to Chat (CHAT_AGENTIC on), their Agent Chat
conversations in their workspace are copied into chat_conversations and
chat_messages with the same ids, so old chats sit in Recents by their
last message and open at /dashboard/chat/{id}. Questions and answers in
words are kept; tool rows, tool-only answers and empty conversations are
not. The default title "New conversation" becomes "New chat".

Once per person: chat_user_prefs.legacy_imported_at (00408) is set only
after a complete copy, so a copy that failed is tried again next visit.
Already-copied ids are left alone (upsert ignoring duplicates), so two
visits at once or a second run change nothing. It never throws and never
keeps Chat from opening; the old tables are only read.

The test fake learns upsert, range and ordering by several columns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Search chats (CHAT-01 item 6; CHAT-23 G2): GET
/api/chat/conversations/search finds the person's chats and the team's
shared ones whose title or messages hold every word typed (00407's
search_tsv, 'simple' configuration, words as prefixes), newest first;
`view=archived` searches their own archived chats. Input is cut to
letters and digits, so no operator reaches Postgres.

- The chat menu gets the Search chats field under Chats: typing lists the
  matches in place of the days, with "No chats match." and Clear filters.
  All chats · {n} › and Archived · {n} › close the list.
- Ctrl K (⌘K) opens the palette (mockup #msearch) under Search chats, or
  under the strip's new Search button while the menu is hidden; again
  closes it. New chat, the latest or matching chats and the Chat pages
  by name; arrows and Enter, Enter opens the first match or a new chat.
- All chats (/dashboard/chat/all, mockup #s-allchats): Active and Archived
  tabs with counts, search over names and messages, filters All, Running,
  Needs you, Done, Mine and Team, and Archive selected / Unarchive
  selected for the person's own chats, with one toast.
- Archive's toast now says "Archived · find it in All chats › Archived";
  it is brought back from All chats › Archived (CHAT-23 chat.archive).

Help: new help/chat/all-chats.md, chat.md updated. Popover passes an
anchor through; the test fake learns textSearch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…l beside Chat

Chat Settings › General (/dashboard/chat/settings, mockup #s-settings;
CHAT-23 chatSettings.*): default mode, answer language, notifications,
"Thought for N s" and Ask Chat on every page, kept on chat_user_prefs
(00408) at once and put back when refused. A new server action,
saveChatGeneralSettings, checks each change against the person: no mode
for Analysts and Agency partners, Full auto only on a paid Growth plan
and where the Admin leaves it on for members (it says why when locked),
Inbox + Slack only once Slack connects (not yet). It never throws (ansvisor#1777).
Settings sits in the chat menu under Inbox with the month's AI usage in
percent, in the Ctrl K palette, and in the header ⋯ (Chat settings).

Navigation (CHAT-01 4b, 4e, 4f; CHAT-23 nav.*, rail.toggle):
- Inbox, All chats, Activity and What Chat can do show ← Back to Chat
  and the "Chat › {page}" breadcrumb; Back to Chat returns to the last
  conversation open in this tab, or Chat Home. Settings shows its name.
- Esc closes only the topmost layer and never navigates (covered by tests).
- On Chat's screens the app sidebar is the rail; the logo expands and
  collapses it, kept on the person (chat_user_prefs.rail_open) through a
  new saveChatRailOpen action. Elsewhere, and with the flag off, the
  sidebar keeps its own pinned state and the logo still goes home.

Help: new help/chat/chat-settings.md; chat.md gets "Move around Chat".

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

Ask Chat sits at the top right of every page header (after the AI usage
meter) and Ctrl J / ⌘J opens and closes the panel from anywhere, a page
input included; on Chat's routes the key focuses the composer, and the
Content Editor is left to its own Chat. The panel hosts the chat view
(panel variant, the page's address stays) with New chat, History,
Compact / Wide / Full screen and Close; from 1100px a compact or wide
panel pushes the page aside, narrower and in full screen it overlays,
below 760px it is full width with ← back to the page. It greets the
person when empty and reopens its last chat used in the last 30 minutes.
The layout reads panel_on_pages and panel_size (00408); the panel keeps
its last size on the person.

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

Creating an empty chat, deleting, restoring and marking your own chat read
start no cost; a chat's first message is a run, which the engine refuses
with 402. The read-only coverage test lists them with that reason.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
gkhngyk and others added 11 commits October 30, 2026 17:57
…ake-1865

# Conflicts:
#	web/src/components/chat/chat-thread-view.test.tsx
… and stop a Run now that lands after Archive

An Admin's change to a Manager's agent that is on now checks Full auto
against the owner too, since its triggered runs act as the owner (as Resume
does). A Run now whose insert lands after Archive has stopped the queue now
reads the agent again and stops its run as Archive does.
…ns, and say what an Undo can't bring back

From the review of Chat's setup writes:

- pause_prompts' run cap is 50 prompts, as its row takes them; it stopped
  at the default 10.
- The setup actions refuse anyone but an Admin or a Manager themselves
  (isManager, as deleteTopic does). The competitors table lets every member
  in.
- add_prompts takes its topic by id (ImportPromptRow.topicId), never by a
  name another topic, paused or not, may share. rename_topic goes through
  renameBrandTopic: a value back, active topics only, a name taken refused.
- pauseBrandPrompts pauses only the brand's active prompts among the ids,
  says which, and refuses when none was.
- Undo:
  - a topic's prompts it paused don't hold it;
  - resuming prompts on a full plan says quota_exceeded in the plan's
    words, changes nothing, and can be tried again;
  - a competitor brought back opens its actions' links again, and is
    compared by domain (scheme, www and case aside) or, without one, name.
- The remove-competitor card, its Undo line and Help say its timeline events
  don't come back. Undoing new prompts keeps their first answers and cost.
- Tests:
  - the real actions against a member's client (another brand's objects,
    duplicates, partial and quota, roles);
  - another workspace's topic or brand refused (brand_scope);
  - 12 prompts paused from a card.

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

# Conflicts:
#	web/messages/en.json
#	web/src/components/chat/chat-thread-view.tsx
#	web/src/lib/chat/engine.ts
#	web/src/lib/chat/events.ts
… from Chat

This commit and the wip commit before it make up W2-07 (CHAT-20 §9 rows
37, 55, 58, 64).

New WRITE rows, one registry file per area:
- update_draft: History keeps the page before ('agent_before'), then it
  saves as the editor saves. Undo restores that version, 30 days.
- push_cms_draft: the page made ready as the Library's bulk send makes it
  (readCmsSources, moved to lib/content, and bulkCmsItems), sent through the
  API's own send as the member: Webflow, WordPress, Framer, Wix or the
  webhook, as a draft there. No Undo, and its card says so.
- build_report: createReport, from a template over a period. Undo takes it
  out of Reports, 30 days.
- run_site_audit: one page, or several as the Pages tab's Re-audit, against
  the month's quota. Several always show a card, with what they use of the
  month (cost card). No Undo.

Rules:
- Admins and Managers (DECISIONS T); the new actions check it themselves.
- An Analyst's Chat still only saves drafts.
- Going live in a CMS (publish_cms) has no row: no CMS the app sends to can
  be published from it yet.

Engine: a WRITE with no Undo says so on its card (noUndo, beside the row's
own note). not_connected and conflict come back in the action's words.

Help: chat.md "Drafts, reports and audits".

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

# Conflicts:
#	web/src/lib/chat/engine.test.ts
# Conflicts:
#	web/messages/en.json
…to take-1866

# Conflicts:
#	web/src/lib/actions/prompt.ts
…itor rows to plans with competitor tracking

The who-may-do-what matrix lists every change the registry has, so the six
new rows take their place: Admins and Managers only, on a card outside Full
auto, and removing a competitor on a card in every mode. Adding or removing
competitors now names the Competitors page's plan feature, as the page does.
…split calls, and make draft Undo safe

- push_cms_draft no longer sends to the brand's webhook (it goes out of
  Ansvisor), and refuses a page that is live (live_item).
- sendDraftToCms checks the role and maps the API's 403/400/422/404 and
  refused-connection answers; the content actions answer failures as values.
- A batch row's card counts the run's earlier items; run_site_audit's
  cost card shows in every mode, with unique pages, a won't-start warning
  and a line when the quota can't be read.
- updateContentDraft saves nothing when the page before can't be kept;
  its card summarizes the change to words and headings.
- update_draft's Undo leaves a page the agent is writing, restores only
  this draft's version over the page it read, and re-detects the type.
- Activity names the CMS; a card shown again keeps its notes and cost.

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
cihan-gyk and others added 4 commits October 30, 2026 20:41
addTopicPrompts, pauseBrandPrompts, addBrandTopic, renameBrandTopic,
addCompetitors and removeBrandCompetitor now check the plan first inside a
try, and any throw on the way (the role read included) comes back as
{ ok: false, reason: 'failed' } (ansvisor#427).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…into feature/chat-w2-07-content-tools

# Conflicts:
#	web/messages/en.json
#	web/src/lib/chat/engine.test.ts
#	web/src/lib/chat/testing/fake-supabase.ts
The matrix test asks every WRITE or EXECUTE row to take its place, and
W2-06's setup rows came in with the merge. update_draft, push_cms_draft,
build_report and run_site_audit are Managers' and up, like those rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

Brought #1866's latest head in: your 618eab7 (with #1864 and #1808) and our 0b7f36b, now 229e330.

Conflicts. Both sides added lines in three places, and I kept both:

  • en.json: the content and agent labels, with the duplicate accessDenied dropped;
  • engine.test.ts: the action imports;
  • fake-supabase.ts: or() together with your fts comment.

One follow-on commit, 7f191da. W2-07's four rows join the role matrix ("covers every change the registry has"): update_draft, push_cms_draft, build_report and run_site_audit. All four are Managers and up, like the setup rows.

Checks:

  • typecheck clean;
  • Chat, actions and chat components: 165 files, 1,682 tests pass;
  • chat-setup and subscription-guard-coverage pass after the second merge.

Conflicts resolved by applying ansvisor#1868's own diff (from its W2-06 base 0b7f36b) onto main; kept both sides in the help/chat/chat.md keywords and the engine.ts imports.
…ry fast

A page sent to a CMS leaves Ansvisor and has no Undo, and an item updated in
Framer or Webflow goes live with the site's next publish. push_cms_draft now
shows its card in every mode, Full auto included, and its policy tops out at
Ask, so an Admin's Always can't lift it. This matches the help's "Nothing is
published or sent without your click".

update_draft's card summary read the page with lazy matches up to a closing
tag; a page of unclosed tags took tens of seconds. The scan now only goes
forward and stays linear.

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 9fbab0e: current main merged in (this PR's own diff on top of main's squashes of its base PRs) and one fix commit, described below.

Fixes (on this branch)

1. A CMS send always asks, Full auto included. push_cms_draft was ask_full_auto with maxPolicy: 'always', so in Full auto, or under an Admin's Always, a page went to Webflow, WordPress, Framer or Wix with no card. That send leaves Ansvisor and has no Undo (as the PR says). Also, an item that a previous send made and someone later published in Framer or Webflow is updated in place and goes live with the site's next publish. The Help page also says "Nothing is published or sent without your click".

  • The row is now alwaysCard, with defaultPolicy and maxPolicy both 'ask'. It gets a card in every mode, never offers "Don't ask again", and a stored Always is held to Ask.
  • New case in write.test: Admins and Managers get always_card in all three modes, even with an Admin's Always stored for the tool. Analysts are refused. The brand-scope and read-only case now covers push_cms_draft too.
  • The Help sentence now says sending always asks first, even in Full auto, and can't be undone from Chat (the section stays under the 150-word limit).

2. update_draft's card summary stays fast on any page. pageChanges scanned the page with lazy matches up to a closing tag ([\s\S]*?<\/h\1>, <(script|style)\b[\s\S]*?<\/\1>), and <[^>]*> for tags. On a page of unclosed tags that's quadratic: 200k characters took about 60 seconds in the test, and the input allows 500k. It runs while the card is being built. The scan now only searches forward (one indexOf per block, and a tag with no close is skipped from then on), and tags are matched with <[^<>]*>. The new registry/targets.test.ts checks the summary's words and headings, and that five pathological 200k pages finish in under a second each.

What we checked

  • Every row goes through the same path. All four are class: 'write'. They run only through decideOrDeny / the precedence, then runLoggedWrite, which handles the log row, Undo and the idempotency key.
    • run_site_audit is costCard with maxPolicy: 'ask'. That's a card in every mode, showing what it uses of the month's audits. defineTool refuses a costCard row that could go past Ask.
    • A run that read outside text (§16a) still gets a card for update_draft and build_report (step 7). The other two always ask anyway.
    • The run cap and the more-than-five card count items across the run's earlier calls of the same row (before). So splitting calls doesn't avoid either.
    • There's no EXECUTE row. The webhook target is refused in both the schema and the action.
  • Who may do it (#1858's matrix). All four rows are in CHANGES with minRole: 'manager'. Analysts and Agency partners aren't offered them, and the guard test passes. Each action also checks isManager itself. The CMS send also goes through the API's own sender check (Admins and Managers).
  • Same server rules as the app.
    • Read-only workspaces: every action calls assertWritable first ({ brandId } for reports and audits).
    • Demo brand: Chat's precedence refuses it for all four (brandOf). For direct calls, the API's demo guard covers /content-drafts/send and /audits(/bulk), the demo trigger covers content_drafts and its versions, and createReport / startSiteAudits pass the brand to assertWritable.
    • The CMS connection, its daily limit and the send-in-progress lock are the API's, reached with the member's own session.
    • The audit quota is the API's, all-or-none for several pages. getAuditQuota only words the card.
  • Ids stay inside the brand.
    • update_draft and push_cms_draft take their brand from the draft row (brandOf: lookup content_drafts). Reports and audits use brand_id from the input. A draft or brand of another workspace is refused with brand_scope (tested for all four).
    • The actions read through the member's client (RLS).
    • Card targets read titles only after the precedence has accepted the brand.
    • Undo filters by the logged brand id.
  • What goes to the CMS is cleaned. Chat can't hand HTML to a CMS. sendDraftToCms reads the stored page, which was sanitized on save, and builds it the way the Library's bulk send does (readCmsSources, bulkCmsItems: the slug and meta it kept, author, placeholders and length checks). update_draft saves through saveContentDraft, so it gets the same sanitizeDraftHtml, allow-list, agent lock and conflict check as the editor.
  • Undo.
    • update_draft goes back to the agent_before version only if the page hasn't changed since (title and hash, plus compare-and-write on updated_at), the agent isn't writing, the version belongs to this draft and it's under 90 days old. It keeps the page as it is first, as content_draft_restore does. If the version can't be kept, nothing is saved.
    • build_report removes the report.
    • The CMS send and audits record what they did, with no Undo, and their card says so (noUndo).
  • Embeds: content_drafts → brands(name, language) in sendDraftToCms and BRAND_SITE (moved, unchanged). There's one FK between the two tables (content_drafts.brand_id), so no hint is needed.
  • Build check: lib/guards/plan-row.test.ts passes. The only client file touched is _bulk-send-dialog.tsx, where only the import path of readCmsSources changed.

Follow-ups (not blocking)

  1. The Manager switch for going live. As a WRITE, a CMS send from Chat isn't covered by an Admin's "Managers can't publish" switch in Settings › Chat (manager_execute_off: publishing). If that switch should also stop Managers' CMS sends from Chat, the row would become an EXECUTE in publishing. It now always asks, so this is a product choice, not a gap.
  2. build_report takes any period (only date_from <= date_to). A maximum span in the schema would keep a model's typo from gathering years of data.
  3. Undo of build_report deletes the report even if it was shared or renamed since. A check for "unchanged and not shared" would match how the other Undos return changed.
  4. Your own follow-up: a full diff card for update_draft.

Base and merge

this branch = this PR's head 229e330ad + current origin/main (703a68600), then the fixes.

  • Main now has W2-06 (and the rest of the stack) as squashes, so a plain merge conflicts in about 50 files that this PR doesn't change. I resolved it by applying this PR's own diff (from 0b7f36be1) onto main.
  • Only two real overlaps came up, and I kept both sides in each: the Help keywords in help/chat/chat.md (main's retry, error, reconnecting, plus this PR's words) and the imports in engine.ts (main's scope / tool-cache / untrusted imports, plus undoRule).
  • After that, it merges cleanly on current main.

Tests

Run on this branch:

  • All Chat dirs (lib/chat, components/chat, the chat pages), actions/chat-content.test.ts, the Content Library tests, lib/guards/plan-row.test.ts and subscription-guard-coverage.test.ts: 94 files, 1,336 tests, all pass. Without the fixes, the new write.test case and the timing case fail (the latter took 62 s).
  • Full web suite: 7,667 tests in 758 files, all pass. The first run caught my Help sentence pushing its section over the 150-word limit (help/validate.test), so I shortened it and the Help tests pass again.
  • tsc --noEmit, plus eslint and prettier on the changed files: clean.

@github-actions github-actions Bot removed the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 30, 2026
push_cms_draft leaves Ansvisor, so it is now an EXECUTE in the publishing
group instead of an always-card WRITE. It still runs only on the person's
click, in every mode, Full auto included, and no Admin "Always" lifts it.
An Admin's "Managers can't go live" switch for publishing now stops a
Manager's send too: the row isn't offered to that Manager, the explainer
gives the usual policy refusal, and a click on a card opened before the
switch changed is refused when the run resumes. Analysts and Agency
partners still aren't offered it.

sendDraftToCms checks the same switch itself, on the member's own client,
since a server action can be called without Chat. An EXECUTE's undo rule
only records, so the Activity log still names the draft and the CMS, with
no Undo, and the card still says it can't be undone.

The help says the send waits for a click and what the switch does.

@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.

Approving again with 4f82327: one commit on top, described below.

fix(chat): make the CMS send an EXECUTE in the publishing group

  • push_cms_draft is now class: 'execute', executeGroup: 'publishing', in place of the always-card WRITE. It still runs only on the person's click, in every mode including Full auto, and an Admin's stored "Always" doesn't lift it, because an EXECUTE is always a click.
  • The "Managers can't go live" switch now covers it. When an Admin turns publishing off for Managers:
    • Chat doesn't offer the row to a Manager.
    • The explainer gives the standard execute_off refusal ("An Admin turned publishing off for Managers.").
    • A card opened before the switch changed is refused when the click resumes the run, because the engine decides again on fresh settings.
    • Admins still get the card. Analysts and Agency partners are still not offered it.
  • sendDraftToCms checks the same switch itself, on the member's own client, since a server action can be called without Chat. If the switch is off for a Manager it returns execute_off. That reason maps through SAID_FAILURES.
  • undoRule now returns a record-only rule (window 0) for an EXECUTE. The Activity log still names the draft and the CMS, with no Undo, and the card still says it can't be undone.
  • Help (help/chat/chat.md): the send waits for a click, and Managers can't send from Chat when publishing is off for them. The section stays under 150 words.

Tests:

  • Admin and Manager: a click card in every mode, even with "Always" stored.
  • Manager with publishing off: refused, not offered, and the explainer's words. A different group being off doesn't block the send.
  • Admin with publishing off: still clicks through, and the page is sent.
  • A click after the switch turned off while the card waited: refused.
  • Analyst and Agency partner: not offered and no card, in every mode.
  • The Activity row: execute, click, no Undo.
  • The action's own refusal.

The new tests fail on the previous head. vitest passes on chat, chat-access, chat pages, guards, help, actions, content pages, subscription-guard-coverage, demo-gate-routes and plan-row. The only failure is the known flaky clock case in chat-menu. tsc, eslint and prettier are clean.

@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 PRs. This head merges current main; its tree is what main will be after this squash, checked with the full server and web suites, tsc, lint, format and next build.

@gkhngyk
gkhngyk merged commit a647803 into ansvisor:main Oct 31, 2026
3 of 5 checks passed
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