Skip to content

feat(chat): add Chat's flag, its core tables and the events a run streams - #1758

Merged
gkhngyk merged 7 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-core
Oct 29, 2026
Merged

gkhngyk merged 7 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-core

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

Chat P0, part A1: the flag, Chat's core tables and the events a run streams. This is the foundation for the agentic Chat (Drive › Chat: CHAT-00, CHAT-20 §16c, CHAT-01 9a, CHAT-03, CHAT-24, CHAT-25 §12). Nothing is visible: no table is read while the flag is off, and today's /dashboard/agent keeps working on agent_conversations / agent_messages (00009) as it does now.

Flag (web/src/lib/chat/flag.ts, server/src/lib/chat-flag.js)

  • CHAT_AGENTIC=true turns Chat on. It's read on each request, so it is never baked into the client bundle (not NEXT_PUBLIC_).
  • CHAT_AGENTIC_ORGS (comma-separated organization ids) limits it to those workspaces, so prod can try it on Ansvisor's own workspace only. The list alone never turns it on.
  • A change applies after a restart when self-hosted, or a redeploy on Vercel. The flag is read only from request-time server code.
  • Both .env.example files document it.

Migration 00400 (supabase/migrations/00400_chat_core.sql)

Table What it holds
chat_conversations A chat. brand_id null means it's about the whole workspace. A deleted brand leaves its chats with their author (set null), as agent_conversations does.
chat_messages The person's messages and Chat's answers: the answer only (content_md), generated_at, data_as_of and the time zone. An after-insert trigger moves the chat up Recents (last_message_at).
chat_runs The work behind one answer: status, model, effort, error. Tied to its answer by (message_id, conversation_id), so a run's chat is always its answer's chat.
chat_run_steps The run's steps in order: kind, status, label, detail, scope (names only), row count, data_as_of. Plus server-only tool and debug_json.
chat_step_kinds The 10 step kinds (thinking, read, open_page, skill, check, write, ask, schedule, image, execute). A new kind is a row, not a new check.
chat_user_prefs A person's Chat settings, kept on the server: menu open, where pages open, focus areas (at most 8, each once), model, effort.

Access (RLS)

  • A chat is private to its author while they're in the organization, admins included (CHAT-20 §16c). Messages, runs and steps follow their chat.
  • Members only read; the server writes with the service role.
  • On chat_run_steps, members are granted every column except tool and debug_json, the ai_bot_connections pattern.
    • select('*') as a member fails (42501), so reads use the shared CHAT_RUN_STEP_SELECT.
    • toClientStep() builds what the browser gets, field by field, even from a service-role row.
  • chat_user_prefs: each person reads and writes only their own row.
  • Every pair of tables has one foreign key, so PostgREST embeds are unambiguous.

Events (web/src/lib/chat/events.ts)

  • The run's streamed events from CHAT-00 (step.*, text.delta, ask.created, deliverable.created, confirm.required, next_moves, usage.updated, run.*), plus CHAT-25's deliverable.updated, suggestion.* and page.opened.
  • What reaches the browser carries no tool name, debug data, internal id or money (CHAT-03 fix(ui): link MIT license text in footer to LICENSE file #22, CHAT-04). This is enforced twice:
    • In the types: ChatForbiddenKey, tool / debug / token / latency / money key patterns.
    • At run time: chatEvent() refuses those keys and masks UUIDs in text as …, so a page path like /products/<uuid> doesn't break a run.
  • An optional href lets a card open a draft or file. It accepts only in-app paths under /dashboard/: no absolute URL, //, javascript:, query, hash or ...

Related issue

None (Chat P0, Drive › Chat).

Type of change

  • feat — New feature (behind CHAT_AGENTIC, off by default)

How to test

  1. Deploy: apply 00400. It doesn't depend on 00375 or 00380/00381, which are still open. If migrations are pushed with supabase db push, apply in number order or use --include-all.
  2. Unit tests: cd web && yarn vitest run src/lib/chat/ and cd server && npx vitest run src/lib/chat-flag.test.js.
  3. With the flag off: nothing changes, and /dashboard/agent works as before.

Checklist

  • Branch follows the naming convention
  • Commits follow Conventional Commits
  • bash supabase/build-schema.sh: schema.sql is current
  • Migration 00400 ran on the dev database inside a transaction that was rolled back: no errors, 10 step kinds
  • Server: format, lint, and 280 test files / 3,915 tests (3 skipped) pass
  • Web: lint (0 errors, 7 warnings), typecheck and build pass. Tests: 557 of 558 files; content/editor/[draftId]/_before-publish.test.tsx failed on the focus race that test(content): wait for the dialog's first focus before opening the JSON-LD code #1753 fixes (untouched here)
  • Reviewed before opening: RLS, schema, flag and events. Its findings are in this branch (UUID masking, wider key patterns, href, focus check, Recents trigger, step columns)

🤖 Generated with Claude Code

cihan-gyk and others added 5 commits October 29, 2026 12:51
…eams

The first part of the new Chat (Drive Chat specs, P0 part A1). Nothing
uses it yet, and with the flag off nothing changes: today's
/dashboard/agent keeps its own tables and code.

- CHAT_AGENTIC turns the new Chat on, read on the server at request time
  (web lib/chat/flag.ts, server lib/chat-flag.js), so the same build runs
  with it on or off. CHAT_AGENTIC_ORGS narrows it to listed workspaces.
  Off unless "true", so a self-hosted install sees nothing new.
- 00400 adds chat_conversations, chat_messages, chat_runs, chat_run_steps
  and chat_user_prefs. A chat is private to its author (CHAT-20 §16c):
  only they read it, admins included, and messages, runs and steps follow
  their chat's policies, so sharing with the team can be one more policy
  later. The server writes them; a person writes only their own Chat
  settings (menu, where pages open, focus areas, model, effort), kept on
  the server so they follow them across devices (DECISIONS N3).
- A step's tool and debug record stay with the server: members are
  granted every other column. Step kinds live in chat_step_kinds, so a
  new kind is an inserted row, not a rewritten check.
- web lib/chat/events.ts types every event a run streams (CHAT-00, with
  room for CHAT-25's), names steps by their place in the run, and
  chatEvent() refuses a tool's name, a debug record, an id or a dollar
  amount before an event reaches the browser.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A deleted brand now leaves its chats with their author, as about the
workspace, the way agent_conversations does (00009), rather than
deleting a person's private history with it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nd add app links and the step converter

A uuid in an event's text (a page path, a link the person pasted) no
longer stops the run: chatEvent() shows it as "…". The answer's own text
is still sent as it is, and forbidden keys still throw.

- Forbidden keys are patterns now, in the type (ChatForbiddenKey) and at
  run time alike: any tool key (toolInput, toolResult…) and params; debug,
  tokens and latency; money (usd, price, amount, spend, cost, cents). A
  cost multiplier, a percent and a tooltip still pass.
- Deliverable cards and page.opened get an optional href for their Open
  (CHAT-06, CHAT-25): a path under /dashboard/ only, with no host, query,
  fragment, "//" or ".." part, kept whole by the masking.
- steps.ts holds chat_run_steps' member columns (every one but tool and
  debug_json, checked against the migration's grant) and toClientStep(),
  the one way a stored step reaches the browser: built field by field, so
  a row read with the service role gives up its tool and debug record too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ch new message

- chat_user_prefs.focus holds at most the 8 areas, each once
  (chat_text_array_distinct: a check can't hold a subquery); the model
  column says the server checks it against the catalog before a run.
- A trigger on chat_messages sets its chat's last_message_at (security
  definer, so it reaches the chat whoever writes the message; it never
  moves back).
- The step kinds comment no longer says a kind can be removed: steps
  keep theirs, and there is no index on kind to find out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…y be read

A change applies when the app starts again: a restart when self-hosted,
a new deployment on Vercel. The web flag is for dynamic server code only;
a page rendered at build time would keep the build's value.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… in the database

A message's content_md takes up to 200,000 characters, a step's scope_json
up to 8 KB and its debug_json up to 1 MB as text, so a run that forgets to
shorten a tool's output can't grow a row without limit. Checked now, while
the tables are new, so no later migration has to scan them to add it.

@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 4ef698a: I made one change on top.

What I changed

  • Sizes in the new tables. title, label, detail, origin_page and timezone had length checks, but three columns had none:
    • chat_messages.content_md (a person's message or an answer),
    • chat_run_steps.scope_json,
    • chat_run_steps.debug_json (the tool's input and output, for staff).
  • Nothing writes them yet, but the engine will. A run that forgets to shorten a tool's output could grow a row without limit. Adding a check later means a scan and a lock on a filled table, while adding it now costs nothing. 00400 now has:
    • content_md: at most 200,000 characters;
    • scope_json: at most 8 KB as text (it holds four short names);
    • debug_json: at most 1 MB as text.
  • The engine should cut a large tool output before it writes debug_json. A longer one is refused, so the step insert fails. schema.sql is rebuilt.

What I checked

  • Flag off changes nothing.
    • Nothing in this PR reads chatAgenticEnabled yet. There's no route, page, action or cron.
    • agent_conversations/agent_messages (00009) and /dashboard/agent are untouched.
    • Off unless exactly "true".
    • Both flags are read from process.env at call time. Neither is NEXT_PUBLIC_.
    • With CHAT_AGENTIC_ORGS set, a missing organization id is off.
  • RLS.
    • Every table has RLS on. anon and authenticated lose everything, then get back only:
      • select on chats, messages and runs;
      • select on the step columns except tool and debug_json;
      • select/insert/update on their own chat_user_prefs.
    • A chat is readable only by its author, and only while their profile is in the chat's organization. Messages, runs and steps follow through in (select … from chat_conversations), which runs under the caller's RLS.
    • No member write policy exists on chats, messages, runs or steps, so only the service role writes them.
    • chat_step_kinds has no member access, and the FK check runs as the owner.
  • Functions.
    • chat_touch_last_message is security definer with search_path = '' and qualified names. It only fires from a chat_messages insert, which only the service role can do.
    • chat_text_array_distinct is immutable with no table access.
  • Indexes. They cover Recents (user_id, last_message_at desc), messages by chat, runs by chat, open runs, and steps by run (the unique key). organization_id and brand_id are indexed for the cascades.
  • Idempotence. It uses if not exists, on conflict do nothing, and drop … if exists before each policy and trigger.
  • Events (events.ts, steps.ts).
    • chatEvent() refuses tool, id and money keys and any href outside /dashboard/, including encoded ./.. parts and //.
    • It masks uuids in every string except href and text.delta.
    • toClientStep builds a step field by field, so a service-role row can't leak tool or debug_json.
    • CHAT_RUN_STEP_SELECT lists only the granted columns.
  • Numbering. Nothing on main or in another open PR uses 00400–00449. Only this stack does (00400, 00404).
  • No PostgREST embeds.
  • Tests: lib/chat (events, flag, steps) and chat-flag pass. The full server and web suites pass on the stack merged with main (see #1771).

Follow-ups

  1. chat_user_prefs is written by the member straight through PostgREST. That means no read-only-workspace check applies and model is any 200-character text until the engine checks it against the catalog. Both are fine for a person's own settings, as the PR says.
  2. chat_conversations.brand_id isn't checked against organization_id. The server writes both, so the server needs to keep them consistent.
  3. auth.uid() in the policies isn't wrapped in (select auth.uid()). That's the repo's style everywhere, so there's nothing to change here.

@gkhngyk
gkhngyk merged commit 7131076 into ansvisor:main Oct 29, 2026
4 of 5 checks passed
gkhngyk added a commit to cihan-gyk/ansvisor that referenced this pull request Oct 29, 2026
gkhngyk added a commit to cihan-gyk/ansvisor that referenced this pull request Oct 29, 2026
gkhngyk added a commit to cihan-gyk/ansvisor that referenced this pull request Oct 29, 2026
Keeps main's merged copies of ansvisor#1758, ansvisor#1759, ansvisor#1776, ansvisor#1780, ansvisor#1781 and ansvisor#1786
(request_access's Undo is main's, so 4c7b8cb adds nothing).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-migration Adds or edits a migration — apply it to the hosted database

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants